1 | <!--
|
---|
2 | I fleshed out some problems with strong module theory after working through some examples and writing some code, and got a better idea of how to actually implement my vision. The cynic in me says that I've simply solved many hard problems by slapping "compile-time reflection" on it (which is by no means a simple thing to engineer), but it does solve a number of glaring issues with my previous attempts. Additionally, it takes many concepts from other programming languages, so the strategy seems at least reasonable.
|
---|
3 | Now, the biggest hole in my proposal is that I do not address the issue of initialization order (I'm kind of putting this one off, because I think I can handle this separately). Additionally, I still need to present "walkthrough examples" and present a formalism.
|
---|
4 |
|
---|
5 | Motivation
|
---|
6 | Goal
|
---|
7 | Strategy (high-level)
|
---|
8 | Strategy (implementation details)
|
---|
9 | Handling unboxed types
|
---|
10 | C macros are not exportable
|
---|
11 | Import ordering does not matter
|
---|
12 | Forward declarations are unnecessary
|
---|
13 | Explicit transitive dependencies
|
---|
14 | Exporting inline functions
|
---|
15 | Generating multiple module interfaces
|
---|
16 | Modules use `import` instead of `#include`
|
---|
17 | Forall polymorphism
|
---|
18 | Walkthrough
|
---|
19 | Formalism
|
---|
20 | -->
|
---|
21 |
|
---|
22 | # Modules proposal (v4, strong modules)
|
---|
23 |
|
---|
24 | ## Motivation
|
---|
25 |
|
---|
26 | Let's walk through the design process of making a C module system.
|
---|
27 |
|
---|
28 | First things first: **Why do we need modules?** From a theoretical standpoint, it's superfluous - a module system restricts your creative freedom because it makes you think that organizing code and organizing data is different, even though they use the same concepts. However, in practical scenarios it's useful to have a module system because we care about building things fast, reliably, and spread across multiple teams with varying skill levels. **We want modules because it helps us focus on only the parts of the program we're working on.**
|
---|
29 |
|
---|
30 | But **isn't a C translation unit a module?** *(a c translation unit is a `.c` file after preprocessing)* It has `static` and `extern`, but there isn't a good way to analyze which symbols are used where in the program. A symbol defined in `foo.c` can be declared in `foo.h`, but that symbol can also be declared in `unrelated.c`. Calling a C translation unit a module is like saying a struct is well-defined, even if it can only be used if some arbitrary set of functions is called. We don't consider it a module because it doesn't provide a way to control which modules depend on its contents. **We argue that C translation units, with some access control, can be considered a module.**
|
---|
31 |
|
---|
32 | ## Goal
|
---|
33 |
|
---|
34 | Let's first clarify what we're trying to achieve with our modules. The term "module" is as abused as "polymorphism" in programming languages, which makes it challenging to determine what we're working towards with a module system for C. Let's start:
|
---|
35 |
|
---|
36 | * **Make C translation units into modules** (needs some access control on `extern`)
|
---|
37 | * **Generate module interfaces** (so .h files are not necessary)
|
---|
38 | * **Each feature is incremental** (each part of the module system requires minimal changes to existing C code - features should feel optional, functioning more like syntactic sugar)
|
---|
39 |
|
---|
40 | Put simply, we want to require minimal changes to the existing C workflow (source code, makefile, programmer thought process, compiler implementation) while providing something similar to Rust modules. There are other aspects of modules that we'll want to cover - initialization order, modules defined across multiple files, modules nested within a file, module friendship - which have their various solutions, but we'll get to them after working with these main 3 goals.
|
---|
41 |
|
---|
42 | ## Strategy (high-level)
|
---|
43 |
|
---|
44 | From [this article](https://thunderseethe.dev/posts/whats-in-a-module/) (more specifically, [Backpack in Haskell](https://plv.mpi-sws.org/backpack/)), we are introduced to this concept of **weak and strong modules**. A weak module is tied to its dependencies, meaning that swapping out a dependent module for another requires recompilation. Contrast this with a strong module, where we can provide the dependent modules after the module has been compiled.
|
---|
45 |
|
---|
46 | For our purposes, the difference is thus: **weak modules are dependent on other modules, while strong modules are dependent on module interfaces.** In order to achieve this, we need modules to control what is exported to other modules, which includes limiting transitive dependencies between modules. This will allow modules to only expose what they own, allowing us to avoid depending on module details. By having modules generate their interfaces, we can separate the parts of C that force modules to be "weak" into the interface generation step, so that the compilation step can work with "strong" modules.
|
---|
47 |
|
---|
48 | From a logical perspective, modules can only export symbols that they own, and only use symbols that they import. Some concessions need to be made to support the complexities surrounding unboxed types, but this is limited to what is absolutely necessary. Note that C macros cannot be exported, since they run before module processing. The order of imports does not affect compilation - they can be reordered without changing module behaviour. In fact, forward declarations are unnecessary in these modules - we scan all top-level declarations while determining what to export, so the symbols are already in memory by the time we resolve definitions. Explicit transitive dependencies can be created with the use of `export import` - from the perspective of the importing module, it has the same behaviour as if the exported module were imported separately. To support inline functions, we introduce the distinction between a module being visible to the compiler (in order to expand function definitions) and being visible to an importing module. Since we can generate our own module interfaces, we can generate multiple interfaces, which helps solve the module friendship problem. Modules are imported using `import` instead of `#include`, and a translation unit need not be a module to import modules. The forall keyword is an addition from Cforall to support polymorphism, with polymorphic functions using vtables and a single implementation. This has a straightforward implementation in modules (the module that owns the polymorphic function holds the implementation), though if we wish to support specialization for polymorphic functions (ie. multiple implementations), the module system would need to be updated to support this. More details in the next section.
|
---|
49 |
|
---|
50 | ## Strategy (implementation details)
|
---|
51 |
|
---|
52 | A module is a collection of symbol definitions, which it can export to other modules. It may also import other modules' symbols, which it uses to define its symbols. There are 3 kinds of symbols in C to consider: variables, functions and types.
|
---|
53 |
|
---|
54 | ```
|
---|
55 | --------------------------------------
|
---|
56 | | module B; |
|
---|
57 | imports | import A; | exports
|
---|
58 | A::a --------> | export int b = a; | --------> B::b
|
---|
59 | A::aa | export struct aa foobar(); | B::foobar (+ A::aa?)
|
---|
60 | | export struct bb {struct aa foo;}; | B::bb (+ A::aa?)
|
---|
61 | --------------------------------------
|
---|
62 | ```
|
---|
63 |
|
---|
64 | ### Handling unboxed types
|
---|
65 |
|
---|
66 | Above, we note a problem: whereas functions and variables can export only their symbol declarations, we need the definitions of types in order to use them fully. Languages that use boxed types (eg. Java, Go) do not have this restriction, since the caller only needs to reserve space for a pointer (eg. when calling `B.foobar`). In contrast, C and other systems programming languages (eg. C++, Rust) require handling unboxed types, since it demands control over pointer indirection (also, there may not be a heap available to support boxed types). This means we need to know the definitions of types in order to use them, even if it's just to allocate enough space on the stack. In Rust, this is done by compiling an entire crate at a time; in C/C++, this is done by including transitive dependencies in headers.
|
---|
67 |
|
---|
68 | We make the following insight: **if we have an oracle that tells us the size and alignment of any type, we can use unboxed types without needing to expose type definitions.** For example, a caller of `B.foobar` need only know that the structure returned has size 32 bytes, aligned to 8 bytes, in order to use it. For type safety, the caller should also know the type returned is `A.aa`, but the caller does not need to know the inner fields of `A.aa`. This means, if `B` does not change, any module that uses `B` does not need to be recompiled unless `A.aa` exceeds its size or alignment allocations. The extra condition that any module that uses `B` needs to be recompiled if `A.aa` exceeding its size or alignment allocations does break the "strong module guarantee" (since `A` is not re-exported, it would ideally not be considered a dependency), but the scope of this has been limited to only what is absolutely necessary to support unboxed types. If the module that uses `B` wants to access the inner fields of `A.aa`, it needs to import `A`.
|
---|
69 |
|
---|
70 | How do we actually implement this "oracle"? After analyzing the alternatives, option 2 feels the most "natural", despite its inherent complexity.
|
---|
71 | 1. We can perform whole-program analysis to analyze all type-related information, similar to how Rust does it. This allows for maximum expressiveness since this gives us full visibility into the entire program, and can rely on the analyzer to automatically resolve circularly dependent modules (eg. module `A` imports module `B`, which in turn imports module `A`, but in a way that is still resolvable). However, this breaks the principle of separate compilation by accessing the entire program, and raises questions such as "what gets reanalyzed if `A` changes?"
|
---|
72 | 2. We can also extract type information into a separate generated module interface. This aligns closer to the principle of separate compilation, though it still requires special analysis to resolve circularly dependent modules (eg. module `A` imports module `B`, which in turn imports module `A`, but in a way that is still resolvable. In order to avoid a circular import error, this requires only importing the symbols from `B` that `A` needs). A criticism is that this does not really resolve the transitive dependency issue; in a certain sense, it's offloading the problem to a compile-time reflection mechanism. This level of compile-time reflection is also non-trivial, poentially requiring significant re-engineering and validation of an existing C compiler in order to implement. Despite these concerns, this strategy seems to align best with general intuitition when analyzing an existing codebase.
|
---|
73 |
|
---|
74 | ### C macros are not exportable
|
---|
75 |
|
---|
76 | **C preprocessing runs first, then the module system generates module interfaces for exporting symbols, then the translation unit is compiled using the generated module interfaces.** The module system runs after preprocessing because we may want to use C macros to generate export definitions. However, this means the module system cannot export C macros, because they have already been evaluated at that point.
|
---|
77 |
|
---|
78 | Supporing C macro exports may be possible if we made the preprocessor module-aware. This could be done by augmenting the C preprocessor to check for a `module;` statement or having all module-related statements be `#pragma` directives instead. However, this overcomplicates the preprocessor, making it both hard to develop and demonstrate how to use it. Additionally, certain functionalities such as compile-time reflection are not compatible with the "one pass" nature of the C preprocessor. Put simply, the set of functionalities we wish to support with our module system is complex enough that it warrants being a separate system.
|
---|
79 |
|
---|
80 | As it currently stands, one can achieve "exported macros" by simply putting them in a header file, then using `#include`. It could also be argued that the trait system in Cforall makes this kind of metaprogramming unnecessary for most use-cases. That being said, this proposal permits future extensions which provide some form of metaprogramming that executes after the module system. Some ideas for inspiration include: string mixins from D, procedural macros from Rust, and staged functions from Zig.
|
---|
81 |
|
---|
82 | ### Import ordering does not matter
|
---|
83 |
|
---|
84 | A key problem with `#include` is that textual inclusion is order-dependent - including `a.h` before `b.h` may result in different behaviour than `b.h` before `a.h`. Not only does this cause confusion among developers, it also affects compilation speed - while headers can be precompiled, they must always account for the possibility of a C macro completely changing the meaning of the header file.
|
---|
85 |
|
---|
86 | The fact that each import is independent from each other assures developers that reformatting the import list will not break functionality. Additionally, since modules can only export symbols that they own (with the caveat on types), it is clear to the developer what a module is getting from another.
|
---|
87 |
|
---|
88 | Since the module system runs after the C preprocessor (and requires a certain formatting of the file), the generated module interfaces can be optimized for maximum compiler efficiency. The potential gains are significant: when the standard library became available to import in C++23 (ie. `import std;`), the time to compile a "Hello World" program essentially halved. This significant reduction in build times likely translates to faster iterations and more productive developers.
|
---|
89 |
|
---|
90 | As a point for future development, the generated module interfaces can also be analyzed by a language server in order to provide accurate suggestions to the developer. This may be augmented with AI in order to provide robust code-generation capabilities.
|
---|
91 |
|
---|
92 | ### Forward declarations are unnecessary
|
---|
93 |
|
---|
94 | Since we scan all top-level declarations while generating module interfaces, forward declarations are unnecessary. In fact, the module system can resolve what would otherwise be incomplete types in C. In the following example, even if we added `struct Other;` after `module;`, `struct Other details;` would still break. However, with our module system, we can resolve this.
|
---|
95 |
|
---|
96 | ```
|
---|
97 | module;
|
---|
98 | export struct Node {
|
---|
99 | int id;
|
---|
100 | struct Other details;
|
---|
101 | };
|
---|
102 | struct Other {
|
---|
103 | int symbols[max_symbols_supported];
|
---|
104 | };
|
---|
105 | const int max_symbols_supported = 100;
|
---|
106 | ```
|
---|
107 |
|
---|
108 | This property of being able to "look ahead" in a file echoes some parallels with classes in object-oriented languages. In those languages, a method's definition can call a method defined later, but still within the same class definition. In fact, modules and objects share many features (eg. abstraction, encapsulation). The main difference is that a module behaves more like a singleton class (as they are actually sections of code), wheras objects can be instantiated.
|
---|
109 |
|
---|
110 | ### Explicit transitive dependencies
|
---|
111 |
|
---|
112 | There are many cases where development of a module is broken up into parts, yet is often used together. In other cases, some modules are meant to be used in conjunction with another module's symbols.
|
---|
113 |
|
---|
114 | ```
|
---|
115 | // module std
|
---|
116 | module;
|
---|
117 | export import std/vector;
|
---|
118 | export import std/iostream;
|
---|
119 |
|
---|
120 | // module wrapper
|
---|
121 | module;
|
---|
122 | export import std/map;
|
---|
123 | export import std/string;
|
---|
124 | export typedef map[string, string] stringmap;
|
---|
125 |
|
---|
126 | // module client
|
---|
127 | module;
|
---|
128 | import std; // this is equivalent to import std/vector;
|
---|
129 | // import std/iostream;
|
---|
130 | // import std; // superfluous in this case
|
---|
131 | import wrapper; // this is equivalent to import std/map;
|
---|
132 | // import std/string;
|
---|
133 | // import wrapper; // for stringmap
|
---|
134 | ```
|
---|
135 |
|
---|
136 | In the above case, `std` allows developers to import a common set of functionality without needing to concern themselves with the explicit naming of modules. `wrapper` handles a special case with exporting `typedef`: Since `wrapper` does not own `map` or `string`, it should export the modules that contain them if `client` expects to use the fields of `map[string, string]` (as opposed to simply knowing that `stringmap` is a `map[string, string]`).
|
---|
137 |
|
---|
138 | ### Exporting inline functions
|
---|
139 |
|
---|
140 | Inline functions require the definition of a function to be available. Similar to the section on "handling unboxed types", we would wish to avoid unwanted transitive dependencies if possible.
|
---|
141 |
|
---|
142 | ```
|
---|
143 | // module inlined
|
---|
144 | module;
|
---|
145 | import supporting;
|
---|
146 | export inline int power(int a, int b) {
|
---|
147 | int ret = 1;
|
---|
148 | for (int i=0; i<b; ++i) ret = multiply(ret, a);
|
---|
149 | return ret;
|
---|
150 | }
|
---|
151 | // module supporting
|
---|
152 | module;
|
---|
153 | import deeper;
|
---|
154 | export int multiply(int a, int b) {
|
---|
155 | int ret = 0;
|
---|
156 | for (int i=0; i<b; ++i) ret = add(ret, a);
|
---|
157 | return ret;
|
---|
158 | }
|
---|
159 | // module deeper
|
---|
160 | module;
|
---|
161 | export int add (int a, int b) {return a + b;}
|
---|
162 | // module client
|
---|
163 | module;
|
---|
164 | export int foobar() {return power(10, 5);}
|
---|
165 | ```
|
---|
166 |
|
---|
167 | In this scenario, to compile `client`, the compiler needs the exported symbols of `inlined` and `supporting`. Note that the compiler does not need `deeper` because `multiply()` is not an inline function. However, `client` cannot access symbols from `supporting` unless it imports it directly.
|
---|
168 |
|
---|
169 | If `inlined` has not generated its module interfaces by the time `client` is being compiled, then the presence of a single inlined function would cause all modules imported by `inlined` to need to be traversed, since the module system cannot ascertain which module contains `multiply()`. After the module interfaces are generated (and the modules have not been edited in the meantime), we can use those instead of traversing imports.
|
---|
170 |
|
---|
171 | There is another optimization that can be made here: have all exported inline functions generate actual function definitions, so that if importers choose not to expand the function definition, they do not need to regenerate the function definition. It may be tricky to implement if the functionality is not already supported, though this feature is optional.
|
---|
172 |
|
---|
173 | ### Generating multiple module interfaces
|
---|
174 |
|
---|
175 | A common problem with encapsulation is that certain modules may need certain functionalities from others that should otherwise be private. In object-oriented languages, this is accomplished by designating "friend classes", which get full access to a class' internals. However, this "all or nothing" approach lacks fine-grained control. Another alternative is to present multiple interfaces for importers to choose from, facilitated by the fact that we already generate module interfaces.
|
---|
176 |
|
---|
177 | ```
|
---|
178 | // module multiple
|
---|
179 | module;
|
---|
180 | export int public_function() {return 100;}
|
---|
181 | export(internal) int internal_function() {return 10;}
|
---|
182 | int private_function() {return 1;}
|
---|
183 | // module kernel
|
---|
184 | module;
|
---|
185 | import multiple(internal); // can use public_function, internal_function
|
---|
186 | // module client
|
---|
187 | module;
|
---|
188 | import multiple; // can use public_function
|
---|
189 | ```
|
---|
190 |
|
---|
191 | Here, `internal` is a user-defined tag. We could use `export(aaa)` and `import multiple(aaa)` instead. Additionally, we can attach multiple tags to an export (eg. `export(aaa, internal)`) and import with multiple tags (eg. `import multiple(aaa, internal)`). Any symbol that is exported without a tag is always imported, and a symbol that is exported with tags is imported if the import statement includes one of its tags.
|
---|
192 |
|
---|
193 | Another details is that `private_function()` is technically still accessible by accessing its mangled C name directly. If we truly wanted it to be private, we could use `static`. An additional functionality that the module system could provide is to automatically append `static` to these functions.
|
---|
194 |
|
---|
195 | ### Modules use `import` instead of `#include`
|
---|
196 |
|
---|
197 | A module is defined by having `module;` be the first statement in a source file (somewhat similar to C++20 modules). Internally, modules work like namespaces, implemented by prepending the module name in front of all declared symbols. There are multiple alternatives to determine the module name - we use option 2 for its brevity:
|
---|
198 | 1. Have the user define the module names (eg. `module A;`). This is similar to how Java and C++ require specifying packages and namespaces, respectively. This gives the developer some flexibility on naming, as it is not tied to the file system. However, it raises some questions surrounding how module discovery works (if a module imports `A`, where is `A`?).
|
---|
199 | 2. Have the module names be defined from a "root directory" (eg. `module;` is module `A` because it is located at `src/A.cfa`, and `src/` is defined as the root directory). This creates import paths that look similar to include paths, allowing us to align more closely with existing C programmers. When searching for an appropriate module, a search is conducted first from the current directory, then we look for an appropriate library (similar to the include path in C). A downside is that this precludes adding nested modules (ie. module definitions within a module file), though nested modules are arguably not that important.
|
---|
200 |
|
---|
201 | Another design choice that was made was to have files with the same name as a folder exist outside their folder. For example, module `graph` exists at `src/graph.cfa`, while module `graph/node` exists at `src/graph/node.cfa`. The alternative is to have module `graph` at `src/graph/mod.cfa` - this may be more familiar to some developers, but this complicates module discovery (eg. if there exists a module at `src/graph.cfa` at the same time, which takes precedence? Does `graph` need to `import ../analysis` in order to import the module at `src/analysis`?). Taking insights from Rust's move from `mod.rs` to files with the same name as the folder, we opt to use the more straightforward strategy.
|
---|
202 |
|
---|
203 | Since modules prepend their module name in front of all declared symbols, we use `import` instead of `#include` when importing modules (this is also necessary to support some of our compile-time reflection mechanisms, which would be challenging to implement in the preprocessor). This automatically removes the module name from the front of the symbol names. If this causes symbol clashes, they can be resolved using attributes (eg. `A::a` means "symbol `a` within module `A`").
|
---|
204 |
|
---|
205 | This prepending of the module name in front of all symbols within a module can result in undesirable behaviour if we use `#include` within a module, as all of its contents will be prepended with the module name. To resolve this, we introduce extern blocks, which escape the module prefixing (eg. `extern { #include <stdio.h> }`, though with a newline after the `>`).
|
---|
206 |
|
---|
207 | By having modules prepend their names to their symbols, we can add functionality to perform a "unity build", as every symbol can be disambiguated. This would allow us to balance a "development configuration" with the benefits of modularization, alongside a "release configuration" with maximum optimizations.
|
---|
208 |
|
---|
209 | ### Forall polymorphism
|
---|
210 |
|
---|
211 | The forall keyword is an addition to Cforall to support polymorphism, with polymorphic functions using vtables and a single implementation. If a module exports a forall statement, the module owns the polymorphic function implementations, while the polymorphic function declarations are exported (if these were declared inline, the definition could be exported, similar to C++20 modules). Polymorphic types are instantiated from the caller's side, so their definitions are exported. This does not present the same issues as those in the "handling unboxed types" section, as non-polymorphic function declarations cannot inadvertently capture these types (thus, they cannot "leak" outside of a module).
|
---|
212 |
|
---|
213 | An interesting case is to consider if Cforall could be updated to perform specialization (multiple implementations for a single function) in addition to the single implementation strategy. This would be similar to Rust's `impl` vs `dyn` traits. To support this, the module system would need to be updated, as we would want the multiple implementations to exist within the module that owns the forall statement.
|
---|
214 |
|
---|
215 | ## Walkthrough
|
---|
216 |
|
---|
217 | ## Formalism
|
---|
218 |
|
---|