ImportC: On the issue of using a type from two different C files
Adam D Ruppe
destructionator at gmail.com
Sat Aug 27 12:32:21 UTC 2022
On Saturday, 27 August 2022 at 03:07:25 UTC, Mike Parker wrote:
> Martin disagreed, and proposed an alternative:
>
>> Martin said that one problem with that approach is that a D
>> module would have access to symbols it didn't import. He
>> suggested the ideal solution would be for each header to have
>> its own module that doesn't change from one invocation of the
>> compiler to the next.
This is why I said "be an alias" in the chat thread. The `import
c` module essentially selectively imports just the things
actually declared from the magic module, giving the same
behavior, but since the canonical name+definition is elsewhere
and merged in there, the aliases won't cause type conflicts.
The implementation might be easier said than done, since you'd
have a pseudo-module being mutated through the import process. I
expect a high probability of forward reference bugs cropping up.
But the concept is something we can test by hand. Taking the same
example from my blog that fails with importC on dmd master an
doing instead:
---
module __magic_importC;
// representing all the C definitions imported
struct FILE;
extern(C) int printf(const char*, ...);
extern(C) int fclose(FILE*);
extern(C) void saySomethingToAFile(FILE*);
extern(C) FILE* openAFile();
---
then
---
module b;
// it does a public selective import
public import magic : FILE, printf, fclose, openAFile;
---
and
---
module b2;
// again public selective import
public import magic : FILE, printf, fclose, saySomethingToAFile;
---
And now the test program compiles successfully:
---
import b;
import b2;
void main() {
auto fp = openAFile();
scope(exit) fclose(fp);
saySomethingToAFile(fp);
printf("Hello\n");
}
---
and if you remove an import, you correctly get:
d.d(7): Error: undefined identifier `saySomethingToAFile`
thanks to the selective import mechanism.
This scheme is compatible with both C and D declaration rules,
doesn't have a big namespace surprise (the compiler should also
just forbid importing the magic internal implementation module so
people don't try to poke that directly), and.... might be doable.
Again, possibility of bugs with the extraordinary magic module
being mutated through the process, but since that's all inside
dmd thanks to the selective import hiding anything you can't see
in the right order anyway and the mutations are strictly additive
we ought to be able to cover it up and make it work.
More information about the Digitalmars-d
mailing list