blob: eec0b774cf6894cef9e26f669a7c6f3577af1b09 [file] [log] [blame]
Douglas Gregor86e04682013-09-27 21:23:28 +00001=======
2Modules
3=======
Douglas Gregora2b3d582013-03-20 06:25:14 +00004
Sean Silvac9fd1862013-03-20 18:37:42 +00005.. warning::
Douglas Gregor86e04682013-09-27 21:23:28 +00006 The functionality described on this page is supported for C and
7 Objective-C. C++ support is experimental.
Sean Silvac9fd1862013-03-20 18:37:42 +00008
Sean Silva9522ae12013-09-09 19:57:49 +00009.. contents::
10 :local:
11
Douglas Gregora2b3d582013-03-20 06:25:14 +000012Introduction
13============
14Most software is built using a number of software libraries, including libraries supplied by the platform, internal libraries built as part of the software itself to provide structure, and third-party libraries. For each library, one needs to access both its interface (API) and its implementation. In the C family of languages, the interface to a library is accessed by including the appropriate header files(s):
15
16.. code-block:: c
17
18 #include <SomeLib.h>
19
20The implementation is handled separately by linking against the appropriate library. For example, by passing ``-lSomeLib`` to the linker.
21
22Modules provide an alternative, simpler way to use software libraries that provides better compile-time scalability and eliminates many of the problems inherent to using the C preprocessor to access the API of a library.
23
Douglas Gregor5529e3e2013-03-22 07:05:07 +000024Problems with the current model
Douglas Gregora2b3d582013-03-20 06:25:14 +000025-------------------------------
26The ``#include`` mechanism provided by the C preprocessor is a very poor way to access the API of a library, for a number of reasons:
27
28* **Compile-time scalability**: Each time a header is included, the
29 compiler must preprocess and parse the text in that header and every
30 header it includes, transitively. This process must be repeated for
31 every translation unit in the application, which involves a huge
32 amount of redundant work. In a project with *N* translation units
33 and *M* headers included in each translation unit, the compiler is
34 performing *M x N* work even though most of the *M* headers are
35 shared among multiple translation units. C++ is particularly bad,
36 because the compilation model for templates forces a huge amount of
37 code into headers.
38
39* **Fragility**: ``#include`` directives are treated as textual
40 inclusion by the preprocessor, and are therefore subject to any
41 active macro definitions at the time of inclusion. If any of the
42 active macro definitions happens to collide with a name in the
43 library, it can break the library API or cause compilation failures
44 in the library header itself. For an extreme example,
45 ``#define std "The C++ Standard"`` and then include a standard
46 library header: the result is a horrific cascade of failures in the
47 C++ Standard Library's implementation. More subtle real-world
48 problems occur when the headers for two different libraries interact
49 due to macro collisions, and users are forced to reorder
50 ``#include`` directives or introduce ``#undef`` directives to break
51 the (unintended) dependency.
52
53* **Conventional workarounds**: C programmers have
54 adopted a number of conventions to work around the fragility of the
55 C preprocessor model. Include guards, for example, are required for
56 the vast majority of headers to ensure that multiple inclusion
57 doesn't break the compile. Macro names are written with
58 ``LONG_PREFIXED_UPPERCASE_IDENTIFIERS`` to avoid collisions, and some
59 library/framework developers even use ``__underscored`` names
60 in headers to avoid collisions with "normal" names that (by
61 convention) shouldn't even be macros. These conventions are a
62 barrier to entry for developers coming from non-C languages, are
63 boilerplate for more experienced developers, and make our headers
64 far uglier than they should be.
65
66* **Tool confusion**: In a C-based language, it is hard to build tools
67 that work well with software libraries, because the boundaries of
68 the libraries are not clear. Which headers belong to a particular
69 library, and in what order should those headers be included to
70 guarantee that they compile correctly? Are the headers C, C++,
71 Objective-C++, or one of the variants of these languages? What
72 declarations in those headers are actually meant to be part of the
73 API, and what declarations are present only because they had to be
74 written as part of the header file?
75
Douglas Gregor5529e3e2013-03-22 07:05:07 +000076Semantic import
Douglas Gregora2b3d582013-03-20 06:25:14 +000077---------------
78Modules improve access to the API of software libraries by replacing the textual preprocessor inclusion model with a more robust, more efficient semantic model. From the user's perspective, the code looks only slightly different, because one uses an ``import`` declaration rather than a ``#include`` preprocessor directive:
79
80.. code-block:: c
81
82 import std.io; // pseudo-code; see below for syntax discussion
83
84However, this module import behaves quite differently from the corresponding ``#include <stdio.h>``: when the compiler sees the module import above, it loads a binary representation of the ``std.io`` module and makes its API available to the application directly. Preprocessor definitions that precede the import declaration have no impact on the API provided by ``std.io``, because the module itself was compiled as a separate, standalone module. Additionally, any linker flags required to use the ``std.io`` module will automatically be provided when the module is imported [#]_
85This semantic import model addresses many of the problems of the preprocessor inclusion model:
86
87* **Compile-time scalability**: The ``std.io`` module is only compiled once, and importing the module into a translation unit is a constant-time operation (independent of module system). Thus, the API of each software library is only parsed once, reducing the *M x N* compilation problem to an *M + N* problem.
88
89* **Fragility**: Each module is parsed as a standalone entity, so it has a consistent preprocessor environment. This completely eliminates the need for ``__underscored`` names and similarly defensive tricks. Moreover, the current preprocessor definitions when an import declaration is encountered are ignored, so one software library can not affect how another software library is compiled, eliminating include-order dependencies.
90
91* **Tool confusion**: Modules describe the API of software libraries, and tools can reason about and present a module as a representation of that API. Because modules can only be built standalone, tools can rely on the module definition to ensure that they get the complete API for the library. Moreover, modules can specify which languages they work with, so, e.g., one can not accidentally attempt to load a C++ module into a C program.
92
Douglas Gregor5529e3e2013-03-22 07:05:07 +000093Problems modules do not solve
Douglas Gregora2b3d582013-03-20 06:25:14 +000094-----------------------------
95Many programming languages have a module or package system, and because of the variety of features provided by these languages it is important to define what modules do *not* do. In particular, all of the following are considered out-of-scope for modules:
96
97* **Rewrite the world's code**: It is not realistic to require applications or software libraries to make drastic or non-backward-compatible changes, nor is it feasible to completely eliminate headers. Modules must interoperate with existing software libraries and allow a gradual transition.
98
99* **Versioning**: Modules have no notion of version information. Programmers must still rely on the existing versioning mechanisms of the underlying language (if any exist) to version software libraries.
100
101* **Namespaces**: Unlike in some languages, modules do not imply any notion of namespaces. Thus, a struct declared in one module will still conflict with a struct of the same name declared in a different module, just as they would if declared in two different headers. This aspect is important for backward compatibility, because (for example) the mangled names of entities in software libraries must not change when introducing modules.
102
Douglas Gregor03d262b2013-03-20 17:11:13 +0000103* **Binary distribution of modules**: Headers (particularly C++ headers) expose the full complexity of the language. Maintaining a stable binary module format across architectures, compiler versions, and compiler vendors is technically infeasible.
Douglas Gregora2b3d582013-03-20 06:25:14 +0000104
105Using Modules
106=============
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000107To enable modules, pass the command-line flag ``-fmodules`` [#]_. This will make any modules-enabled software libraries available as modules as well as introducing any modules-specific syntax. Additional `command-line parameters`_ are described in a separate section later.
Douglas Gregora2b3d582013-03-20 06:25:14 +0000108
Douglas Gregor86e04682013-09-27 21:23:28 +0000109Objective-C Import declaration
110------------------------------
111Objective-C provides syntax for importing a module via an *@import declaration*, which imports the named module:
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000112
113.. parsed-literal::
114
Douglas Gregor86e04682013-09-27 21:23:28 +0000115 @import std;
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000116
Douglas Gregor86e04682013-09-27 21:23:28 +0000117The @import declaration above imports the entire contents of the ``std`` module (which would contain, e.g., the entire C or C++ standard library) and make its API available within the current translation unit. To import only part of a module, one may use dot syntax to specific a particular submodule, e.g.,
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000118
119.. parsed-literal::
120
Douglas Gregor86e04682013-09-27 21:23:28 +0000121 @import std.io;
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000122
123Redundant import declarations are ignored, and one is free to import modules at any point within the translation unit, so long as the import declaration is at global scope.
124
Douglas Gregor86e04682013-09-27 21:23:28 +0000125At present, there is no C or C++ syntax for import declarations. Clang
126will track the modules proposal in the C++ committee. See the section
127`Includes as imports`_ to see how modules get imported today.
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000128
129Includes as imports
Douglas Gregora2b3d582013-03-20 06:25:14 +0000130-------------------
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000131The primary user-level feature of modules is the import operation, which provides access to the API of software libraries. However, today's programs make extensive use of ``#include``, and it is unrealistic to assume that all of this code will change overnight. Instead, modules automatically translate ``#include`` directives into the corresponding module import. For example, the include directive
Douglas Gregora2b3d582013-03-20 06:25:14 +0000132
133.. code-block:: c
134
135 #include <stdio.h>
136
Douglas Gregor03d262b2013-03-20 17:11:13 +0000137will be automatically mapped to an import of the module ``std.io``. Even with specific ``import`` syntax in the language, this particular feature is important for both adoption and backward compatibility: automatic translation of ``#include`` to ``import`` allows an application to get the benefits of modules (for all modules-enabled libraries) without any changes to the application itself. Thus, users can easily use modules with one compiler while falling back to the preprocessor-inclusion mechanism with other compilers.
Douglas Gregora2b3d582013-03-20 06:25:14 +0000138
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000139.. note::
140
141 The automatic mapping of ``#include`` to ``import`` also solves an implementation problem: importing a module with a definition of some entity (say, a ``struct Point``) and then parsing a header containing another definition of ``struct Point`` would cause a redefinition error, even if it is the same ``struct Point``. By mapping ``#include`` to ``import``, the compiler can guarantee that it always sees just the already-parsed definition from the module.
142
143Module maps
Douglas Gregora2b3d582013-03-20 06:25:14 +0000144-----------
145The crucial link between modules and headers is described by a *module map*, which describes how a collection of existing headers maps on to the (logical) structure of a module. For example, one could imagine a module ``std`` covering the C standard library. Each of the C standard library headers (``<stdio.h>``, ``<stdlib.h>``, ``<math.h>``, etc.) would contribute to the ``std`` module, by placing their respective APIs into the corresponding submodule (``std.io``, ``std.lib``, ``std.math``, etc.). Having a list of the headers that are part of the ``std`` module allows the compiler to build the ``std`` module as a standalone entity, and having the mapping from header names to (sub)modules allows the automatic translation of ``#include`` directives to module imports.
146
Stephen Hines651f13c2014-04-23 16:59:28 -0700147Module maps are specified as separate files (each named ``module.modulemap``) alongside the headers they describe, which allows them to be added to existing software libraries without having to change the library headers themselves (in most cases [#]_). The actual `Module map language`_ is described in a later section.
Douglas Gregora2b3d582013-03-20 06:25:14 +0000148
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000149.. note::
150
151 To actually see any benefits from modules, one first has to introduce module maps for the underlying C standard library and the libraries and headers on which it depends. The section `Modularizing a Platform`_ describes the steps one must take to write these module maps.
Daniel Jasper056ec122013-08-05 20:26:17 +0000152
153One can use module maps without modules to check the integrity of the use of header files. To do this, use the ``-fmodule-maps`` option instead of the ``-fmodules`` option.
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000154
155Compilation model
Douglas Gregora2b3d582013-03-20 06:25:14 +0000156-----------------
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000157The binary representation of modules is automatically generated by the compiler on an as-needed basis. When a module is imported (e.g., by an ``#include`` of one of the module's headers), the compiler will spawn a second instance of itself [#]_, with a fresh preprocessing context [#]_, to parse just the headers in that module. The resulting Abstract Syntax Tree (AST) is then persisted into the binary representation of the module that is then loaded into translation unit where the module import was encountered.
Douglas Gregora2b3d582013-03-20 06:25:14 +0000158
159The binary representation of modules is persisted in the *module cache*. Imports of a module will first query the module cache and, if a binary representation of the required module is already available, will load that representation directly. Thus, a module's headers will only be parsed once per language configuration, rather than once per translation unit that uses the module.
160
161Modules maintain references to each of the headers that were part of the module build. If any of those headers changes, or if any of the modules on which a module depends change, then the module will be (automatically) recompiled. The process should never require any user intervention.
162
163Command-line parameters
164-----------------------
165``-fmodules``
166 Enable the modules feature (EXPERIMENTAL).
167
168``-fcxx-modules``
169 Enable the modules feature for C++ (EXPERIMENTAL and VERY BROKEN).
170
Daniel Jasper056ec122013-08-05 20:26:17 +0000171``-fmodule-maps``
172 Enable interpretation of module maps (EXPERIMENTAL). This option is implied by ``-fmodules``.
173
Douglas Gregora2b3d582013-03-20 06:25:14 +0000174``-fmodules-cache-path=<directory>``
175 Specify the path to the modules cache. If not provided, Clang will select a system-appropriate default.
176
Daniel Dunbarf4910132013-04-16 18:21:19 +0000177``-fno-autolink``
178 Disable automatic linking against the libraries associated with imported modules.
Douglas Gregora2b3d582013-03-20 06:25:14 +0000179
180``-fmodules-ignore-macro=macroname``
181 Instruct modules to ignore the named macro when selecting an appropriate module variant. Use this for macros defined on the command line that don't affect how modules are built, to improve sharing of compiled module files.
182
Douglas Gregord44d2872013-03-25 21:19:16 +0000183``-fmodules-prune-interval=seconds``
184 Specify the minimum delay (in seconds) between attempts to prune the module cache. Module cache pruning attempts to clear out old, unused module files so that the module cache itself does not grow without bound. The default delay is large (604,800 seconds, or 7 days) because this is an expensive operation. Set this value to 0 to turn off pruning.
185
186``-fmodules-prune-after=seconds``
187 Specify the minimum time (in seconds) for which a file in the module cache must be unused (according to access time) before module pruning will remove it. The default delay is large (2,678,400 seconds, or 31 days) to avoid excessive module rebuilding.
188
Douglas Gregorc544ba02013-03-27 16:47:18 +0000189``-module-file-info <module file name>``
190 Debugging aid that prints information about a given module file (with a ``.pcm`` extension), including the language and preprocessor options that particular module variant was built with.
191
Daniel Jasperddd2dfc2013-09-24 09:14:14 +0000192``-fmodules-decluse``
193 Enable checking of module ``use`` declarations.
194
195``-fmodule-name=module-id``
196 Consider a source file as a part of the given module.
197
Daniel Jasper1b8840c2013-09-24 09:27:13 +0000198``-fmodule-map-file=<file>``
199 Load the given module map file if a header from its directory or one of its subdirectories is loaded.
200
Stephen Hines651f13c2014-04-23 16:59:28 -0700201Module Semantics
202================
203
204Modules are modeled as if each submodule were a separate translation unit, and a module import makes names from the other translation unit visible. Each submodule starts with a new preprocessor state and an empty translation unit.
205
206.. note::
207
208 This behavior is currently only approximated when building a module. Entities within a submodule that has already been built are visible when building later submodules in that module. This can lead to fragile modules that depend on the build order used for the submodules of the module, and should not be relied upon.
209
210As an example, in C, this implies that if two structs are defined in different submodules with the same name, those two types are distinct types (but may be *compatible* types if their definitions match. In C++, two structs defined with the same name in different submodules are the *same* type, and must be equivalent under C++'s One Definition Rule.
211
212.. note::
213
214 Clang currently only performs minimal checking for violations of the One Definition Rule.
215
216Macros
217------
218
219The C and C++ preprocessor assumes that the input text is a single linear buffer, but with modules this is not the case. It is possible to import two modules that have conflicting definitions for a macro (or where one ``#define``\s a macro and the other ``#undef``\ines it). The rules for handling macro definitions in the presence of modules are as follows:
220
221* Each definition and undefinition of a macro is considered to be a distinct entity.
222* Such entities are *visible* if they are from the current submodule or translation unit, or if they were exported from a submodule that has been imported.
223* A ``#define X`` or ``#undef X`` directive *overrides* all definitions of ``X`` that are visible at the point of the directive.
224* A ``#define`` or ``#undef`` directive is *active* if it is visible and no visible directive overrides it.
225* A set of macro directives is *consistent* if it consists of only ``#undef`` directives, or if all ``#define`` directives in the set define the macro name to the same sequence of tokens (following the usual rules for macro redefinitions).
226* If a macro name is used and the set of active directives is not consistent, the program is ill-formed. Otherwise, the (unique) meaning of the macro name is used.
227
228For example, suppose:
229
230* ``<stdio.h>`` defines a macro ``getc`` (and exports its ``#define``)
231* ``<cstdio>`` imports the ``<stdio.h>`` module and undefines the macro (and exports its ``#undef``)
232
233The ``#undef`` overrides the ``#define``, and a source file that imports both modules *in any order* will not see ``getc`` defined as a macro.
234
Douglas Gregora2b3d582013-03-20 06:25:14 +0000235Module Map Language
236===================
Douglas Gregora2b3d582013-03-20 06:25:14 +0000237
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000238The module map language describes the mapping from header files to the
239logical structure of modules. To enable support for using a library as
Stephen Hines651f13c2014-04-23 16:59:28 -0700240a module, one must write a ``module.modulemap`` file for that library. The
241``module.modulemap`` file is placed alongside the header files themselves,
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000242and is written in the module map language described below.
243
Stephen Hines651f13c2014-04-23 16:59:28 -0700244.. note::
245 For compatibility with previous releases, if a module map file named
246 ``module.modulemap`` is not found, Clang will also search for a file named
247 ``module.map``. This behavior is deprecated and we plan to eventually
248 remove it.
249
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000250As an example, the module map file for the C standard library might look a bit like this:
251
252.. parsed-literal::
253
Stephen Hines651f13c2014-04-23 16:59:28 -0700254 module std [system] [extern_c] {
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000255 module complex {
256 header "complex.h"
257 export *
258 }
259
260 module ctype {
261 header "ctype.h"
262 export *
263 }
264
265 module errno {
266 header "errno.h"
267 header "sys/errno.h"
268 export *
269 }
270
271 module fenv {
272 header "fenv.h"
273 export *
274 }
275
276 // ...more headers follow...
277 }
278
279Here, the top-level module ``std`` encompasses the whole C standard library. It has a number of submodules containing different parts of the standard library: ``complex`` for complex numbers, ``ctype`` for character types, etc. Each submodule lists one of more headers that provide the contents for that submodule. Finally, the ``export *`` command specifies that anything included by that submodule will be automatically re-exported.
280
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000281Lexical structure
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000282-----------------
283Module map files use a simplified form of the C99 lexer, with the same rules for identifiers, tokens, string literals, ``/* */`` and ``//`` comments. The module map language has the following reserved words; all other C identifiers are valid identifiers.
284
285.. parsed-literal::
286
287 ``config_macros`` ``export`` ``module``
288 ``conflict`` ``framework`` ``requires``
Lawrence Crowlbc3f6282013-06-20 21:14:14 +0000289 ``exclude`` ``header`` ``private``
290 ``explicit`` ``link`` ``umbrella``
Daniel Jasperddd2dfc2013-09-24 09:14:14 +0000291 ``extern`` ``use``
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000292
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000293Module map file
294---------------
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000295A module map file consists of a series of module declarations:
296
297.. parsed-literal::
298
299 *module-map-file*:
300 *module-declaration**
301
302Within a module map file, modules are referred to by a *module-id*, which uses periods to separate each part of a module's name:
303
304.. parsed-literal::
305
306 *module-id*:
Dmitri Gribenkob2cc5212013-03-22 10:25:15 +0000307 *identifier* ('.' *identifier*)*
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000308
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000309Module declaration
310------------------
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000311A module declaration describes a module, including the headers that contribute to that module, its submodules, and other aspects of the module.
312
313.. parsed-literal::
314
315 *module-declaration*:
316 ``explicit``:sub:`opt` ``framework``:sub:`opt` ``module`` *module-id* *attributes*:sub:`opt` '{' *module-member** '}'
Daniel Jasper5f0a3522013-09-11 07:20:44 +0000317 ``extern`` ``module`` *module-id* *string-literal*
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000318
319The *module-id* should consist of only a single *identifier*, which provides the name of the module being defined. Each module shall have a single definition.
320
321The ``explicit`` qualifier can only be applied to a submodule, i.e., a module that is nested within another module. The contents of explicit submodules are only made available when the submodule itself was explicitly named in an import declaration or was re-exported from an imported module.
322
323The ``framework`` qualifier specifies that this module corresponds to a Darwin-style framework. A Darwin-style framework (used primarily on Mac OS X and iOS) is contained entirely in directory ``Name.framework``, where ``Name`` is the name of the framework (and, therefore, the name of the module). That directory has the following layout:
324
325.. parsed-literal::
326
327 Name.framework/
Stephen Hines651f13c2014-04-23 16:59:28 -0700328 Modules/module.modulemap Module map for the framework
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000329 Headers/ Subdirectory containing framework headers
330 Frameworks/ Subdirectory containing embedded frameworks
331 Resources/ Subdirectory containing additional resources
332 Name Symbolic link to the shared library for the framework
333
Stephen Hines651f13c2014-04-23 16:59:28 -0700334The ``system`` attribute specifies that the module is a system module. When a system module is rebuilt, all of the module's headers will be considered system headers, which suppresses warnings. This is equivalent to placing ``#pragma GCC system_header`` in each of the module's headers. The form of attributes is described in the section Attributes_, below.
335
336The ``extern_c`` attribute specifies that the module contains C code that can be used from within C++. When such a module is built for use in C++ code, all of the module's headers will be treated as if they were contained within an implicit ``extern "C"`` block. An import for a module with this attribute can appear within an ``extern "C"`` block. No other restrictions are lifted, however: the module currently cannot be imported within an ``extern "C"`` block in a namespace.
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000337
338Modules can have a number of different kinds of members, each of which is described below:
339
Dmitri Gribenkob2cc5212013-03-22 10:25:15 +0000340.. parsed-literal::
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000341
342 *module-member*:
343 *requires-declaration*
344 *header-declaration*
345 *umbrella-dir-declaration*
346 *submodule-declaration*
347 *export-declaration*
Daniel Jasperddd2dfc2013-09-24 09:14:14 +0000348 *use-declaration*
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000349 *link-declaration*
350 *config-macros-declaration*
351 *conflict-declaration*
352
Daniel Jasper5f0a3522013-09-11 07:20:44 +0000353An extern module references a module defined by the *module-id* in a file given by the *string-literal*. The file can be referenced either by an absolute path or by a path relative to the current map file.
354
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000355Requires declaration
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000356~~~~~~~~~~~~~~~~~~~~
357A *requires-declaration* specifies the requirements that an importing translation unit must satisfy to use the module.
358
359.. parsed-literal::
360
361 *requires-declaration*:
362 ``requires`` *feature-list*
363
364 *feature-list*:
Richard Smith5794b532013-10-28 22:18:19 +0000365 *feature* (',' *feature*)*
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000366
Richard Smith5794b532013-10-28 22:18:19 +0000367 *feature*:
368 ``!``:sub:`opt` *identifier*
369
370The requirements clause allows specific modules or submodules to specify that they are only accessible with certain language dialects or on certain platforms. The feature list is a set of identifiers, defined below. If any of the features is not available in a given translation unit, that translation unit shall not import the module. The optional ``!`` indicates that a feature is incompatible with the module.
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000371
372The following features are defined:
373
374altivec
375 The target supports AltiVec.
376
377blocks
378 The "blocks" language feature is available.
379
380cplusplus
381 C++ support is available.
382
383cplusplus11
384 C++11 support is available.
385
386objc
387 Objective-C support is available.
388
389objc_arc
390 Objective-C Automatic Reference Counting (ARC) is available
391
392opencl
393 OpenCL is available
394
395tls
396 Thread local storage is available.
397
398*target feature*
399 A specific target feature (e.g., ``sse4``, ``avx``, ``neon``) is available.
400
401
402**Example**: The ``std`` module can be extended to also include C++ and C++11 headers using a *requires-declaration*:
403
404.. parsed-literal::
405
406 module std {
407 // C standard library...
408
409 module vector {
410 requires cplusplus
411 header "vector"
412 }
413
414 module type_traits {
415 requires cplusplus11
416 header "type_traits"
417 }
418 }
419
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000420Header declaration
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000421~~~~~~~~~~~~~~~~~~
422A header declaration specifies that a particular header is associated with the enclosing module.
423
424.. parsed-literal::
425
426 *header-declaration*:
427 ``umbrella``:sub:`opt` ``header`` *string-literal*
Lawrence Crowlbc3f6282013-06-20 21:14:14 +0000428 ``private`` ``header`` *string-literal*
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000429 ``exclude`` ``header`` *string-literal*
430
431A header declaration that does not contain ``exclude`` specifies a header that contributes to the enclosing module. Specifically, when the module is built, the named header will be parsed and its declarations will be (logically) placed into the enclosing submodule.
432
433A header with the ``umbrella`` specifier is called an umbrella header. An umbrella header includes all of the headers within its directory (and any subdirectories), and is typically used (in the ``#include`` world) to easily access the full API provided by a particular library. With modules, an umbrella header is a convenient shortcut that eliminates the need to write out ``header`` declarations for every library header. A given directory can only contain a single umbrella header.
434
435.. note::
436 Any headers not included by the umbrella header should have
437 explicit ``header`` declarations. Use the
438 ``-Wincomplete-umbrella`` warning option to ask Clang to complain
439 about headers not covered by the umbrella header or the module map.
440
Lawrence Crowlbc3f6282013-06-20 21:14:14 +0000441A header with the ``private`` specifier may not be included from outside the module itself.
442
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000443A header with the ``exclude`` specifier is excluded from the module. It will not be included when the module is built, nor will it be considered to be part of the module.
444
445**Example**: The C header ``assert.h`` is an excellent candidate for an excluded header, because it is meant to be included multiple times (possibly with different ``NDEBUG`` settings).
446
447.. parsed-literal::
448
449 module std [system] {
450 exclude header "assert.h"
451 }
452
453A given header shall not be referenced by more than one *header-declaration*.
454
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000455Umbrella directory declaration
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000456~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
457An umbrella directory declaration specifies that all of the headers in the specified directory should be included within the module.
458
459.. parsed-literal::
460
461 *umbrella-dir-declaration*:
462 ``umbrella`` *string-literal*
463
464The *string-literal* refers to a directory. When the module is built, all of the header files in that directory (and its subdirectories) are included in the module.
465
466An *umbrella-dir-declaration* shall not refer to the same directory as the location of an umbrella *header-declaration*. In other words, only a single kind of umbrella can be specified for a given directory.
467
468.. note::
469
470 Umbrella directories are useful for libraries that have a large number of headers but do not have an umbrella header.
471
472
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000473Submodule declaration
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000474~~~~~~~~~~~~~~~~~~~~~
475Submodule declarations describe modules that are nested within their enclosing module.
476
477.. parsed-literal::
478
479 *submodule-declaration*:
480 *module-declaration*
481 *inferred-submodule-declaration*
482
483A *submodule-declaration* that is a *module-declaration* is a nested module. If the *module-declaration* has a ``framework`` specifier, the enclosing module shall have a ``framework`` specifier; the submodule's contents shall be contained within the subdirectory ``Frameworks/SubName.framework``, where ``SubName`` is the name of the submodule.
484
485A *submodule-declaration* that is an *inferred-submodule-declaration* describes a set of submodules that correspond to any headers that are part of the module but are not explicitly described by a *header-declaration*.
486
487.. parsed-literal::
488
489 *inferred-submodule-declaration*:
490 ``explicit``:sub:`opt` ``framework``:sub:`opt` ``module`` '*' *attributes*:sub:`opt` '{' *inferred-submodule-member** '}'
491
492 *inferred-submodule-member*:
493 ``export`` '*'
494
495A module containing an *inferred-submodule-declaration* shall have either an umbrella header or an umbrella directory. The headers to which the *inferred-submodule-declaration* applies are exactly those headers included by the umbrella header (transitively) or included in the module because they reside within the umbrella directory (or its subdirectories).
496
497For each header included by the umbrella header or in the umbrella directory that is not named by a *header-declaration*, a module declaration is implicitly generated from the *inferred-submodule-declaration*. The module will:
498
499* Have the same name as the header (without the file extension)
500* Have the ``explicit`` specifier, if the *inferred-submodule-declaration* has the ``explicit`` specifier
501* Have the ``framework`` specifier, if the
502 *inferred-submodule-declaration* has the ``framework`` specifier
503* Have the attributes specified by the \ *inferred-submodule-declaration*
504* Contain a single *header-declaration* naming that header
505* Contain a single *export-declaration* ``export *``, if the \ *inferred-submodule-declaration* contains the \ *inferred-submodule-member* ``export *``
506
507**Example**: If the subdirectory "MyLib" contains the headers ``A.h`` and ``B.h``, then the following module map:
508
509.. parsed-literal::
510
511 module MyLib {
512 umbrella "MyLib"
513 explicit module * {
514 export *
515 }
516 }
517
518is equivalent to the (more verbose) module map:
519
520.. parsed-literal::
521
522 module MyLib {
523 explicit module A {
524 header "A.h"
525 export *
526 }
527
528 explicit module B {
529 header "B.h"
530 export *
531 }
532 }
533
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000534Export declaration
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000535~~~~~~~~~~~~~~~~~~
536An *export-declaration* specifies which imported modules will automatically be re-exported as part of a given module's API.
537
538.. parsed-literal::
539
540 *export-declaration*:
541 ``export`` *wildcard-module-id*
542
543 *wildcard-module-id*:
544 *identifier*
545 '*'
546 *identifier* '.' *wildcard-module-id*
547
548The *export-declaration* names a module or a set of modules that will be re-exported to any translation unit that imports the enclosing module. Each imported module that matches the *wildcard-module-id* up to, but not including, the first ``*`` will be re-exported.
549
550**Example**:: In the following example, importing ``MyLib.Derived`` also provides the API for ``MyLib.Base``:
551
552.. parsed-literal::
553
554 module MyLib {
555 module Base {
556 header "Base.h"
557 }
558
559 module Derived {
560 header "Derived.h"
561 export Base
562 }
563 }
564
565Note that, if ``Derived.h`` includes ``Base.h``, one can simply use a wildcard export to re-export everything ``Derived.h`` includes:
566
567.. parsed-literal::
568
569 module MyLib {
570 module Base {
571 header "Base.h"
572 }
573
574 module Derived {
575 header "Derived.h"
576 export *
577 }
578 }
579
580.. note::
581
582 The wildcard export syntax ``export *`` re-exports all of the
583 modules that were imported in the actual header file. Because
584 ``#include`` directives are automatically mapped to module imports,
585 ``export *`` provides the same transitive-inclusion behavior
586 provided by the C preprocessor, e.g., importing a given module
587 implicitly imports all of the modules on which it depends.
588 Therefore, liberal use of ``export *`` provides excellent backward
589 compatibility for programs that rely on transitive inclusion (i.e.,
590 all of them).
591
Daniel Jasperddd2dfc2013-09-24 09:14:14 +0000592Use declaration
593~~~~~~~~~~~~~~~
594A *use-declaration* specifies one of the other modules that the module is allowed to use. An import or include not matching one of these is rejected when the option *-fmodules-decluse*.
595
596.. parsed-literal::
597
598 *use-declaration*:
599 ``use`` *module-id*
600
601**Example**:: In the following example, use of A from C is not declared, so will trigger a warning.
602
603.. parsed-literal::
604
605 module A {
606 header "a.h"
607 }
608
609 module B {
610 header "b.h"
611 }
612
613 module C {
614 header "c.h"
615 use B
616 }
617
Stephen Hines651f13c2014-04-23 16:59:28 -0700618When compiling a source file that implements a module, use the option ``-fmodule-name=module-id`` to indicate that the source file is logically part of that module.
Daniel Jasperddd2dfc2013-09-24 09:14:14 +0000619
620The compiler at present only applies restrictions to the module directly being built.
621
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000622Link declaration
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000623~~~~~~~~~~~~~~~~
624A *link-declaration* specifies a library or framework against which a program should be linked if the enclosing module is imported in any translation unit in that program.
625
626.. parsed-literal::
627
628 *link-declaration*:
629 ``link`` ``framework``:sub:`opt` *string-literal*
630
631The *string-literal* specifies the name of the library or framework against which the program should be linked. For example, specifying "clangBasic" would instruct the linker to link with ``-lclangBasic`` for a Unix-style linker.
632
633A *link-declaration* with the ``framework`` specifies that the linker should link against the named framework, e.g., with ``-framework MyFramework``.
634
635.. note::
636
637 Automatic linking with the ``link`` directive is not yet widely
638 implemented, because it requires support from both the object file
639 format and the linker. The notion is similar to Microsoft Visual
640 Studio's ``#pragma comment(lib...)``.
641
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000642Configuration macros declaration
643~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000644The *config-macros-declaration* specifies the set of configuration macros that have an effect on the the API of the enclosing module.
645
646.. parsed-literal::
647
648 *config-macros-declaration*:
649 ``config_macros`` *attributes*:sub:`opt` *config-macro-list*:sub:`opt`
650
651 *config-macro-list*:
652 *identifier* (',' *identifier*)*
653
654Each *identifier* in the *config-macro-list* specifies the name of a macro. The compiler is required to maintain different variants of the given module for differing definitions of any of the named macros.
655
656A *config-macros-declaration* shall only be present on a top-level module, i.e., a module that is not nested within an enclosing module.
657
658The ``exhaustive`` attribute specifies that the list of macros in the *config-macros-declaration* is exhaustive, meaning that no other macro definition is intended to have an effect on the API of that module.
659
660.. note::
661
662 The ``exhaustive`` attribute implies that any macro definitions
663 for macros not listed as configuration macros should be ignored
664 completely when building the module. As an optimization, the
665 compiler could reduce the number of unique module variants by not
666 considering these non-configuration macros. This optimization is not
667 yet implemented in Clang.
668
669A translation unit shall not import the same module under different definitions of the configuration macros.
670
671.. note::
672
673 Clang implements a weak form of this requirement: the definitions
674 used for configuration macros are fixed based on the definitions
675 provided by the command line. If an import occurs and the definition
676 of any configuration macro has changed, the compiler will produce a
677 warning (under the control of ``-Wconfig-macros``).
678
679**Example:** A logging library might provide different API (e.g., in the form of different definitions for a logging macro) based on the ``NDEBUG`` macro setting:
680
681.. parsed-literal::
682
683 module MyLogger {
684 umbrella header "MyLogger.h"
685 config_macros [exhaustive] NDEBUG
686 }
687
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000688Conflict declarations
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000689~~~~~~~~~~~~~~~~~~~~~
690A *conflict-declaration* describes a case where the presence of two different modules in the same translation unit is likely to cause a problem. For example, two modules may provide similar-but-incompatible functionality.
691
692.. parsed-literal::
693
694 *conflict-declaration*:
695 ``conflict`` *module-id* ',' *string-literal*
696
697The *module-id* of the *conflict-declaration* specifies the module with which the enclosing module conflicts. The specified module shall not have been imported in the translation unit when the enclosing module is imported.
698
699The *string-literal* provides a message to be provided as part of the compiler diagnostic when two modules conflict.
700
701.. note::
702
703 Clang emits a warning (under the control of ``-Wmodule-conflict``)
704 when a module conflict is discovered.
705
706**Example:**
707
708.. parsed-literal::
709
710 module Conflicts {
711 explicit module A {
712 header "conflict_a.h"
713 conflict B, "we just don't like B"
714 }
715
716 module B {
717 header "conflict_b.h"
718 }
719 }
720
721
722Attributes
723----------
724Attributes are used in a number of places in the grammar to describe specific behavior of other declarations. The format of attributes is fairly simple.
725
726.. parsed-literal::
727
728 *attributes*:
729 *attribute* *attributes*:sub:`opt`
730
731 *attribute*:
732 '[' *identifier* ']'
733
734Any *identifier* can be used as an attribute, and each declaration specifies what attributes can be applied to it.
735
Stephen Hines651f13c2014-04-23 16:59:28 -0700736Private Module Map Files
737------------------------
738Module map files are typically named ``module.modulemap`` and live
739either alongside the headers they describe or in a parent directory of
740the headers they describe. These module maps typically describe all of
741the API for the library.
742
743However, in some cases, the presence or absence of particular headers
744is used to distinguish between the "public" and "private" APIs of a
745particular library. For example, a library may contain the headers
746``Foo.h`` and ``Foo_Private.h``, providing public and private APIs,
747respectively. Additionally, ``Foo_Private.h`` may only be available on
748some versions of library, and absent in others. One cannot easily
749express this with a single module map file in the library:
750
751.. parsed-literal::
752
753 module Foo {
754 header "Foo.h"
755
756 explicit module Private {
757 header "Foo_Private.h"
758 }
759 }
760
761
762because the header ``Foo_Private.h`` won't always be available. The
763module map file could be customized based on whether
764``Foo_Private.h``is available or not, but doing so requires custom
765build machinery.
766
767Private module map files, which are named ``module.private.modulemap``
768(or, for backward compatibility, ``module_private.map``), allow one to
769augment the primary module map file with an additional submodule. For
770example, we would split the module map file above into two module map
771files:
772
773.. parsed-literal::
774
775 /* module.modulemap */
776 module Foo {
777 header "Foo.h"
778 }
779
780 /* module.private.modulemap */
781 explicit module Foo.Private {
782 header "Foo_Private.h"
783 }
784
785
786When a ``module.private.modulemap`` file is found alongside a
787``module.modulemap`` file, it is loaded after the ``module.modulemap``
788file. In our example library, the ``module.private.modulemap`` file
789would be available when ``Foo_Private.h`` is available, making it
790easier to split a library's public and private APIs along header
791boundaries.
792
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000793Modularizing a Platform
794=======================
795To get any benefit out of modules, one needs to introduce module maps for software libraries starting at the bottom of the stack. This typically means introducing a module map covering the operating system's headers and the C standard library headers (in ``/usr/include``, for a Unix system).
796
797The module maps will be written using the `module map language`_, which provides the tools necessary to describe the mapping between headers and modules. Because the set of headers differs from one system to the next, the module map will likely have to be somewhat customized for, e.g., a particular distribution and version of the operating system. Moreover, the system headers themselves may require some modification, if they exhibit any anti-patterns that break modules. Such common patterns are described below.
798
799**Macro-guarded copy-and-pasted definitions**
800 System headers vend core types such as ``size_t`` for users. These types are often needed in a number of system headers, and are almost trivial to write. Hence, it is fairly common to see a definition such as the following copy-and-pasted throughout the headers:
801
802 .. parsed-literal::
803
804 #ifndef _SIZE_T
805 #define _SIZE_T
806 typedef __SIZE_TYPE__ size_t;
807 #endif
808
809 Unfortunately, when modules compiles all of the C library headers together into a single module, only the first actual type definition of ``size_t`` will be visible, and then only in the submodule corresponding to the lucky first header. Any other headers that have copy-and-pasted versions of this pattern will *not* have a definition of ``size_t``. Importing the submodule corresponding to one of those headers will therefore not yield ``size_t`` as part of the API, because it wasn't there when the header was parsed. The fix for this problem is either to pull the copied declarations into a common header that gets included everywhere ``size_t`` is part of the API, or to eliminate the ``#ifndef`` and redefine the ``size_t`` type. The latter works for C++ headers and C11, but will cause an error for non-modules C90/C99, where redefinition of ``typedefs`` is not permitted.
810
811**Conflicting definitions**
812 Different system headers may provide conflicting definitions for various macros, functions, or types. These conflicting definitions don't tend to cause problems in a pre-modules world unless someone happens to include both headers in one translation unit. Since the fix is often simply "don't do that", such problems persist. Modules requires that the conflicting definitions be eliminated or that they be placed in separate modules (the former is generally the better answer).
813
814**Missing includes**
815 Headers are often missing ``#include`` directives for headers that they actually depend on. As with the problem of conflicting definitions, this only affects unlucky users who don't happen to include headers in the right order. With modules, the headers of a particular module will be parsed in isolation, so the module may fail to build if there are missing includes.
816
817**Headers that vend multiple APIs at different times**
818 Some systems have headers that contain a number of different kinds of API definitions, only some of which are made available with a given include. For example, the header may vend ``size_t`` only when the macro ``__need_size_t`` is defined before that header is included, and also vend ``wchar_t`` only when the macro ``__need_wchar_t`` is defined. Such headers are often included many times in a single translation unit, and will have no include guards. There is no sane way to map this header to a submodule. One can either eliminate the header (e.g., by splitting it into separate headers, one per actual API) or simply ``exclude`` it in the module map.
819
820To detect and help address some of these problems, the ``clang-tools-extra`` repository contains a ``modularize`` tool that parses a set of given headers and attempts to detect these problems and produce a report. See the tool's in-source documentation for information on how to check your system or library headers.
821
Douglas Gregor5921e042013-03-22 07:08:56 +0000822Future Directions
823=================
824Modules is an experimental feature, and there is much work left to do to make it both real and useful. Here are a few ideas:
825
826**Detect unused module imports**
827 Unlike with ``#include`` directives, it should be fairly simple to track whether a directly-imported module has ever been used. By doing so, Clang can emit ``unused import`` or ``unused #include`` diagnostics, including Fix-Its to remove the useless imports/includes.
828
829**Fix-Its for missing imports**
830 It's fairly common for one to make use of some API while writing code, only to get a compiler error about "unknown type" or "no function named" because the corresponding header has not been included. Clang should detect such cases and auto-import the required module (with a Fix-It!).
831
832**Improve modularize**
833 The modularize tool is both extremely important (for deployment) and extremely crude. It needs better UI, better detection of problems (especially for C++), and perhaps an assistant mode to help write module maps for you.
834
835**C++ Support**
836 Modules clearly has to work for C++, or we'll never get to use it for the Clang code base.
837
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000838Where To Learn More About Modules
839=================================
840The Clang source code provides additional information about modules:
841
842``clang/lib/Headers/module.map``
843 Module map for Clang's compiler-specific header files.
844
845``clang/test/Modules/``
846 Tests specifically related to modules functionality.
847
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000848``clang/include/clang/Basic/Module.h``
849 The ``Module`` class in this header describes a module, and is used throughout the compiler to implement modules.
850
851``clang/include/clang/Lex/ModuleMap.h``
852 The ``ModuleMap`` class in this header describes the full module map, consisting of all of the module map files that have been parsed, and providing facilities for looking up module maps and mapping between modules and headers (in both directions).
853
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000854PCHInternals_
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000855 Information about the serialized AST format used for precompiled headers and modules. The actual implementation is in the ``clangSerialization`` library.
Douglas Gregora2b3d582013-03-20 06:25:14 +0000856
857.. [#] Automatic linking against the libraries of modules requires specific linker support, which is not widely available.
858
859.. [#] Modules are only available in C and Objective-C; a separate flag ``-fcxx-modules`` enables modules support for C++, which is even more experimental and broken.
860
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000861.. [#] There are certain anti-patterns that occur in headers, particularly system headers, that cause problems for modules. The section `Modularizing a Platform`_ describes some of them.
Douglas Gregora2b3d582013-03-20 06:25:14 +0000862
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000863.. [#] The second instance is actually a new thread within the current process, not a separate process. However, the original compiler instance is blocked on the execution of this thread.
Douglas Gregora2b3d582013-03-20 06:25:14 +0000864
Douglas Gregor5529e3e2013-03-22 07:05:07 +0000865.. [#] The preprocessing context in which the modules are parsed is actually dependent on the command-line options provided to the compiler, including the language dialect and any ``-D`` options. However, the compiled modules for different command-line options are kept distinct, and any preprocessor directives that occur within the translation unit are ignored. See the section on the `Configuration macros declaration`_ for more information.
Douglas Gregor9bb4a0c2013-03-22 06:21:35 +0000866
867.. _PCHInternals: PCHInternals.html
868