Home | History | Annotate | Download | only in docs
      1 =======
      2 Modules
      3 =======
      4 
      5 .. contents::
      6    :local:
      7 
      8 .. warning::
      9    The functionality described on this page is still experimental! Please
     10    try it out and send us bug reports!
     11 
     12 Introduction
     13 ============
     14 Most 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 
     20 The implementation is handled separately by linking against the appropriate library. For example, by passing ``-lSomeLib`` to the linker.
     21 
     22 Modules 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 
     24 Problems with the current model
     25 -------------------------------
     26 The ``#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 
     76 Semantic import
     77 ---------------
     78 Modules 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 
     84 However, 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 [#]_
     85 This 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 
     93 Problems modules do not solve
     94 -----------------------------
     95 Many 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 
    103 * **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.
    104 
    105 Using Modules
    106 =============
    107 To 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.
    108 
    109 Import declaration
    110 ------------------
    111 The most direct way to import a module is with an *import declaration*, which imports the named module:
    112 
    113 .. parsed-literal::
    114 
    115   import std;
    116 
    117 The 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.,
    118 
    119 .. parsed-literal::
    120 
    121   import std.io;
    122 
    123 Redundant 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 
    125 .. warning::
    126   The import declaration syntax described here does not actually exist. Rather, it is a straw man proposal that may very well change when modules are discussed in the C and C++ committees. See the section `Includes as imports`_ to see how modules get imported today.
    127 
    128 Includes as imports
    129 -------------------
    130 The 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
    131 
    132 .. code-block:: c
    133 
    134   #include <stdio.h>
    135 
    136 will 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.
    137 
    138 .. note::
    139 
    140   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.
    141 
    142 Module maps
    143 -----------
    144 The 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.
    145 
    146 Module maps are specified as separate files (each named ``module.map``) 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.
    147 
    148 .. note::
    149 
    150   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.
    151   
    152 One 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.
    153 
    154 Compilation model
    155 -----------------
    156 The 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.
    157 
    158 The 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.
    159 
    160 Modules 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.
    161 
    162 Command-line parameters
    163 -----------------------
    164 ``-fmodules``
    165   Enable the modules feature (EXPERIMENTAL).
    166 
    167 ``-fcxx-modules``
    168   Enable the modules feature for C++ (EXPERIMENTAL and VERY BROKEN).
    169 
    170 ``-fmodule-maps``
    171   Enable interpretation of module maps (EXPERIMENTAL). This option is implied by ``-fmodules``.
    172 
    173 ``-fmodules-cache-path=<directory>``
    174   Specify the path to the modules cache. If not provided, Clang will select a system-appropriate default.
    175 
    176 ``-fno-autolink``
    177   Disable automatic linking against the libraries associated with imported modules.
    178 
    179 ``-fmodules-ignore-macro=macroname``
    180   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.
    181 
    182 ``-fmodules-prune-interval=seconds``
    183   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.
    184 
    185 ``-fmodules-prune-after=seconds``
    186   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.
    187 
    188 ``-module-file-info <module file name>``
    189   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.
    190 
    191 Module Map Language
    192 ===================
    193 
    194 The module map language describes the mapping from header files to the
    195 logical structure of modules. To enable support for using a library as
    196 a module, one must write a ``module.map`` file for that library. The
    197 ``module.map`` file is placed alongside the header files themselves,
    198 and is written in the module map language described below.
    199 
    200 As an example, the module map file for the C standard library might look a bit like this:
    201 
    202 .. parsed-literal::
    203 
    204   module std [system] {
    205     module complex {
    206       header "complex.h"
    207       export *
    208     }
    209 
    210     module ctype {
    211       header "ctype.h"
    212       export *
    213     }
    214 
    215     module errno {
    216       header "errno.h"
    217       header "sys/errno.h"
    218       export *
    219     }
    220 
    221     module fenv {
    222       header "fenv.h"
    223       export *
    224     }
    225 
    226     // ...more headers follow...
    227   }
    228 
    229 Here, 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. 
    230 
    231 Lexical structure
    232 -----------------
    233 Module 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.
    234 
    235 .. parsed-literal::
    236 
    237   ``config_macros`` ``export``     ``module``
    238   ``conflict``      ``framework``  ``requires``
    239   ``exclude``       ``header``     ``private``
    240   ``explicit``      ``link``       ``umbrella``
    241 
    242 Module map file
    243 ---------------
    244 A module map file consists of a series of module declarations:
    245 
    246 .. parsed-literal::
    247 
    248   *module-map-file*:
    249     *module-declaration**
    250 
    251 Within a module map file, modules are referred to by a *module-id*, which uses periods to separate each part of a module's name:
    252 
    253 .. parsed-literal::
    254 
    255   *module-id*:
    256     *identifier* ('.' *identifier*)*
    257 
    258 Module declaration
    259 ------------------
    260 A module declaration describes a module, including the headers that contribute to that module, its submodules, and other aspects of the module.
    261 
    262 .. parsed-literal::
    263 
    264   *module-declaration*:
    265     ``explicit``:sub:`opt` ``framework``:sub:`opt` ``module`` *module-id* *attributes*:sub:`opt` '{' *module-member** '}'
    266 
    267 The *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. 
    268 
    269 The ``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.
    270 
    271 The ``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:
    272 
    273 .. parsed-literal::
    274 
    275   Name.framework/
    276     module.map                Module map for the framework
    277     Headers/                  Subdirectory containing framework headers
    278     Frameworks/               Subdirectory containing embedded frameworks
    279     Resources/                Subdirectory containing additional resources
    280     Name                      Symbolic link to the shared library for the framework
    281 
    282 The ``system`` attribute specifies that the module is a system module. When a system module is rebuilt, all of the module's header 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.
    283 
    284 Modules can have a number of different kinds of members, each of which is described below:
    285 
    286 .. parsed-literal::
    287 
    288   *module-member*:
    289     *requires-declaration*
    290     *header-declaration*
    291     *umbrella-dir-declaration*
    292     *submodule-declaration*
    293     *export-declaration*
    294     *link-declaration*
    295     *config-macros-declaration*
    296     *conflict-declaration*
    297 
    298 Requires declaration
    299 ~~~~~~~~~~~~~~~~~~~~
    300 A *requires-declaration* specifies the requirements that an importing translation unit must satisfy to use the module.
    301 
    302 .. parsed-literal::
    303 
    304   *requires-declaration*:
    305     ``requires`` *feature-list*
    306 
    307   *feature-list*:
    308     *identifier* (',' *identifier*)*
    309 
    310 The 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.
    311 
    312 The following features are defined:
    313 
    314 altivec
    315   The target supports AltiVec.
    316 
    317 blocks
    318   The "blocks" language feature is available.
    319 
    320 cplusplus
    321   C++ support is available.
    322 
    323 cplusplus11
    324   C++11 support is available.
    325 
    326 objc
    327   Objective-C support is available.
    328 
    329 objc_arc
    330   Objective-C Automatic Reference Counting (ARC) is available
    331 
    332 opencl
    333   OpenCL is available
    334 
    335 tls
    336   Thread local storage is available.
    337 
    338 *target feature*
    339   A specific target feature (e.g., ``sse4``, ``avx``, ``neon``) is available.
    340 
    341 
    342 **Example**: The ``std`` module can be extended to also include C++ and C++11 headers using a *requires-declaration*:
    343 
    344 .. parsed-literal::
    345 
    346  module std {
    347     // C standard library...
    348 
    349     module vector {
    350       requires cplusplus
    351       header "vector"
    352     }
    353 
    354     module type_traits {
    355       requires cplusplus11
    356       header "type_traits"
    357     }
    358   }
    359 
    360 Header declaration
    361 ~~~~~~~~~~~~~~~~~~
    362 A header declaration specifies that a particular header is associated with the enclosing module.
    363 
    364 .. parsed-literal::
    365 
    366   *header-declaration*:
    367     ``umbrella``:sub:`opt` ``header`` *string-literal*
    368     ``private`` ``header`` *string-literal*
    369     ``exclude`` ``header`` *string-literal*
    370 
    371 A 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.
    372 
    373 A 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.
    374 
    375 .. note::
    376     Any headers not included by the umbrella header should have
    377     explicit ``header`` declarations. Use the   
    378     ``-Wincomplete-umbrella`` warning option to ask Clang to complain
    379     about headers not covered by the umbrella header or the module map.
    380 
    381 A header with the ``private`` specifier may not be included from outside the module itself.
    382 
    383 A 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.
    384 
    385 **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).
    386 
    387 .. parsed-literal::
    388 
    389   module std [system] {
    390     exclude header "assert.h"
    391   }
    392 
    393 A given header shall not be referenced by more than one *header-declaration*.
    394 
    395 Umbrella directory declaration
    396 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    397 An umbrella directory declaration specifies that all of the headers in the specified directory should be included within the module.
    398 
    399 .. parsed-literal::
    400 
    401   *umbrella-dir-declaration*:
    402     ``umbrella`` *string-literal*
    403   
    404 The *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.
    405 
    406 An *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.
    407 
    408 .. note::
    409 
    410     Umbrella directories are useful for libraries that have a large number of headers but do not have an umbrella header.
    411 
    412 
    413 Submodule declaration
    414 ~~~~~~~~~~~~~~~~~~~~~
    415 Submodule declarations describe modules that are nested within their enclosing module.
    416 
    417 .. parsed-literal::
    418 
    419   *submodule-declaration*:
    420     *module-declaration*
    421     *inferred-submodule-declaration*
    422 
    423 A *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.
    424 
    425 A *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*.
    426 
    427 .. parsed-literal::
    428 
    429   *inferred-submodule-declaration*:
    430     ``explicit``:sub:`opt` ``framework``:sub:`opt` ``module`` '*' *attributes*:sub:`opt` '{' *inferred-submodule-member** '}'
    431   
    432   *inferred-submodule-member*:
    433     ``export`` '*'
    434 
    435 A 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).
    436 
    437 For 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:
    438 
    439 * Have the same name as the header (without the file extension)
    440 * Have the ``explicit`` specifier, if the *inferred-submodule-declaration* has the ``explicit`` specifier
    441 * Have the ``framework`` specifier, if the    
    442   *inferred-submodule-declaration* has the ``framework`` specifier
    443 * Have the attributes specified by the \ *inferred-submodule-declaration* 
    444 * Contain a single *header-declaration* naming that header
    445 * Contain a single *export-declaration* ``export *``, if the \ *inferred-submodule-declaration* contains the \ *inferred-submodule-member* ``export *``
    446 
    447 **Example**: If the subdirectory "MyLib" contains the headers ``A.h`` and ``B.h``, then the following module map:
    448 
    449 .. parsed-literal::
    450 
    451   module MyLib {
    452     umbrella "MyLib"
    453     explicit module * {
    454       export *
    455     }
    456   }
    457 
    458 is equivalent to the (more verbose) module map:
    459 
    460 .. parsed-literal::
    461 
    462   module MyLib {
    463     explicit module A {
    464       header "A.h"
    465       export *
    466     }
    467 
    468     explicit module B {
    469       header "B.h"
    470       export *
    471     }
    472   }
    473 
    474 Export declaration
    475 ~~~~~~~~~~~~~~~~~~
    476 An *export-declaration* specifies which imported modules will automatically be re-exported as part of a given module's API.
    477 
    478 .. parsed-literal::
    479 
    480   *export-declaration*:
    481     ``export`` *wildcard-module-id*
    482 
    483   *wildcard-module-id*:
    484     *identifier*
    485     '*'
    486     *identifier* '.' *wildcard-module-id*
    487 
    488 The *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.
    489 
    490 **Example**:: In the following example, importing ``MyLib.Derived`` also provides the API for ``MyLib.Base``:
    491 
    492 .. parsed-literal::
    493 
    494   module MyLib {
    495     module Base {
    496       header "Base.h"
    497     }
    498 
    499     module Derived {
    500       header "Derived.h"
    501       export Base
    502     }
    503   }
    504 
    505 Note that, if ``Derived.h`` includes ``Base.h``, one can simply use a wildcard export to re-export everything ``Derived.h`` includes:
    506 
    507 .. parsed-literal::
    508 
    509   module MyLib {
    510     module Base {
    511       header "Base.h"
    512     }
    513 
    514     module Derived {
    515       header "Derived.h"
    516       export *
    517     }
    518   }
    519 
    520 .. note::
    521 
    522   The wildcard export syntax ``export *`` re-exports all of the
    523   modules that were imported in the actual header file. Because
    524   ``#include`` directives are automatically mapped to module imports,
    525   ``export *`` provides the same transitive-inclusion behavior
    526   provided by the C preprocessor, e.g., importing a given module
    527   implicitly imports all of the modules on which it depends.
    528   Therefore, liberal use of ``export *`` provides excellent backward
    529   compatibility for programs that rely on transitive inclusion (i.e.,
    530   all of them).
    531 
    532 Link declaration
    533 ~~~~~~~~~~~~~~~~
    534 A *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.
    535 
    536 .. parsed-literal::
    537 
    538   *link-declaration*:
    539     ``link`` ``framework``:sub:`opt` *string-literal*
    540 
    541 The *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.
    542 
    543 A *link-declaration* with the ``framework`` specifies that the linker should link against the named framework, e.g., with ``-framework MyFramework``.
    544 
    545 .. note::
    546 
    547   Automatic linking with the ``link`` directive is not yet widely
    548   implemented, because it requires support from both the object file
    549   format and the linker. The notion is similar to Microsoft Visual
    550   Studio's ``#pragma comment(lib...)``.
    551 
    552 Configuration macros declaration
    553 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    554 The *config-macros-declaration* specifies the set of configuration macros that have an effect on the the API of the enclosing module.
    555 
    556 .. parsed-literal::
    557 
    558   *config-macros-declaration*:
    559     ``config_macros`` *attributes*:sub:`opt` *config-macro-list*:sub:`opt`
    560 
    561   *config-macro-list*:
    562     *identifier* (',' *identifier*)*
    563 
    564 Each *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.
    565 
    566 A *config-macros-declaration* shall only be present on a top-level module, i.e., a module that is not nested within an enclosing module.
    567 
    568 The ``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. 
    569 
    570 .. note::
    571 
    572   The ``exhaustive`` attribute implies that any macro definitions 
    573   for macros not listed as configuration macros should be ignored
    574   completely when building the module. As an optimization, the
    575   compiler could reduce the number of unique module variants by not
    576   considering these non-configuration macros. This optimization is not
    577   yet implemented in Clang.
    578 
    579 A translation unit shall not import the same module under different definitions of the configuration macros.
    580 
    581 .. note::
    582 
    583   Clang implements a weak form of this requirement: the definitions
    584   used for configuration macros are fixed based on the definitions
    585   provided by the command line. If an import occurs and the definition
    586   of any configuration macro has changed, the compiler will produce a
    587   warning (under the control of ``-Wconfig-macros``).
    588 
    589 **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:
    590 
    591 .. parsed-literal::
    592 
    593   module MyLogger {
    594     umbrella header "MyLogger.h"
    595     config_macros [exhaustive] NDEBUG
    596   }
    597 
    598 Conflict declarations
    599 ~~~~~~~~~~~~~~~~~~~~~
    600 A *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.
    601 
    602 .. parsed-literal::
    603 
    604   *conflict-declaration*:
    605     ``conflict`` *module-id* ',' *string-literal*
    606 
    607 The *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.
    608 
    609 The *string-literal* provides a message to be provided as part of the compiler diagnostic when two modules conflict.
    610 
    611 .. note::
    612 
    613   Clang emits a warning (under the control of ``-Wmodule-conflict``)
    614   when a module conflict is discovered.
    615 
    616 **Example:**
    617 
    618 .. parsed-literal::
    619 
    620   module Conflicts {
    621     explicit module A {
    622       header "conflict_a.h"
    623       conflict B, "we just don't like B"
    624     }
    625 
    626     module B {
    627       header "conflict_b.h"
    628     }
    629   }
    630 
    631 
    632 Attributes
    633 ----------
    634 Attributes are used in a number of places in the grammar to describe specific behavior of other declarations. The format of attributes is fairly simple.
    635 
    636 .. parsed-literal::
    637 
    638   *attributes*:
    639     *attribute* *attributes*:sub:`opt`
    640 
    641   *attribute*:
    642     '[' *identifier* ']'
    643 
    644 Any *identifier* can be used as an attribute, and each declaration specifies what attributes can be applied to it.
    645 
    646 Modularizing a Platform
    647 =======================
    648 To 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). 
    649 
    650 The 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.
    651 
    652 **Macro-guarded copy-and-pasted definitions**
    653   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:
    654 
    655   .. parsed-literal::
    656 
    657     #ifndef _SIZE_T
    658     #define _SIZE_T
    659     typedef __SIZE_TYPE__ size_t;
    660     #endif
    661 
    662   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.
    663 
    664 **Conflicting definitions**
    665   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).
    666 
    667 **Missing includes**
    668   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.
    669 
    670 **Headers that vend multiple APIs at different times**
    671   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.
    672 
    673 To 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.
    674 
    675 Future Directions
    676 =================
    677 Modules is an experimental feature, and there is much work left to do to make it both real and useful. Here are a few ideas:
    678 
    679 **Detect unused module imports**
    680   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.
    681 
    682 **Fix-Its for missing imports**
    683   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!).
    684 
    685 **Improve modularize**
    686   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.
    687 
    688 **C++ Support**
    689   Modules clearly has to work for C++, or we'll never get to use it for the Clang code base.
    690 
    691 Where To Learn More About Modules
    692 =================================
    693 The Clang source code provides additional information about modules:
    694 
    695 ``clang/lib/Headers/module.map``
    696   Module map for Clang's compiler-specific header files.
    697 
    698 ``clang/test/Modules/``
    699   Tests specifically related to modules functionality.
    700 
    701 ``clang/include/clang/Basic/Module.h``
    702   The ``Module`` class in this header describes a module, and is used throughout the compiler to implement modules.
    703 
    704 ``clang/include/clang/Lex/ModuleMap.h``
    705   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).
    706 
    707 PCHInternals_
    708   Information about the serialized AST format used for precompiled headers and modules. The actual implementation is in the ``clangSerialization`` library.
    709 
    710 .. [#] Automatic linking against the libraries of modules requires specific linker support, which is not widely available.
    711 
    712 .. [#] 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.
    713 
    714 .. [#] 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.
    715 
    716 .. [#] 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.
    717 
    718 .. [#] 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.
    719 
    720 .. _PCHInternals: PCHInternals.html
    721  
    722