D import idiom compilation time

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Jan 8 15:35:14 UTC 2019


On Tue, Jan 08, 2019 at 03:18:03PM +0000, Martin Tschierschke via Digitalmars-d wrote:
[...]
> With "real local import" I was referring to the "new import idiom" in
> this thread, provided by  localimport.dub.pm
[...]

The intent of that import idiom is an import whose scope is limited to
the expression it's in. It's a way of pulling in a specific symbol
without "polluting" the surrounding scope. E.g. currently, if you have a
module-scope declaration that requires an imported symbol, you have no
choice but to import the symbol into the containing scope:

	// This import line is required otherwise the sig constraint
	// won't work.
	import std.range.primitives : isInputRange;
	auto myRangeFunc(R)(R range) if (isInputRange!R) { ... }

If this is the only function in a module of say 100 functions that
requires std.range.primitives, it seems wasteful to import it into the
entire module's scope.  With the new import idiom, we can do this:

	// N.B.: no more imports in module scope!
	auto myRangeFunc(R)(R range) if (from.std.range.isInputRange!R)
	{ ... }

Which also makes the declaration carry it's own import dependencies, so
when you decide to refactor and move this function into another module,
you'll never have to worry about also moving/copying the global import
statement.

This is the primary use case of this idiom.

If you actually need the import symbols into the containing scope, just
use the built-in import statement instead! :-D

	auto myRangeFunc(R)(R range) if (from.std.range.isInputRange!R)
	{
		// We need std.uni in this function, so just pull it
		// into the function scope. No need to pull out the
		// expression-local import warhead!
		import std.uni : isWhite;

		while (!range.empty && isWhite(range.front))
			range.popFront;
		...
		// more uses of isWhite here
		...
	}


T

-- 
LINUX = Lousy Interface for Nefarious Unix Xenophobes.


More information about the Digitalmars-d mailing list