/**
* Process orchestration for the `--better-c`, `--wasm` and `--wasm-bare` runner modes:
* extract the annotated tests (see $(MREF sparkles,test_runner,extract)),
* generate a standalone program, compile it for the special environment, and
* execute it.
*
* Uses only `std.process`/`std.file` so it works in every host package —
* including `sparkles:base`, whose test build has no `core-cli`.
*/
module (package) sparklessparkles.(package) sparkles.test_runnertest_runner.(module) sparkles.test_runner.driverProcess orchestration for the --better-c, --wasm and --wasm-bare runner modes:
extract the annotated tests (see sparkles.test_runner.extract),
generate a standalone program, compile it for the special environment, and
execute it.
Uses only std.process/std.file so it works in every host package —
including sparkles:base, whose test build has no core-cli.
driver;
import (package) sparklessparkles.(package) sparkles.test_runnertest_runner.(module) sparkles.test_runner.extractSource extraction of unittest bodies and generation of standalone
-betterC / WebAssembly test programs.
unittest blocks cannot run under -betterC (druntime's test driver is
absent) or on wasm32 targets, so the runner's --better-c / --wasm
modes extract the annotated tests: each test's body is sliced out of
its source file (located via __traits(getLocation) metadata gathered at
discovery), re-emitted as a named function in a generated program with a
hand-rolled main, compiled for the special environment, and executed.
The same approach — reflection-driven instead of parser-driven — replaces
dlang's libdparse-based tests_extractor.
Extracted tests import their module, so they can only reference its
public symbols. By default the driver also compiles that module into
the generated program (-i=<module>), so ordinary functions are reachable
and not just templates; a test that opts out with
@betterC(selfContained: true) keeps its module out entirely and is then
limited to templates and CTFE-able code (the phobos @betterC suite's
model, and what lets a module that cannot itself compile under -betterC
still host such a test).
This module also generates the @ctfe probe program (see
generateCtfeProgram), which involves no extraction at all: the
probe imports the tests' modules and selects tests by reflection, so their
bodies stay in place.
Everything in this module is pure string processing — the process
orchestration lives in sparkles.test_runner.driver.
extract : (struct) sparkles.test_runner.extract.CtfeTargetOne @ctfe test to force through CTFE in a generated probe program.
CtfeTarget, (struct) sparkles.test_runner.extract.ExtractedTestOne extracted test, ready to be emitted into a generated program.
ExtractedTest,
(alias) sparkles.test_runner.driver.extractUnittestBody = string sparkles.test_runner.extract.extractUnittestBody(string source, ulong line) pure @safeExtracts the body of the unittest block declared at line (its
__traits(getLocation) line): the text between the block's braces,
without the braces themselves. Returns null when no block is found.
extractUnittestBody, (alias) sparkles.test_runner.driver.generateBetterCProgram = string sparkles.test_runner.extract.generateBetterCProgram(in sparkles.test_runner.extract.ExtractedTest[] tests) pure @safeA complete standalone -betterC program running the given tests: the
extracted functions plus an extern(C) main announcing each test before
running it (so an assert abort is attributable).
generateBetterCProgram, (alias) sparkles.test_runner.driver.generateCtfeProgram = string sparkles.test_runner.extract.generateCtfeProgram(in sparkles.test_runner.extract.CtfeTarget[] targets) pure @safeA complete probe program forcing the given @ctfe tests through CTFE.
The probe imports each test's module and selects the tests by
reflection (matching __traits(getLocation) lines), so test bodies stay
in their home modules — private symbols keep working and no source
extraction is involved. It is meant to be compiled with -o- -unittest
together with the modules' source files: semantic analysis (and therefore
CTFE) only, no code generation. A failing test is a compile error whose
closing error instantiating line carries the test's display name.
generateCtfeProgram,
(alias) sparkles.test_runner.driver.generateWasiProgram = string sparkles.test_runner.extract.generateWasiProgram(in sparkles.test_runner.extract.ExtractedTest[] tests) pure @safeA complete WASI program running the given tests (--wasm): the extracted
functions plus a main that announces and runs each one, catching what it
throws, so one failing test does not hide the rest. The full druntime is
there, so a failed assert is an AssertError like any other Throwable.
The exit status is 1 when any test failed.
generateWasiProgram, (alias) sparkles.test_runner.driver.generateWasmBareJsShim = string sparkles.test_runner.extract.generateWasmBareJsShim(in sparkles.test_runner.extract.ExtractedTest[] tests, string wasmFile) pure @safeThe JavaScript shim executing a generated wasm test module under node,
deno, or bun: instantiates the module and calls each run_test_<i>
export, reporting per-test outcomes.
generateWasmBareJsShim, (alias) sparkles.test_runner.driver.generateWasmBareProgram = string sparkles.test_runner.extract.generateWasmBareProgram(in sparkles.test_runner.extract.ExtractedTest[] tests) pure @safeA complete bare wasm32 test module (--wasm-bare): the extracted
functions, each exported as test_<i> for individual invocation by the
host shim, plus a trapping __assert handler (there is no libc on bare
wasm32, so a failed assert traps and surfaces as a host-side
RuntimeError).
generateWasmBareProgram, (alias) sparkles.test_runner.driver.sourceRootOf = string sparkles.test_runner.extract.sourceRootOf(string file, string moduleName) pure nothrow @safeDerives the source root of a module from its file path and dotted name:
("libs/base/src/sparkles/base/buffer.d", "sparkles.base.buffer")
yields "libs/base/src". Returns null when the path does not end with
the module path. Either separator matches: on Windows the compiler reports
libs\base\src\sparkles\base\buffer.d, and the root keeps its own
separators.
sourceRootOf;
import (package) sparklessparkles.(package) sparkles.test_runnertest_runner.(module) sparkles.test_runner.modelData model of the test runner: descriptions of discovered tests and the
results of executing them.
Everything here is runtime data — the compile-time discovery that produces
it lives in sparkles.test_runner.discovery.
model : (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test;
/// Where the modes' messages go. The core prints nothing (process-model
/// TRM1): its client renders these, to a terminal or as task output.
struct (struct) sparkles.test_runner.driver.ModeReportWhere the modes' messages go. The core prints nothing (process-model
TRM1): its client renders these, to a terminal or as task output.
ModeReport
{
/// A mode's report: per-test lines, the tests' own output.
void delegate((alias) object.string = stringstring) @safe (field) void delegate(string) @safe sparkles.test_runner.driver.ModeReport.outputA mode's report: per-test lines, the tests' own output.
output;
/// Why a mode skipped or failed, and the commands echoed under `-v`.
void delegate((alias) object.string = stringstring) @safe (field) void delegate(string) @safe sparkles.test_runner.driver.ModeReport.diagnosticsWhy a mode skipped or failed, and the commands echoed under -v.
diagnostics;
}
/// `args` and a line feed, to `report`'s output.
private void void sparkles.test_runner.driver.say!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safeargs and a line feed, to report's output.
say(Args...)(in (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, ArgsArgs (parameter) Args argsargs)
{
import (package) stdstd.(module) std.convA one-stop shop for converting values from one type to another.
Category Functions Generic asOriginalType castFrom parse to toChars bitCast Strings text wtext dtext writeText writeWText writeDText hexString Numeric octal roundTo signed unsigned Exceptions ConvException ConvOverflowException
Source
std/conv.d
conv : (alias template) text = std.conv.text(T...)(T args) if (T.length > 0)Convenience functions for converting one or more arguments
of any type into _text (the three character widths).
text;
if ((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.reportwhere the modes' messages go
report.(field) void delegate(string) @safe sparkles.test_runner.driver.ModeReport.outputA mode's report: per-test lines, the tests' own output.
output !is null)
(parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.reportwhere the modes' messages go
report.(field) void delegate(string) @safe sparkles.test_runner.driver.ModeReport.outputA mode's report: per-test lines, the tests' own output.
output(string std.conv.text!(string, string)(string __param_0, string __param_1) pure nothrow @safeConvenience functions for converting one or more arguments
of any type into text (the three character widths).
text(args, "\n"));
}
/// `text`, as it is, to `report`'s output.
private void void sparkles.test_runner.driver.sayRaw(in sparkles.test_runner.driver.DriverOptions options, string text)text, as it is, to report's output.
sayRaw(in (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, (alias) object.string = stringstring (parameter) string texttext)
{
if ((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.reportwhere the modes' messages go
report.(field) void delegate(string) @safe sparkles.test_runner.driver.ModeReport.outputA mode's report: per-test lines, the tests' own output.
output !is null)
(parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.reportwhere the modes' messages go
report.(field) void delegate(string) @safe sparkles.test_runner.driver.ModeReport.outputA mode's report: per-test lines, the tests' own output.
output((parameter) string texttext);
}
/// `args` and a line feed, to `report`'s diagnostics.
private void void sparkles.test_runner.driver.warn!(string, string, string, string, string, string, string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2, string __param_3, string __param_4, string __param_5, string __param_6, string __param_7, string __param_8) @safeargs and a line feed, to report's diagnostics.
warn(Args...)(in (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, ArgsArgs (parameter) Args argsargs)
{
void sparkles.test_runner.driver.warnTo!(string, string, string, string, string, string, string, string)(in sparkles.test_runner.driver.ModeReport report, string __param_1, string __param_2, string __param_3, string __param_4, string __param_5, string __param_6, string __param_7, string __param_8) @safeargs and a line feed, to report's diagnostics.
warnTo((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.reportwhere the modes' messages go
report, args);
}
/// ditto
private void void sparkles.test_runner.driver.warnTo!(string, string, string, string, string, string, string, string)(in sparkles.test_runner.driver.ModeReport report, string __param_1, string __param_2, string __param_3, string __param_4, string __param_5, string __param_6, string __param_7, string __param_8) @safeargs and a line feed, to report's diagnostics.
warnTo(Args...)(in (struct) sparkles.test_runner.driver.ModeReportWhere the modes' messages go. The core prints nothing (process-model
TRM1): its client renders these, to a terminal or as task output.
ModeReport (parameter) const(sparkles.test_runner.driver.ModeReport) reportreport, ArgsArgs (parameter) Args argsargs)
{
import (package) stdstd.(module) std.convA one-stop shop for converting values from one type to another.
Category Functions Generic asOriginalType castFrom parse to toChars bitCast Strings text wtext dtext writeText writeWText writeDText hexString Numeric octal roundTo signed unsigned Exceptions ConvException ConvOverflowException
Source
std/conv.d
conv : (alias template) text = std.conv.text(T...)(T args) if (T.length > 0)Convenience functions for converting one or more arguments
of any type into _text (the three character widths).
text;
if ((parameter) const(sparkles.test_runner.driver.ModeReport) reportreport.(field) void delegate(string) @safe sparkles.test_runner.driver.ModeReport.diagnosticsWhy a mode skipped or failed, and the commands echoed under -v.
diagnostics !is null)
(parameter) const(sparkles.test_runner.driver.ModeReport) reportreport.(field) void delegate(string) @safe sparkles.test_runner.driver.ModeReport.diagnosticsWhy a mode skipped or failed, and the commands echoed under -v.
diagnostics(string std.conv.text!(string, string, string, string, string, string, string, string, string)(string __param_0, string __param_1, string __param_2, string __param_3, string __param_4, string __param_5, string __param_6, string __param_7, string __param_8) pure nothrow @safeConvenience functions for converting one or more arguments
of any type into text (the three character widths).
text(args, "\n"));
}
/// Options shared by both driver modes.
struct (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions
{
(alias) object.string = stringstring (field) string sparkles.test_runner.driver.DriverOptions.compilerexplicit D compiler; empty = $DC, then ldc2, dmd
compiler; /// explicit D compiler; empty = `$DC`, then `ldc2`, `dmd`
(alias) object.string = stringstring[] (field) string[] sparkles.test_runner.driver.DriverOptions.importPathsextra -I paths
importPaths; /// extra `-I` paths
(alias) object.string = stringstring[] (field) string[] sparkles.test_runner.driver.DriverOptions.includeImportsextra -i=<pattern> module-inclusion patterns
includeImports; /// extra `-i=<pattern>` module-inclusion patterns
bool (field) bool sparkles.test_runner.driver.DriverOptions.noAutoIncludedon't compile the extracted tests' own modules in
noAutoInclude; /// don't compile the extracted tests' own modules in
bool (field) bool sparkles.test_runner.driver.DriverOptions.keepkeep the generated files and print their location
keep; /// keep the generated files and print their location
bool (field) bool sparkles.test_runner.driver.DriverOptions.verboseecho the commands that are run
verbose; /// echo the commands that are run
(struct) sparkles.test_runner.driver.ModeReportWhere the modes' messages go. The core prints nothing (process-model
TRM1): its client renders these, to a terminal or as task output.
ModeReport (field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.reportwhere the modes' messages go
report; /// where the modes' messages go
(alias) object.string = stringstring[] (field) string[] sparkles.test_runner.driver.DriverOptions.stringImportPathsextra -J paths
stringImportPaths; /// extra `-J` paths
(alias) object.string = stringstring[] (field) string[] sparkles.test_runner.driver.DriverOptions.versionsversion identifiers
versions; /// version identifiers
(alias) object.string = stringstring[] (field) string[] sparkles.test_runner.driver.DriverOptions.dflagsextra compiler flags
dflags; /// extra compiler flags
(alias) object.string = stringstring (field) string sparkles.test_runner.driver.DriverOptions.probeDirwhere generated programs go; empty = the temp directory
probeDir; /// where generated programs go; empty = the temp directory
bool (field) bool sparkles.test_runner.driver.DriverOptions.noDubnever run dub describe (process-model TRX2)
noDub; /// never run `dub describe` (process-model TRX2)
(alias) object.string = stringstring[] (field) string[] sparkles.test_runner.driver.DriverOptions.harnessRootsthe source roots the test binary reported
harnessRoots; /// the source roots the test binary reported
}
/// The probe directory of the current run (`DriverOptions.probeDir`).
private __gshared (alias) object.string = stringstring (__gshared global) string sparkles.test_runner.driver.probeRootThe probe directory of the current run (DriverOptions.probeDir).
probeRoot;
/// Sets where generated programs go for the rest of the run.
void void sparkles.test_runner.driver.setProbeDir(string dir)Sets where generated programs go for the rest of the run.
setProbeDir((alias) object.string = stringstring (parameter) string dirdir)
{
(__gshared global) string sparkles.test_runner.driver.probeRootThe probe directory of the current run (DriverOptions.probeDir).
probeRoot = (parameter) string dirdir;
}
/// The outcome of one driver run.
struct (struct) sparkles.test_runner.driver.DriverOutcomeThe outcome of one driver run.
DriverOutcome
{
(alias) object.size_t = ulongsize_t (field) ulong sparkles.test_runner.driver.DriverOutcome.testCounttestCount;
bool (field) bool sparkles.test_runner.driver.DriverOutcome.succeededsucceeded = true;
bool (field) bool sparkles.test_runner.driver.DriverOutcome.skippedmissing toolchain — reported but not a failure
skipped; /// missing toolchain — reported but not a failure
}
// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────
/// Whether an executable is reachable through `searchPath` (`$PATH` by
/// default). On Windows the file is `name.exe`, as `CreateProcess` finds it:
/// `$DC=ldc2` names `ldc2.exe` there.
///
/// A local re-implementation rather than `sparkles.core_cli.process_utils.isInPath`:
/// this module is source-compiled into `base`'s test build, which has no
/// `core-cli` dependency (the impl-library cycle is `impl → base`).
private bool bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safeWhether an executable is reachable through searchPath ($PATH by
default). On Windows the file is ``name.exe, as CreateProcess finds it:
$DC=ldc2 names ldc2.exe there.
A local re-implementation rather than sparkles.core_cli.process_utils.isInPath:
this module is source-compiled into base's test build, which has no
core-cli dependency (the impl-library cycle is impl → base).
inPath((alias) object.string = stringstring (parameter) string namename, (alias) object.string = stringstring (parameter) string searchPathsearchPath = null) @safe
{
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.iterationThis is a submodule of std.algorithm.
It contains generic iteration algorithms.
Function Name Description cache Eagerly evaluates and caches another range's front. lazyCache Lazily evaluates and caches another range's front, unlike cache. cacheBidirectional As above, but also provides back and popBack. chunkBy chunkBy!((a,b) => a[1] == b[1])([[1, 1], [1, 2], [2, 2], [2, 1]]) returns a range containing 3 subranges: the first with just [1, 1]; the second with the elements [1, 2] and [2, 2]; and the third with just [2, 1]. cumulativeFold cumulativeFold!((a, b) => a + b)([1, 2, 3, 4]) returns a lazily-evaluated range containing the successive reduced values 1, 3, 6, 10. each each!writeln([1, 2, 3]) eagerly prints the numbers 1, 2 and 3 on their own lines. filter filter!(a => a > 0)([1, -1, 2, 0, -3]) iterates over elements 1 and 2. filterBidirectional Similar to filter, but also provides back and popBack at a small increase in cost. fold fold!((a, b) => a + b)([1, 2, 3, 4]) returns 10. group group([5, 2, 2, 3, 3]) returns a range containing the tuples tuple(5, 1), tuple(2, 2), and tuple(3, 2). joiner joiner(["hello", "world!"], "; ") returns a range that iterates over the characters "hello; world!". No new string is created - the existing inputs are iterated. map map!(a => a * 2)([1, 2, 3]) lazily returns a range with the numbers 2, 4, 6. mean Colloquially known as the average, mean([1, 2, 3]) returns 2. permutations Lazily computes all permutations using Heap's algorithm. reduce reduce!((a, b) => a + b)([1, 2, 3, 4]) returns 10. This is the old implementation of fold. splitWhen Lazily splits a range by comparing adjacent elements. splitter Lazily splits a range by a separator, element predicate or whitespace. substitute [1, 2].substitute(1, 0.1) returns [0.1, 2]. sum Same as fold, but specialized for accurate summation. uniq Iterates over the unique elements in a range, which is assumed sorted.
Source
std/algorithm/iteration.d
iteration : (alias template) splitter = std.algorithm.iteration.splitter(alias pred = "a == b", Flag keepSeparators = No.keepSeparators, Range, Separator)(Range r, Separator s) if (is(typeof(binaryFun!pred(r.front, s)) : bool) && (hasSlicing!Range && hasLength!Range || isNarrowString!Range) && (is(ElementType!Range : Separator) || !(isForwardRange!Separator && (hasLength!Separator || isNarrowString!Separator))))Lazily splits a range using an element or range as a separator.
Separator ranges can be any narrow string type or sliceable range type.
Two adjacent separators are considered to surround an empty element in
the split range. Use filter!(a => !a.empty) on the result to compress
empty elements.
The predicate is passed to $(REF binaryFun, std,functional) and accepts
any callable function that can be executed via pred(element, s).
Note:
If splitting a string on whitespace and token compression is desired,
consider using the splitter(r) overload.
Params:
pred = The predicate for comparing each element with the separator,
defaulting to "a == b".
r = The $(REF_ALTTEXT input range, isInputRange, std,range,primitives) to be
split. Must support slicing and .length or be a narrow string type.
s = The element (or range) to be treated as the separator
between range segments to be split.
keepSeparators = The flag for deciding if the separators are kept
Constraints:
The predicate pred needs to accept an element of r and the
separator s.
Returns:
An input range of the subranges of elements between separators. If r
is a $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
or $(REF_ALTTEXT bidirectional range, isBidirectionalRange, std,range,primitives),
the returned range will be likewise.
When a range is used a separator, bidirectionality isn't possible.
If `keepSeparators` is equal to `Yes.keepSeparators` the output will also contain the
separators.
If an empty range is given, the result is an empty range. If a range with
one separator is given, the result is a range with two empty elements.
See_Also:
$(REF _splitter, std,regex) for a version that splits using a regular expression defined separator.
$(REF _split, std,array) for a version that splits eagerly.
$(LREF splitWhen), which compares adjacent elements instead of element against separator.
splitter;
import (package) stdstd.(module) std.fileUtilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one file
at a time. For opening files and manipulating them via handles refer
to module std.stdio.
Category Functions General exists isDir isFile isSymlink rename thisExePath Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir Files append copy read readText remove slurp write Symlinks symlink readLink Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace
Source
std/file.d
file : (alias template) exists = std.file.exists(R)(R name) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)Determine whether the given file (or directory) _exists.
Params:
name = string or range of characters representing the file _name
Returns:
true if the file name specified as input exists
exists, (alias template) isFile = std.file.isFile(R)(R name) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)Returns whether the given file (or directory) is a file.
On Windows, if a file is not a directory, then it's a file. So,
either `isFile` or `isDir` will return true for any given file.
On POSIX systems, if `isFile` is `true`, that indicates that the file
is a regular file (e.g. not a block not device). So, on POSIX systems, it's
possible for both `isFile` and `isDir` to be `false` for a
particular file (in which case, it's a special file). You can use
`getAttributes` to get the attributes to figure out what type of special
it is, or you can use `DirEntry` to get at its `statBuf`, which is the
result from `stat`. In either case, see the man page for `stat` for
more information.
Params:
name = The path to the file.
Returns:
true if name specifies a file
Throws:
$(LREF FileException) if the given file does not exist.
isFile;
import (package) stdstd.(module) std.pathThis module is used to manipulate path strings.
All functions, with the exception of expandTilde (and in some
cases absolutePath and relativePath), are pure
string manipulation functions; they don't depend on any state outside
the program, nor do they perform any actual file system actions.
This has the consequence that the module does not make any distinction
between a path that points to a directory and a path that points to a
file, and it does not know whether or not the object pointed to by the
path actually exists in the file system.
To differentiate between these cases, use isDir and
exists.
Note that on Windows, both the backslash (\) and the slash (/)
are in principle valid directory separators. This module treats them
both on equal footing, but in cases where a new separator is
added, a backslash will be used. Furthermore, the buildNormalizedPath
function will replace all slashes with backslashes on that platform.
In general, the functions in this module assume that the input paths
are well-formed. (That is, they should not contain invalid characters,
they should follow the file system's path format, etc.) The result
of calling a function on an ill-formed path is undefined. When there
is a chance that a path or a file name is invalid (for instance, when it
has been input by the user), it may sometimes be desirable to use the
isValidFilename and isValidPath functions to check
this.
Most functions do not perform any memory allocations, and if a string is
returned, it is usually a slice of an input string. If a function
allocates, this is explicitly mentioned in the documentation.
Category Functions Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension Other filenameCharCmp filenameCmp globMatch CaseSensitive
Source
std/path.d
path : (alias template) buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))Combines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by $(LREF isAbsolute)), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. $(D `\foo`)), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if `paths` is a forward
range.
Params:
segments = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
of segments to assemble the path from.
Returns: The assembled path.
buildPath, (alias template) extension = std.path.extension(R)(R path) if (isRandomAccessRange!R && hasSlicing!R && isSomeChar!(ElementType!R) || is(StringTypeOf!R))Params: path = A path name.
Returns: The _extension part of a file name, including the dot.
If there is no _extension, `null` is returned.
extension, (alias constant) pathSeparator = string std.path.pathSeparator = ":"Path separator string. A colon under POSIX, a semicolon
under Windows.
pathSeparator;
import (package) stdstd.(module) std.processFunctions for starting and interacting with other processes, and for
working with the current process' execution environment.
Process handling
`spawnProcess` spawns a new `process`, optionally assigning it an
arbitrary set of standard input, output, and error streams.
The function returns immediately, leaving the child process to execute
in parallel with its parent. All other functions in this module that
spawn processes are built around spawnProcess.
`wait` makes the parent `process` wait for a child `process` to
terminate. In general one should always do this, to avoid
child processes becoming "zombies" when the parent process exits.
Scope guards are perfect for this – see the spawnProcess
documentation for examples. tryWait is similar to wait,
but does not block if the process has not yet terminated.
`pipeProcess` also spawns a child `process` which runs
in parallel with its parent. However, instead of taking
arbitrary streams, it automatically creates a set of
pipes that allow the parent to communicate with the child
through the child's standard input, output, and/or error streams.
This function corresponds roughly to C's popen function.
`execute` starts a new `process` and waits for it
to complete before returning. Additionally, it captures
the process' standard output and error streams and returns
the output of these as a string.
`spawnShell`, `pipeShell` and `executeShell` work like
spawnProcess, pipeProcess and execute, respectively,
except that they take a single command string and run it through
the current user's default command interpreter.
executeShell corresponds roughly to C's system function.
`kill` attempts to terminate a running `process`.
The following table compactly summarises the different process creation
functions and how they relate to each other:
Runs program directly
Runs shell command Low-level process creation spawnProcess spawnShell Automatic input/output redirection using pipes pipeProcess pipeShell Execute and wait for completion, collect output execute executeShell
Other functionality
`pipe` is used to create unidirectional pipes.
`environment` is an interface through which the current `process`'
environment variables can be read and manipulated.
`escapeShellCommand` and `escapeShellFileName` are useful
for constructing shell command lines in a portable way.
Source
std/process.d
Note
Most of the functionality in this module is not available on iOS, tvOS
and watchOS. The only functions available on those platforms are:
environment, thisProcessID and thisThreadID.
process : (class) std.process.environmentManipulates environment variables using an associative-array-like
interface.
This class contains only static methods, and cannot be instantiated.
See below for examples of use.
environment;
if ((parameter) string searchPathsearchPath is null)
(parameter) string searchPathsearchPath = (class) std.process.environmentManipulates environment variables using an associative-array-like
interface.
This class contains only static methods, and cannot be instantiated.
See below for examples of use.
environment.string std.process.environment.get(scope const(char)[] name, string defaultValue = null) @safeRetrieves the value of the environment variable with the given name,
or a default value if the variable doesn't exist.
Unlike environment.opIndex, this function never throws on Posix.
auto sh = environment.get("SHELL", "/bin/sh");
This function is also useful in checking for the existence of an
environment variable.
auto myVar = environment.get("MYVAR");
if (myVar is null)
{
// Environment variable doesn't exist.
// Note that we have to use 'is' for the comparison, since
// myVar == null is also true if the variable exists but is
// empty.
}
get("PATH", "");
version (WindowsWindows)
const file = name.extension.length ? name : name ~ ".exe";
else
const (local variable) const(string) filefile = (parameter) string namename;
foreach ((local variable) string dirdir; (parameter) string searchPathsearchPath.std.algorithm.iteration.splitter!("a == b", Flag.no, string, string).Result std.algorithm.iteration.splitter!("a == b", Flag.no, string, string)(string r, string s) pure nothrow @nogc @safeSplitter returns bidirectional ranges if the delimiter is a single element
splitter((constant) string std.path.pathSeparator = ":"Path separator string. A colon under POSIX, a semicolon
under Windows.
pathSeparator))
{
const (local variable) const(string) candidatecandidate = string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath((local variable) string dirdir, (local variable) const(string) filefile);
if ((local variable) string dirdir.(field) ulong string.lengthlength && (local variable) const(string) candidatecandidate.bool std.file.exists!string(string name) nothrow @nogc @safeDetermine whether the given file (or directory) exists.
exists && (local variable) const(string) candidatecandidate.bool std.file.isFile!string(string name) @property @safeReturns whether the given file (or directory) is a file.
On Windows, if a file is not a directory, then it's a file. So,
either isFile or isDir will return true for any given file.
On POSIX systems, if isFile is true, that indicates that the file
is a regular file (e.g. not a block not device). So, on POSIX systems, it's
possible for both isFile and isDir to be false for a
particular file (in which case, it's a special file). You can use
getAttributes to get the attributes to figure out what type of special
it is, or you can use DirEntry to get at its statBuf, which is the
result from stat. In either case, see the man page for stat for
more information.
isFile)
return true;
}
return false;
}
@("inPath.platformExecutableName")
@safe
unittest
{
import (package) stdstd.(module) std.convA one-stop shop for converting values from one type to another.
Category Functions Generic asOriginalType castFrom parse to toChars bitCast Strings text wtext dtext writeText writeWText writeDText hexString Numeric octal roundTo signed unsigned Exceptions ConvException ConvOverflowException
Source
std/conv.d
conv : (alias template) text = std.conv.text(T...)(T args) if (T.length > 0)Convenience functions for converting one or more arguments
of any type into _text (the three character widths).
text;
import (package) stdstd.(module) std.fileUtilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one file
at a time. For opening files and manipulating them via handles refer
to module std.stdio.
Category Functions General exists isDir isFile isSymlink rename thisExePath Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir Files append copy read readText remove slurp write Symlinks symlink readLink Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace
Source
std/file.d
file : (alias) mkdirRecurse = void std.file.mkdirRecurse(scope const(char)[] pathname) @safeMake directory and all parent directories as needed.
Does nothing if the directory specified by
pathname already exists.
Params:
pathname = the full path of the directory to create
Throws: $(LREF FileException) on error.
mkdirRecurse, (alias) rmdirRecurse = void std.file.rmdirRecurse(scope const(char)[] pathname) @safeRemove directory and all of its content and subdirectories,
recursively.
Params:
pathname = the path of the directory to completely remove
de = The $(LREF DirEntry) to remove
Throws:
$(LREF FileException) if there is an error (including if the given
file is not a directory).
rmdirRecurse, (alias) tempDir = string std.file.tempDir() @trustedReturns the path to a directory for temporary files.
On POSIX platforms, it searches through the following list of directories
and returns the first one which is found to exist:
$(OL
$(LI The directory given by the TMPDIR environment variable.)
$(LI The directory given by the `TEMP` environment variable.)
$(LI The directory given by the TMP environment variable.)
$(LI `/tmp/`)
$(LI /var/tmp/)
$(LI /usr/tmp/)
)
On all platforms, tempDir returns the current working directory on failure.
The return value of the function is cached, so the procedures described
below will only be performed the first time the function is called. All
subsequent runs will return the same string, regardless of whether
environment variables and directory structures have changed in the
meantime.
The POSIX tempDir algorithm is inspired by Python's
$(LINK2 http://docs.python.org/library/tempfile.html#tempfile.tempdir, tempfile.tempdir).
Returns:
On Windows, this function returns the result of calling the Windows API function
$(LINK2 http://msdn.microsoft.com/en-us/library/windows/desktop/aa364992.aspx, GetTempPath).
On POSIX platforms, it searches through the following list of directories
and returns the first one which is found to exist:
$(OL
$(LI The directory given by the `TMPDIR` environment variable.)
$(LI The directory given by the `TEMP` environment variable.)
$(LI The directory given by the `TMP` environment variable.)
$(LI `/tmp`)
$(LI `/var/tmp`)
$(LI `/usr/tmp`)
)
On all platforms, `tempDir` returns `"."` on failure, representing
the current working directory.
tempDir, (alias template) write = std.file.write(R)(R name, const void[] buffer) if ((isSomeFiniteCharInputRange!R || isSomeString!R) && !isConvertibleToString!R)Write buffer to file name.
Creates the file if it does not already exist.
Params:
name = string or range of characters representing the file _name
buffer = data to be written to file
Throws: $(LREF FileException) on error.
See_also: $(REF toFile, std,stdio)
write;
import (package) stdstd.(module) std.pathThis module is used to manipulate path strings.
All functions, with the exception of expandTilde (and in some
cases absolutePath and relativePath), are pure
string manipulation functions; they don't depend on any state outside
the program, nor do they perform any actual file system actions.
This has the consequence that the module does not make any distinction
between a path that points to a directory and a path that points to a
file, and it does not know whether or not the object pointed to by the
path actually exists in the file system.
To differentiate between these cases, use isDir and
exists.
Note that on Windows, both the backslash (\) and the slash (/)
are in principle valid directory separators. This module treats them
both on equal footing, but in cases where a new separator is
added, a backslash will be used. Furthermore, the buildNormalizedPath
function will replace all slashes with backslashes on that platform.
In general, the functions in this module assume that the input paths
are well-formed. (That is, they should not contain invalid characters,
they should follow the file system's path format, etc.) The result
of calling a function on an ill-formed path is undefined. When there
is a chance that a path or a file name is invalid (for instance, when it
has been input by the user), it may sometimes be desirable to use the
isValidFilename and isValidPath functions to check
this.
Most functions do not perform any memory allocations, and if a string is
returned, it is usually a slice of an input string. If a function
allocates, this is explicitly mentioned in the documentation.
Category Functions Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension Other filenameCharCmp filenameCmp globMatch CaseSensitive
Source
std/path.d
path : (alias template) buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))Combines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by $(LREF isAbsolute)), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. $(D `\foo`)), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if `paths` is a forward
range.
Params:
segments = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
of segments to assemble the path from.
Returns: The assembled path.
buildPath, (alias constant) pathSeparator = string std.path.pathSeparator = ":"Path separator string. A colon under POSIX, a semicolon
under Windows.
pathSeparator;
import (package) stdstd.(module) std.processFunctions for starting and interacting with other processes, and for
working with the current process' execution environment.
Process handling
`spawnProcess` spawns a new `process`, optionally assigning it an
arbitrary set of standard input, output, and error streams.
The function returns immediately, leaving the child process to execute
in parallel with its parent. All other functions in this module that
spawn processes are built around spawnProcess.
`wait` makes the parent `process` wait for a child `process` to
terminate. In general one should always do this, to avoid
child processes becoming "zombies" when the parent process exits.
Scope guards are perfect for this – see the spawnProcess
documentation for examples. tryWait is similar to wait,
but does not block if the process has not yet terminated.
`pipeProcess` also spawns a child `process` which runs
in parallel with its parent. However, instead of taking
arbitrary streams, it automatically creates a set of
pipes that allow the parent to communicate with the child
through the child's standard input, output, and/or error streams.
This function corresponds roughly to C's popen function.
`execute` starts a new `process` and waits for it
to complete before returning. Additionally, it captures
the process' standard output and error streams and returns
the output of these as a string.
`spawnShell`, `pipeShell` and `executeShell` work like
spawnProcess, pipeProcess and execute, respectively,
except that they take a single command string and run it through
the current user's default command interpreter.
executeShell corresponds roughly to C's system function.
`kill` attempts to terminate a running `process`.
The following table compactly summarises the different process creation
functions and how they relate to each other:
Runs program directly
Runs shell command Low-level process creation spawnProcess spawnShell Automatic input/output redirection using pipes pipeProcess pipeShell Execute and wait for completion, collect output execute executeShell
Other functionality
`pipe` is used to create unidirectional pipes.
`environment` is an interface through which the current `process`'
environment variables can be read and manipulated.
`escapeShellCommand` and `escapeShellFileName` are useful
for constructing shell command lines in a portable way.
Source
std/process.d
Note
Most of the functionality in this module is not available on iOS, tvOS
and watchOS. The only functions available on those platforms are:
environment, thisProcessID and thisThreadID.
process : (alias) thisProcessID = int std.process.thisProcessID() nothrow @nogc @property @trustedReturns the process ID of the current process,
which is guaranteed to be unique on the system.
Example:
writefln("Current process ID: %d", thisProcessID);
---
thisProcessID;
const (local variable) const(string) dirdir = string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath(string std.file.tempDir() @trustedReturns the path to a directory for temporary files.
On POSIX platforms, it searches through the following list of directories
and returns the first one which is found to exist:
The directory given by the TMPDIR environment variable.
The directory given by the TEMP environment variable.
The directory given by the TMP environment variable.
/tmp/
/var/tmp/
/usr/tmp/
On all platforms, tempDir returns the current working directory on failure.
The return value of the function is cached, so the procedures described
below will only be performed the first time the function is called. All
subsequent runs will return the same string, regardless of whether
environment variables and directory structures have changed in the
meantime.
The POSIX tempDir algorithm is inspired by Python's
tempfile.tempdir.
Examples
import std.ascii : letters;
import std.conv : to;
import std.path : buildPath;
import std.random : randomSample;
import std.utf : byCodeUnit;
// random id with 20 letters
auto id = letters.byCodeUnit.randomSample(20).to!string;
auto myFile = tempDir.buildPath(id ~ "my_tmp_file");
scope(exit) myFile.remove;
myFile.write("hello");
assert(myFile.readText == "hello");
tempDir, string std.conv.text!(string, int)(string __param_0, int __param_1) pure nothrow @safeConvenience functions for converting one or more arguments
of any type into text (the three character widths).
text("sparkles-inpath-", int std.process.thisProcessID() nothrow @nogc @property @trustedReturns the process ID of the current process,
which is guaranteed to be unique on the system.
Example
writefln("Current process ID: %d", thisProcessID);
thisProcessID));
void std.file.mkdirRecurse(scope const(char)[] pathname) @safeMake directory and all parent directories as needed.
Does nothing if the directory specified by
pathname already exists.
Examples
import std.path : buildPath;
auto dir = deleteme ~ "dir";
scope(exit) dir.rmdirRecurse;
dir.mkdir;
assert(dir.exists);
dir.mkdirRecurse; // does nothing
// creates all parent directories as needed
auto nested = dir.buildPath("a", "b", "c");
nested.mkdirRecurse;
assert(nested.exists);
import std.exception : assertThrown;
scope(exit) deleteme.remove;
deleteme.write("a");
// cannot make directory as it's already a file
assertThrown!FileException(deleteme.mkdirRecurse);
mkdirRecurse((local variable) const(string) dirdir);
scope (exit)
void std.file.rmdirRecurse(scope const(char)[] pathname) @safeRemove directory and all of its content and subdirectories,
recursively.
rmdirRecurse((local variable) const(string) dirdir);
version (WindowsWindows)
write(buildPath(dir, "probe-tool.exe"), "");
else
void std.file.write!string(string name, const(void[]) buffer) @safeWrite buffer to file name.
Creates the file if it does not already exist.
Examples
scope(exit)
{
assert(exists(deleteme));
remove(deleteme);
}
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write(deleteme, a); // deleteme is the name of a temporary file
const bytes = read(deleteme);
const fileInts = () @trusted { return cast(int[]) bytes; }();
assert(fileInts == a);
write(string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath((local variable) const(string) dirdir, "probe-tool"), "");
const (local variable) const(string) searchsearch = "" ~ (constant) string std.path.pathSeparator = ":"Path separator string. A colon under POSIX, a semicolon
under Windows.
pathSeparator ~ (local variable) const(string) dirdir;
assert(bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safeWhether an executable is reachable through searchPath ($PATH by
default). On Windows the file is ``name.exe, as CreateProcess finds it:
$DC=ldc2 names ldc2.exe there.
A local re-implementation rather than sparkles.core_cli.process_utils.isInPath:
this module is source-compiled into base's test build, which has no
core-cli dependency (the impl-library cycle is impl → base).
inPath("probe-tool", (local variable) const(string) searchsearch), "found by the name a caller spawns");
assert(!bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safeWhether an executable is reachable through searchPath ($PATH by
default). On Windows the file is ``name.exe, as CreateProcess finds it:
$DC=ldc2 names ldc2.exe there.
A local re-implementation rather than sparkles.core_cli.process_utils.isInPath:
this module is source-compiled into base's test build, which has no
core-cli dependency (the impl-library cycle is impl → base).
inPath("absent-tool", (local variable) const(string) searchsearch));
}
/// The D compiler to use: explicit choice, `$DC`, or the first of
/// `ldc2`/`dmd` found in `$PATH` (empty string when none). An explicit choice
/// that doesn't resolve is reported to `report` and treated as "no compiler", so
/// the caller's toolchain-missing skip fires instead of a raw
/// `ProcessException` escaping from the spawn.
(alias) object.string = stringstring string sparkles.test_runner.driver.detectCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report = ModeReport(null, null)) @safeThe D compiler to use: explicit choice, $DC, or the first of
ldc2/dmd found in $PATH (empty string when none). An explicit choice
that doesn't resolve is reported to report and treated as "no compiler", so
the caller's toolchain-missing skip fires instead of a raw
ProcessException escaping from the spawn.
detectCompiler((alias) object.string = stringstring (parameter) string preferredpreferred, in (struct) sparkles.test_runner.driver.ModeReportWhere the modes' messages go. The core prints nothing (process-model
TRM1): its client renders these, to a terminal or as task output.
ModeReport (parameter) const(sparkles.test_runner.driver.ModeReport) reportreport = (struct) sparkles.test_runner.driver.ModeReportWhere the modes' messages go. The core prints nothing (process-model
TRM1): its client renders these, to a terminal or as task output.
ModeReport.(constant) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.ModeReport.init = ModeReport(null, null)init) @safe
{
import (package) stdstd.(module) std.processFunctions for starting and interacting with other processes, and for
working with the current process' execution environment.
Process handling
`spawnProcess` spawns a new `process`, optionally assigning it an
arbitrary set of standard input, output, and error streams.
The function returns immediately, leaving the child process to execute
in parallel with its parent. All other functions in this module that
spawn processes are built around spawnProcess.
`wait` makes the parent `process` wait for a child `process` to
terminate. In general one should always do this, to avoid
child processes becoming "zombies" when the parent process exits.
Scope guards are perfect for this – see the spawnProcess
documentation for examples. tryWait is similar to wait,
but does not block if the process has not yet terminated.
`pipeProcess` also spawns a child `process` which runs
in parallel with its parent. However, instead of taking
arbitrary streams, it automatically creates a set of
pipes that allow the parent to communicate with the child
through the child's standard input, output, and/or error streams.
This function corresponds roughly to C's popen function.
`execute` starts a new `process` and waits for it
to complete before returning. Additionally, it captures
the process' standard output and error streams and returns
the output of these as a string.
`spawnShell`, `pipeShell` and `executeShell` work like
spawnProcess, pipeProcess and execute, respectively,
except that they take a single command string and run it through
the current user's default command interpreter.
executeShell corresponds roughly to C's system function.
`kill` attempts to terminate a running `process`.
The following table compactly summarises the different process creation
functions and how they relate to each other:
Runs program directly
Runs shell command Low-level process creation spawnProcess spawnShell Automatic input/output redirection using pipes pipeProcess pipeShell Execute and wait for completion, collect output execute executeShell
Other functionality
`pipe` is used to create unidirectional pipes.
`environment` is an interface through which the current `process`'
environment variables can be read and manipulated.
`escapeShellCommand` and `escapeShellFileName` are useful
for constructing shell command lines in a portable way.
Source
std/process.d
Note
Most of the functionality in this module is not available on iOS, tvOS
and watchOS. The only functions available on those platforms are:
environment, thisProcessID and thisThreadID.
process : (class) std.process.environmentManipulates environment variables using an associative-array-like
interface.
This class contains only static methods, and cannot be instantiated.
See below for examples of use.
environment;
static bool bool sparkles.test_runner.driver.detectCompiler.resolves(string compiler) @saferesolves((alias) object.string = stringstring (parameter) string compilercompiler) @safe
{
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.searchingThis is a submodule of std.algorithm.
It contains generic searching algorithms.
Function Name Description all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses. boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm. canFind canFind("hello world", "or") returns true. count Counts all elements or elements matching a predicate, specific element or sub-range.
count([1, 2, 1]) returns 3,
count([1, 2, 1], 1) returns 2 and
count!"a < 0"([1, -3, 0]) returns 1. |
| countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. |
| commonPrefix | commonPrefix("parakeet", "parachute") returns "para". |
| endsWith | endsWith("rocks", "ks") returns true. |
| extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. |
| find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) |
| findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. |
| findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". |
| findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. |
| findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". |
| findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". |
| findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". |
| minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). |
| maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). |
| minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. |
| maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. |
| minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. |
| maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. |
| minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. |
| maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. |
| skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. |
| startsWith | startsWith("hello, world", "hello") returns true. |
| until | Lazily iterates a range until a specific value is found. |
Source
std/algorithm/searching.d
searching : (alias template) canFind = std.algorithm.searching.canFind(alias pred = "a == b")Convenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see $(LREF find).
See_Also:
$(REF among, std,algorithm,comparison) for checking a value against multiple arguments.
canFind;
import (package) stdstd.(module) std.fileUtilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one file
at a time. For opening files and manipulating them via handles refer
to module std.stdio.
Category Functions General exists isDir isFile isSymlink rename thisExePath Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir Files append copy read readText remove slurp write Symlinks symlink readLink Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace
Source
std/file.d
file : (alias template) exists = std.file.exists(R)(R name) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)Determine whether the given file (or directory) _exists.
Params:
name = string or range of characters representing the file _name
Returns:
true if the file name specified as input exists
exists, (alias template) isFile = std.file.isFile(R)(R name) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)Returns whether the given file (or directory) is a file.
On Windows, if a file is not a directory, then it's a file. So,
either `isFile` or `isDir` will return true for any given file.
On POSIX systems, if `isFile` is `true`, that indicates that the file
is a regular file (e.g. not a block not device). So, on POSIX systems, it's
possible for both `isFile` and `isDir` to be `false` for a
particular file (in which case, it's a special file). You can use
`getAttributes` to get the attributes to figure out what type of special
it is, or you can use `DirEntry` to get at its `statBuf`, which is the
result from `stat`. In either case, see the man page for `stat` for
more information.
Params:
name = The path to the file.
Returns:
true if name specifies a file
Throws:
$(LREF FileException) if the given file does not exist.
isFile;
return (parameter) string compilercompiler.bool std.algorithm.searching.canFind!().canFind!(string, char)(string haystack, scope char needle) pure @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind('/') || (parameter) string compilercompiler.bool std.algorithm.searching.canFind!().canFind!(string, char)(string haystack, scope char needle) pure @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind('\\')
? (parameter) string compilercompiler.bool std.file.exists!string(string name) nothrow @nogc @safeDetermine whether the given file (or directory) exists.
exists && (parameter) string compilercompiler.bool std.file.isFile!string(string name) @property @safeReturns whether the given file (or directory) is a file.
On Windows, if a file is not a directory, then it's a file. So,
either isFile or isDir will return true for any given file.
On POSIX systems, if isFile is true, that indicates that the file
is a regular file (e.g. not a block not device). So, on POSIX systems, it's
possible for both isFile and isDir to be false for a
particular file (in which case, it's a special file). You can use
getAttributes to get the attributes to figure out what type of special
it is, or you can use DirEntry to get at its statBuf, which is the
result from stat. In either case, see the man page for stat for
more information.
isFile : bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safeWhether an executable is reachable through searchPath ($PATH by
default). On Windows the file is ``name.exe, as CreateProcess finds it:
$DC=ldc2 names ldc2.exe there.
A local re-implementation rather than sparkles.core_cli.process_utils.isInPath:
this module is source-compiled into base's test build, which has no
core-cli dependency (the impl-library cycle is impl → base).
inPath((parameter) string compilercompiler);
}
(alias) object.string = stringstring string sparkles.test_runner.driver.detectCompiler.checked(string compiler, string origin) @safechecked((alias) object.string = stringstring (parameter) string compilercompiler, (alias) object.string = stringstring (parameter) string originorigin) @safe
{
if (bool sparkles.test_runner.driver.detectCompiler.resolves(string compiler) @saferesolves((parameter) string compilercompiler))
return (parameter) string compilercompiler;
void sparkles.test_runner.driver.warnTo!(string, string, string, string)(in sparkles.test_runner.driver.ModeReport report, string __param_1, string __param_2, string __param_3, string __param_4) @safeargs and a line feed, to report's diagnostics.
warnTo((parameter) const(sparkles.test_runner.driver.ModeReport) reportreport, (parameter) string originorigin, ": compiler '", (parameter) string compilercompiler, "' not found");
return null;
}
if ((parameter) string preferredpreferred.(field) ulong string.lengthlength)
return string sparkles.test_runner.driver.detectCompiler.checked(string compiler, string origin) @safechecked((parameter) string preferredpreferred, "--compiler");
if (const (local variable) const(string) dcdc = (class) std.process.environmentManipulates environment variables using an associative-array-like
interface.
This class contains only static methods, and cannot be instantiated.
See below for examples of use.
environment.string std.process.environment.get(scope const(char)[] name, string defaultValue = null) @safeRetrieves the value of the environment variable with the given name,
or a default value if the variable doesn't exist.
Unlike environment.opIndex, this function never throws on Posix.
auto sh = environment.get("SHELL", "/bin/sh");
This function is also useful in checking for the existence of an
environment variable.
auto myVar = environment.get("MYVAR");
if (myVar is null)
{
// Environment variable doesn't exist.
// Note that we have to use 'is' for the comparison, since
// myVar == null is also true if the variable exists but is
// empty.
}
get("DC", null))
return string sparkles.test_runner.driver.detectCompiler.checked(string compiler, string origin) @safechecked((local variable) const(string) dcdc, "$DC");
foreach ((parameter) string candidatecandidate; ["ldc2", "dmd"])
if (bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safeWhether an executable is reachable through searchPath ($PATH by
default). On Windows the file is ``name.exe, as CreateProcess finds it:
$DC=ldc2 names ldc2.exe there.
A local re-implementation rather than sparkles.core_cli.process_utils.isInPath:
this module is source-compiled into base's test build, which has no
core-cli dependency (the impl-library cycle is impl → base).
inPath((local variable) string candidatecandidate))
return (local variable) string candidatecandidate;
return null;
}
/// `-I` roots derived from every discovered test's module-name ↔ file-path
/// pair, after the extras: the user's, then the harness roots the binary
/// reported. Never the runner's own root: the pinned runner's copy of the
/// attributes is not the one the tested package was compiled against
/// (process-model TRX4).
(alias) object.string = stringstring[] string[] sparkles.test_runner.driver.deriveImportPaths(in sparkles.test_runner.model.Test[] allTests, in string[] extra) pure @safe-I roots derived from every discovered test's module-name ↔ file-path
pair, after the extras: the user's, then the harness roots the binary
reported. Never the runner's own root: the pinned runner's copy of the
attributes is not the one the tested package was compiled against
(process-model TRX4).
deriveImportPaths(in (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test[] (parameter) const(sparkles.test_runner.model.Test[]) allTestsallTests, in (alias) object.string = stringstring[] (parameter) const(string[]) extraextra) @safe pure
{
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.searchingThis is a submodule of std.algorithm.
It contains generic searching algorithms.
Function Name Description all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses. boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm. canFind canFind("hello world", "or") returns true. count Counts all elements or elements matching a predicate, specific element or sub-range.
count([1, 2, 1]) returns 3,
count([1, 2, 1], 1) returns 2 and
count!"a < 0"([1, -3, 0]) returns 1. |
| countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. |
| commonPrefix | commonPrefix("parakeet", "parachute") returns "para". |
| endsWith | endsWith("rocks", "ks") returns true. |
| extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. |
| find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) |
| findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. |
| findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". |
| findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. |
| findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". |
| findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". |
| findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". |
| minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). |
| maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). |
| minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. |
| maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. |
| minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. |
| maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. |
| minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. |
| maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. |
| skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. |
| startsWith | startsWith("hello, world", "hello") returns true. |
| until | Lazily iterates a range until a specific value is found. |
Source
std/algorithm/searching.d
searching : (alias template) canFind = std.algorithm.searching.canFind(alias pred = "a == b")Convenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see $(LREF find).
See_Also:
$(REF among, std,algorithm,comparison) for checking a value against multiple arguments.
canFind;
(alias) object.string = stringstring[] (local variable) string[] rootsroots = (parameter) const(string[]) extraextra.string[] object.dup!string(const(string)[] a) pure nothrow @property @safedup;
foreach (ref (parameter) const(sparkles.test_runner.model.Test) testtest; (parameter) const(sparkles.test_runner.model.Test[]) allTestsallTests)
{
const (local variable) const(string) rootroot = string sparkles.test_runner.extract.sourceRootOf(string file, string moduleName) pure nothrow @safeDerives the source root of a module from its file path and dotted name:
("libs/base/src/sparkles/base/buffer.d", "sparkles.base.buffer")
yields "libs/base/src". Returns null when the path does not end with
the module path. Either separator matches: on Windows the compiler reports
libs\base\src\sparkles\base\buffer.d, and the root keeps its own
separators.
sourceRootOf((local variable) const(sparkles.test_runner.model.Test) testtest.(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.locationlocation.(field) string sparkles.test_runner.model.TestLocation.filefile, string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safeThe actual module containing test: ``test.moduleName with aggregate
qualifiers stripped (a nested test's fullName includes its aggregate),
found by peeling trailing components until the name matches the file path.
probeModuleName((local variable) const(sparkles.test_runner.model.Test) testtest));
if ((local variable) const(string) rootroot !is null && !(local variable) string[] rootsroots.bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind((local variable) const(string) rootroot))
(local variable) string[] rootsroots ~= (local variable) const(string) rootroot;
}
return (local variable) string[] rootsroots;
}
@("deriveImportPaths.uniqueRoots")
@safe pure
unittest
{
import (package) sparklessparkles.(package) sparkles.test_runnertest_runner.(module) sparkles.test_runner.modelData model of the test runner: descriptions of discovered tests and the
results of executing them.
Everything here is runtime data — the compile-time discovery that produces
it lives in sparkles.test_runner.discovery.
model : (struct) sparkles.test_runner.model.TestLocationSource location of a unittest block, from __traits(getLocation).
The file path is as the compiler saw it (usually relative to the package
root that dub test runs in).
TestLocation;
const (local variable) const(sparkles.test_runner.model.Test[]) teststests = [
(struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test(fullName: "pkg.a.__unittest_L1_C1", name: "a",
location: (struct) sparkles.test_runner.model.TestLocationSource location of a unittest block, from __traits(getLocation).
The file path is as the compiler saw it (usually relative to the package
root that dub test runs in).
TestLocation(file: "src/pkg/a.d", line: 1, column: 1)),
(struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test(fullName: "pkg.b.__unittest_L1_C1", name: "b",
location: (struct) sparkles.test_runner.model.TestLocationSource location of a unittest block, from __traits(getLocation).
The file path is as the compiler saw it (usually relative to the package
root that dub test runs in).
TestLocation(file: "src/pkg/b.d", line: 1, column: 1)),
(struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test(fullName: "other.c.__unittest_L1_C1", name: "c",
location: (struct) sparkles.test_runner.model.TestLocationSource location of a unittest block, from __traits(getLocation).
The file path is as the compiler saw it (usually relative to the package
root that dub test runs in).
TestLocation(file: "lib2/src/other/c.d", line: 1, column: 1)),
];
assert(string[] sparkles.test_runner.driver.deriveImportPaths(in sparkles.test_runner.model.Test[] allTests, in string[] extra) pure @safe-I roots derived from every discovered test's module-name ↔ file-path
pair, after the extras: the user's, then the harness roots the binary
reported. Never the runner's own root: the pinned runner's copy of the
attributes is not the one the tested package was compiled against
(process-model TRX4).
deriveImportPaths((local variable) const(sparkles.test_runner.model.Test[]) teststests, ["extra"]) == ["extra", "src", "lib2/src"]);
}
/// The dub package root containing `sourceRoot`: the nearest ancestor
/// directory (including itself) with a `dub.sdl`/`dub.json`, or `null`.
private (alias) object.string = stringstring string sparkles.test_runner.driver.findPackageRoot(string sourceRoot) @safeThe dub package root containing sourceRoot: the nearest ancestor
directory (including itself) with a dub.sdl/dub.json, or null.
findPackageRoot((alias) object.string = stringstring (parameter) string sourceRootsourceRoot) @safe
{
import (package) stdstd.(module) std.fileUtilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one file
at a time. For opening files and manipulating them via handles refer
to module std.stdio.
Category Functions General exists isDir isFile isSymlink rename thisExePath Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir Files append copy read readText remove slurp write Symlinks symlink readLink Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace
Source
std/file.d
file : (alias template) exists = std.file.exists(R)(R name) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)Determine whether the given file (or directory) _exists.
Params:
name = string or range of characters representing the file _name
Returns:
true if the file name specified as input exists
exists;
import (package) stdstd.(module) std.pathThis module is used to manipulate path strings.
All functions, with the exception of expandTilde (and in some
cases absolutePath and relativePath), are pure
string manipulation functions; they don't depend on any state outside
the program, nor do they perform any actual file system actions.
This has the consequence that the module does not make any distinction
between a path that points to a directory and a path that points to a
file, and it does not know whether or not the object pointed to by the
path actually exists in the file system.
To differentiate between these cases, use isDir and
exists.
Note that on Windows, both the backslash (\) and the slash (/)
are in principle valid directory separators. This module treats them
both on equal footing, but in cases where a new separator is
added, a backslash will be used. Furthermore, the buildNormalizedPath
function will replace all slashes with backslashes on that platform.
In general, the functions in this module assume that the input paths
are well-formed. (That is, they should not contain invalid characters,
they should follow the file system's path format, etc.) The result
of calling a function on an ill-formed path is undefined. When there
is a chance that a path or a file name is invalid (for instance, when it
has been input by the user), it may sometimes be desirable to use the
isValidFilename and isValidPath functions to check
this.
Most functions do not perform any memory allocations, and if a string is
returned, it is usually a slice of an input string. If a function
allocates, this is explicitly mentioned in the documentation.
Category Functions Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension Other filenameCharCmp filenameCmp globMatch CaseSensitive
Source
std/path.d
path : (alias template) buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))Combines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by $(LREF isAbsolute)), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. $(D `\foo`)), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if `paths` is a forward
range.
Params:
segments = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
of segments to assemble the path from.
Returns: The assembled path.
buildPath, (alias template) dirName = std.path.dirName(R)(return scope R path) if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R)Returns the parent directory of path. On Windows, this
includes the drive letter if present. If path is a relative path and
the parent directory is the current working directory, returns ".".
Params:
path = A path name.
Returns:
A slice of `path` or `"."`.
Standards:
This function complies with
$(LINK2 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/dirname.html,
the POSIX requirements for the 'dirname' shell utility)
(with suitable adaptations for Windows paths).
dirName;
for ((alias) object.string = stringstring (local variable) string dirdir = (parameter) string sourceRootsourceRoot; dir.length && dir != "/" && dir != ".";
dir = dir.dirName)
{
if (string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath((local variable) string dirdir, "dub.sdl").bool std.file.exists!string(string name) nothrow @nogc @safeDetermine whether the given file (or directory) exists.
exists || string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath((local variable) string dirdir, "dub.json").bool std.file.exists!string(string name) nothrow @nogc @safeDetermine whether the given file (or directory) exists.
exists)
return (local variable) string dirdir;
}
return null;
}
/// Import paths reported by `dub describe` for the packages containing the
/// derived source roots — this is how paths of registry dependencies (e.g.
/// `expected`) are found. Best-effort: failures yield an empty list.
private (alias) object.string = stringstring[] string[] sparkles.test_runner.driver.dubDescribeImportPaths(in string[] sourceRoots, in sparkles.test_runner.driver.DriverOptions options)Import paths reported by dub describe for the packages containing the
derived source roots — this is how paths of registry dependencies (e.g.
expected) are found. Best-effort: failures yield an empty list.
dubDescribeImportPaths(in (alias) object.string = stringstring[] (parameter) const(string[]) sourceRootssourceRoots, in (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions)
{
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.iterationThis is a submodule of std.algorithm.
It contains generic iteration algorithms.
Function Name Description cache Eagerly evaluates and caches another range's front. lazyCache Lazily evaluates and caches another range's front, unlike cache. cacheBidirectional As above, but also provides back and popBack. chunkBy chunkBy!((a,b) => a[1] == b[1])([[1, 1], [1, 2], [2, 2], [2, 1]]) returns a range containing 3 subranges: the first with just [1, 1]; the second with the elements [1, 2] and [2, 2]; and the third with just [2, 1]. cumulativeFold cumulativeFold!((a, b) => a + b)([1, 2, 3, 4]) returns a lazily-evaluated range containing the successive reduced values 1, 3, 6, 10. each each!writeln([1, 2, 3]) eagerly prints the numbers 1, 2 and 3 on their own lines. filter filter!(a => a > 0)([1, -1, 2, 0, -3]) iterates over elements 1 and 2. filterBidirectional Similar to filter, but also provides back and popBack at a small increase in cost. fold fold!((a, b) => a + b)([1, 2, 3, 4]) returns 10. group group([5, 2, 2, 3, 3]) returns a range containing the tuples tuple(5, 1), tuple(2, 2), and tuple(3, 2). joiner joiner(["hello", "world!"], "; ") returns a range that iterates over the characters "hello; world!". No new string is created - the existing inputs are iterated. map map!(a => a * 2)([1, 2, 3]) lazily returns a range with the numbers 2, 4, 6. mean Colloquially known as the average, mean([1, 2, 3]) returns 2. permutations Lazily computes all permutations using Heap's algorithm. reduce reduce!((a, b) => a + b)([1, 2, 3, 4]) returns 10. This is the old implementation of fold. splitWhen Lazily splits a range by comparing adjacent elements. splitter Lazily splits a range by a separator, element predicate or whitespace. substitute [1, 2].substitute(1, 0.1) returns [0.1, 2]. sum Same as fold, but specialized for accurate summation. uniq Iterates over the unique elements in a range, which is assumed sorted.
Source
std/algorithm/iteration.d
iteration : (alias template) filter = std.algorithm.iteration.filter(alias predicate) if (is(typeof(unaryFun!predicate)))filter!(predicate)(range) returns a new range containing only elements x in range for
which predicate(x) returns true.
The predicate is passed to $(REF unaryFun, std,functional), and can be either a string, or
any callable that can be executed via pred(element).
Params:
predicate = Function to apply to each element of range
Returns:
An input range that contains the filtered elements. If range is at least a forward range, the return value of filter
will also be a forward range.
See_Also:
$(HTTP en.wikipedia.org/wiki/Filter_(higher-order_function), Filter (higher-order function)),
$(REF filterBidirectional, std,algorithm,iteration)
filter;
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.searchingThis is a submodule of std.algorithm.
It contains generic searching algorithms.
Function Name Description all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses. boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm. canFind canFind("hello world", "or") returns true. count Counts all elements or elements matching a predicate, specific element or sub-range.
count([1, 2, 1]) returns 3,
count([1, 2, 1], 1) returns 2 and
count!"a < 0"([1, -3, 0]) returns 1. |
| countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. |
| commonPrefix | commonPrefix("parakeet", "parachute") returns "para". |
| endsWith | endsWith("rocks", "ks") returns true. |
| extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. |
| find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) |
| findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. |
| findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". |
| findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. |
| findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". |
| findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". |
| findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". |
| minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). |
| maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). |
| minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. |
| maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. |
| minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. |
| maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. |
| minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. |
| maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. |
| skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. |
| startsWith | startsWith("hello, world", "hello") returns true. |
| until | Lazily iterates a range until a specific value is found. |
Source
std/algorithm/searching.d
searching : (alias template) canFind = std.algorithm.searching.canFind(alias pred = "a == b")Convenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see $(LREF find).
See_Also:
$(REF among, std,algorithm,comparison) for checking a value against multiple arguments.
canFind;
import (package) stdstd.(module) std.stringString handling functions.
Category Functions Searching column indexOf indexOfAny indexOfNeither lastIndexOf lastIndexOfAny lastIndexOfNeither Comparison isNumeric Mutation capitalize Pruning and Filling center chomp chompPrefix chop detabber detab entab entabber leftJustify outdent rightJustify strip stripLeft stripRight wrap Substitution abbrev soundex soundexer succ tr translate Miscellaneous assumeUTF fromStringz lineSplitter representation splitLines toStringz Objects of types string, wstring, and dstring are value types and cannot be mutated element-by-element. For using mutation during building strings, use char[], wchar[], or dchar[]. The xxxstring types are preferable because they don't exhibit undesired aliasing, thus making code more robust.
The following functions are publicly imported:
Module Functions Publicly imported functions std.algorithm cmp, std,algorithm,comparison count, std,algorithm,searching endsWith, std,algorithm,searching startsWith, std,algorithm,searching std.array join, std,array replace, std,array replaceInPlace, std,array split, std,array empty, std,array std.format format, std,format sformat, std,format std.uni icmp, std,uni toLower, std,uni toLowerInPlace, std,uni toUpper, std,uni toUpperInPlace, std,uni There is a rich set of functions for string handling defined in other modules. Functions related to Unicode and ASCII are found in std.uni and std.ascii, respectively. Other functions that have a wider generality than just strings can be found in std.algorithm and std.range.
Source
std/string.d
string : (alias template) lineSplitter = std.string.lineSplitter(Flag keepTerm = No.keepTerminator, Range)(Range r) if (hasSlicing!Range && hasLength!Range && isSomeChar!(ElementType!Range) && !isSomeString!Range)Split an array or slicable range of characters into a range of lines
using '\r', '\n', '\v', '\f', "\r\n",
$(REF lineSep, std,uni), $(REF paraSep, std,uni) and '\u0085' (NEL)
as delimiters. If keepTerm is set to Yes.keepTerminator, then the
delimiter is included in the slices returned.
Does not throw on invalid UTF; such is simply passed unchanged
to the output.
Adheres to $(HTTP www.unicode.org/versions/Unicode7.0.0/ch05.pdf, Unicode 7.0).
Does not allocate memory.
Params:
r = array of chars, wchars, or dchars or a slicable range
keepTerm = whether delimiter is included or not in the results
Returns:
range of slices of the input range r
See_Also:
$(LREF splitLines)
$(REF splitter, std,algorithm)
$(REF splitter, std,regex)
lineSplitter;
if (!bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safeWhether an executable is reachable through searchPath ($PATH by
default). On Windows the file is ``name.exe, as CreateProcess finds it:
$DC=ldc2 names ldc2.exe there.
A local re-implementation rather than sparkles.core_cli.process_utils.isInPath:
this module is source-compiled into base's test build, which has no
core-cli dependency (the impl-library cycle is impl → base).
inPath("dub"))
return null;
(alias) object.string = stringstring[] (local variable) string[] packageRootspackageRoots;
foreach ((parameter) const(string) rootroot; (parameter) const(string[]) sourceRootssourceRoots)
{
const (local variable) const(string) packageRootpackageRoot = string sparkles.test_runner.driver.findPackageRoot(string sourceRoot) @safeThe dub package root containing sourceRoot: the nearest ancestor
directory (including itself) with a dub.sdl/dub.json, or null.
findPackageRoot((local variable) const(string) rootroot);
if ((local variable) const(string) packageRootpackageRoot !is null && !(local variable) string[] packageRootspackageRoots.bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind((local variable) const(string) packageRootpackageRoot))
(local variable) string[] packageRootspackageRoots ~= (local variable) const(string) packageRootpackageRoot;
}
(alias) object.string = stringstring[] (local variable) string[] pathspaths;
foreach ((local variable) string packageRootpackageRoot; (local variable) string[] packageRootspackageRoots)
{
// The unittest configuration first: the tests' modules import what
// only it depends on (`sparkles:dql`'s integration schemas import
// `sparkles:input`). A package without one falls back to its default.
auto (local variable) std.typecons.Tuple!(int, "status", string, "output") resultresult = std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safeRuns command, echoing it when verbose, and returns (status, output).
A spawn failure (compiler binary vanished between the detectCompiler
check and here, or an unlaunchable absolute path) becomes a failed result
instead of a ProcessException stack trace.
run(["dub", "describe", "--root", (local variable) string packageRootpackageRoot, "--config=unittest",
"--data=import-paths", "--data-list"], (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions);
if ((local variable) std.typecons.Tuple!(int, "status", string, "output") resultresult.status != 0)
(local variable) std.typecons.Tuple!(int, "status", string, "output") resultresult = std.typecons.Tuple!(int, "status", string, "output") std.typecons.Tuple!(int, "status", string, "output").opAssign!(std.typecons.Tuple!(int, "status", string, "output"))(std.typecons.Tuple!(int, "status", string, "output") rhs) pure nothrow @nogc ref @safeAssignment from another Tuple.
run(["dub", "describe", "--root", (local variable) string packageRootpackageRoot,
"--data=import-paths", "--data-list"], (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions);
if ((local variable) std.typecons.Tuple!(int, "status", string, "output") resultresult.status != 0)
continue;
foreach ((local variable) string lineline; (local variable) std.typecons.Tuple!(int, "status", string, "output") resultresult.(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1output.std.string.LineSplitter!(Flag.no, string) std.string.lineSplitter!(Flag.no, immutable(char))(string r) pure nothrow @nogc @safeSplit an array or slicable range of characters into a range of lines
using '\r', '\n', '\v', '\f', "\r\n",
lineSep, paraSep and '\u0085' (NEL)
as delimiters. If keepTerm is set to Yes.keepTerminator, then the
delimiter is included in the slices returned.
Does not throw on invalid UTF; such is simply passed unchanged
to the output.
Adheres to Unicode 7.0.
Does not allocate memory.
Examples
import std.array : array;
string s = "Hello\nmy\rname\nis";
/* notice the call to 'array' to turn the lazy range created by
lineSplitter comparable to the string[] created by splitLines.
*/
assert(lineSplitter(s).array == splitLines(s));
auto s = "\rpeter\n\rpaul\r\njerry\u2028ice\u2029cream\n\nsunday\nmon\u2030day\n";
auto lines = s.lineSplitter();
static immutable witness = ["", "peter", "", "paul", "jerry", "ice", "cream", "", "sunday", "mon\u2030day"];
uint i;
foreach (line; lines)
{
assert(line == witness[i++]);
}
assert(i == witness.length);
lineSplitter.sparkles.test_runner.driver.dubDescribeImportPaths.FilterResult!(__lambda_L271_C59, LineSplitter!(Flag.no, string)) sparkles.test_runner.driver.dubDescribeImportPaths.filter!(std.string.LineSplitter!(Flag.no, string))(std.string.LineSplitter!(Flag.no, string) range) pure nothrow @nogc @safefilter`!(predicate)(`range`)` returns a new `range` containing only elements `x` in range`` for
which predicate(x) returns true.
The predicate is passed to unaryFun, and can be either a string, or
any callable that can be executed via pred(element).
Examples
import std.algorithm.comparison : equal;
import std.math.operations : isClose;
import std.range;
int[] arr = [ 1, 2, 3, 4, 5 ];
// Filter below 3
auto small = filter!(a => a < 3)(arr);
assert(equal(small, [ 1, 2 ]));
// Filter again, but with Uniform Function Call Syntax (UFCS)
auto sum = arr.filter!(a => a < 3);
assert(equal(sum, [ 1, 2 ]));
// In combination with chain() to span multiple ranges
int[] a = [ 3, -2, 400 ];
int[] b = [ 100, -101, 102 ];
auto r = chain(a, b).filter!(a => a > 0);
assert(equal(r, [ 3, 400, 100, 102 ]));
// Mixing convertible types is fair game, too
double[] c = [ 2.5, 3.0 ];
auto r1 = chain(c, a, b).filter!(a => cast(int) a != a);
assert(isClose(r1, [ 2.5 ]));
filter!(l => l.length))
if (!(local variable) string[] pathspaths.bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind((local variable) string lineline))
(local variable) string[] pathspaths ~= (local variable) string lineline;
}
return (local variable) string[] pathspaths;
}
/++
The language-semantics switches (`-preview=`, `-revert=`, `-transition=`) that
`dub describe` reports for the packages containing the derived source roots.
A program compiled outside dub needs them to see the packages' code the way
their own builds do (`-preview=dip1000` changes attribute inference).
Best-effort: failures yield an empty list.
+/
private (alias) object.string = stringstring[] string[] sparkles.test_runner.driver.dubDescribeLanguageFlags(in string[] sourceRoots, in sparkles.test_runner.driver.DriverOptions options)The language-semantics switches (-preview=, -revert=, -transition=) that
dub describe reports for the packages containing the derived source roots.
A program compiled outside dub needs them to see the packages' code the way
their own builds do (-preview=dip1000 changes attribute inference).
Best-effort: failures yield an empty list.
dubDescribeLanguageFlags(in (alias) object.string = stringstring[] (parameter) const(string[]) sourceRootssourceRoots, in (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions)
{
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.searchingThis is a submodule of std.algorithm.
It contains generic searching algorithms.
Function Name Description all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses. boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm. canFind canFind("hello world", "or") returns true. count Counts all elements or elements matching a predicate, specific element or sub-range.
count([1, 2, 1]) returns 3,
count([1, 2, 1], 1) returns 2 and
count!"a < 0"([1, -3, 0]) returns 1. |
| countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. |
| commonPrefix | commonPrefix("parakeet", "parachute") returns "para". |
| endsWith | endsWith("rocks", "ks") returns true. |
| extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. |
| find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) |
| findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. |
| findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". |
| findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. |
| findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". |
| findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". |
| findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". |
| minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). |
| maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). |
| minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. |
| maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. |
| minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. |
| maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. |
| minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. |
| maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. |
| skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. |
| startsWith | startsWith("hello, world", "hello") returns true. |
| until | Lazily iterates a range until a specific value is found. |
Source
std/algorithm/searching.d
searching : (alias template) canFind = std.algorithm.searching.canFind(alias pred = "a == b")Convenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see $(LREF find).
See_Also:
$(REF among, std,algorithm,comparison) for checking a value against multiple arguments.
canFind, (alias template) startsWith = std.algorithm.searching.startsWith(alias pred = (a, b) => a == b, Range, Needles...)(Range doesThisStart, Needles withOneOfThese) if (isInputRange!Range && (Needles.length > 1) && allSatisfy!(canTestStartsWith!(pred, Range), Needles))Checks whether the given
$(REF_ALTTEXT input range, isInputRange, std,range,primitives) starts with (one
of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate pred.
For more information about pred see $(LREF find).
Params:
pred = Predicate to use in comparing the elements of the haystack and the
needle(s). Mandatory if no needles are given.
doesThisStart = The input range to check.
withOneOfThese = The needles against which the range is to be checked,
which may be individual elements or input ranges of elements.
withThis = The single needle to check, which may be either a single element
or an input range of elements.
Returns:
0 if the needle(s) do not occur at the beginning of the given range;
otherwise the position of the matching needle, that is, 1 if the range starts
with withOneOfThese[0], 2 if it starts with withOneOfThese[1], and so
on.
In the case where doesThisStart starts with multiple of the ranges or
elements in withOneOfThese, then the shortest one matches (if there are
two which match which are of the same length (e.g. "a" and 'a'), then
the left-most of them in the argument
list matches).
In the case when no needle parameters are given, return true iff front of
doesThisStart fulfils predicate pred.
startsWith;
import (package) stdstd.(module) std.stringString handling functions.
Category Functions Searching column indexOf indexOfAny indexOfNeither lastIndexOf lastIndexOfAny lastIndexOfNeither Comparison isNumeric Mutation capitalize Pruning and Filling center chomp chompPrefix chop detabber detab entab entabber leftJustify outdent rightJustify strip stripLeft stripRight wrap Substitution abbrev soundex soundexer succ tr translate Miscellaneous assumeUTF fromStringz lineSplitter representation splitLines toStringz Objects of types string, wstring, and dstring are value types and cannot be mutated element-by-element. For using mutation during building strings, use char[], wchar[], or dchar[]. The xxxstring types are preferable because they don't exhibit undesired aliasing, thus making code more robust.
The following functions are publicly imported:
Module Functions Publicly imported functions std.algorithm cmp, std,algorithm,comparison count, std,algorithm,searching endsWith, std,algorithm,searching startsWith, std,algorithm,searching std.array join, std,array replace, std,array replaceInPlace, std,array split, std,array empty, std,array std.format format, std,format sformat, std,format std.uni icmp, std,uni toLower, std,uni toLowerInPlace, std,uni toUpper, std,uni toUpperInPlace, std,uni There is a rich set of functions for string handling defined in other modules. Functions related to Unicode and ASCII are found in std.uni and std.ascii, respectively. Other functions that have a wider generality than just strings can be found in std.algorithm and std.range.
Source
std/string.d
string : (alias template) lineSplitter = std.string.lineSplitter(Flag keepTerm = No.keepTerminator, Range)(Range r) if (hasSlicing!Range && hasLength!Range && isSomeChar!(ElementType!Range) && !isSomeString!Range)Split an array or slicable range of characters into a range of lines
using '\r', '\n', '\v', '\f', "\r\n",
$(REF lineSep, std,uni), $(REF paraSep, std,uni) and '\u0085' (NEL)
as delimiters. If keepTerm is set to Yes.keepTerminator, then the
delimiter is included in the slices returned.
Does not throw on invalid UTF; such is simply passed unchanged
to the output.
Adheres to $(HTTP www.unicode.org/versions/Unicode7.0.0/ch05.pdf, Unicode 7.0).
Does not allocate memory.
Params:
r = array of chars, wchars, or dchars or a slicable range
keepTerm = whether delimiter is included or not in the results
Returns:
range of slices of the input range r
See_Also:
$(LREF splitLines)
$(REF splitter, std,algorithm)
$(REF splitter, std,regex)
lineSplitter;
if (!bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safeWhether an executable is reachable through searchPath ($PATH by
default). On Windows the file is ``name.exe, as CreateProcess finds it:
$DC=ldc2 names ldc2.exe there.
A local re-implementation rather than sparkles.core_cli.process_utils.isInPath:
this module is source-compiled into base's test build, which has no
core-cli dependency (the impl-library cycle is impl → base).
inPath("dub"))
return null;
(alias) object.string = stringstring[] (local variable) string[] packageRootspackageRoots;
foreach ((parameter) const(string) rootroot; (parameter) const(string[]) sourceRootssourceRoots)
{
const (local variable) const(string) packageRootpackageRoot = string sparkles.test_runner.driver.findPackageRoot(string sourceRoot) @safeThe dub package root containing sourceRoot: the nearest ancestor
directory (including itself) with a dub.sdl/dub.json, or null.
findPackageRoot((local variable) const(string) rootroot);
if ((local variable) const(string) packageRootpackageRoot !is null && !(local variable) string[] packageRootspackageRoots.bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind((local variable) const(string) packageRootpackageRoot))
(local variable) string[] packageRootspackageRoots ~= (local variable) const(string) packageRootpackageRoot;
}
(alias) object.string = stringstring[] (local variable) string[] flagsflags;
foreach ((local variable) string packageRootpackageRoot; (local variable) string[] packageRootspackageRoots)
{
const (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult = std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safeRuns command, echoing it when verbose, and returns (status, output).
A spawn failure (compiler binary vanished between the detectCompiler
check and here, or an unlaunchable absolute path) becomes a failed result
instead of a ProcessException stack trace.
run(["dub", "describe", "--root", (local variable) string packageRootpackageRoot,
"--data=dflags", "--data-list"], (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions);
if ((local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult.status != 0)
continue;
foreach ((local variable) string lineline; (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult.(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1output.std.string.LineSplitter!(Flag.no, string) std.string.lineSplitter!(Flag.no, immutable(char))(string r) pure nothrow @nogc @safeSplit an array or slicable range of characters into a range of lines
using '\r', '\n', '\v', '\f', "\r\n",
lineSep, paraSep and '\u0085' (NEL)
as delimiters. If keepTerm is set to Yes.keepTerminator, then the
delimiter is included in the slices returned.
Does not throw on invalid UTF; such is simply passed unchanged
to the output.
Adheres to Unicode 7.0.
Does not allocate memory.
Examples
import std.array : array;
string s = "Hello\nmy\rname\nis";
/* notice the call to 'array' to turn the lazy range created by
lineSplitter comparable to the string[] created by splitLines.
*/
assert(lineSplitter(s).array == splitLines(s));
auto s = "\rpeter\n\rpaul\r\njerry\u2028ice\u2029cream\n\nsunday\nmon\u2030day\n";
auto lines = s.lineSplitter();
static immutable witness = ["", "peter", "", "paul", "jerry", "ice", "cream", "", "sunday", "mon\u2030day"];
uint i;
foreach (line; lines)
{
assert(line == witness[i++]);
}
assert(i == witness.length);
lineSplitter)
if (((local variable) string lineline.bool std.algorithm.searching.startsWith!("a == b", string, string)(string doesThisStart, string withThis) pure nothrow @nogc @safeChecks whether the given
input range starts with (one
of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate pred.
For more information about pred see find.
startsWith("-preview=") || (local variable) string lineline.bool std.algorithm.searching.startsWith!("a == b", string, string)(string doesThisStart, string withThis) pure nothrow @nogc @safeChecks whether the given
input range starts with (one
of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate pred.
For more information about pred see find.
startsWith("-revert=")
|| (local variable) string lineline.bool std.algorithm.searching.startsWith!("a == b", string, string)(string doesThisStart, string withThis) pure nothrow @nogc @safeChecks whether the given
input range starts with (one
of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate pred.
For more information about pred see find.
startsWith("-transition=")) && !(local variable) string[] flagsflags.bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind((local variable) string lineline))
(local variable) string[] flagsflags ~= (local variable) string lineline.string object.idup!(immutable(char))(string a) pure nothrow @property @safeProvide the .idup array property, which creates an immutable duplicate.
idup;
}
return (local variable) string[] flagsflags;
}
/// Slices the bodies of `tests` out of their source files. Files are read
/// relative to the working directory — the same place the compiler resolved
/// them from when the test build was created.
(struct) sparkles.test_runner.extract.ExtractedTestOne extracted test, ready to be emitted into a generated program.
ExtractedTest[] sparkles.test_runner.extract.ExtractedTest[] sparkles.test_runner.driver.extractTests(in sparkles.test_runner.model.Test[] tests)Slices the bodies of tests out of their source files. Files are read
relative to the working directory — the same place the compiler resolved
them from when the test build was created.
extractTests(in (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test[] (parameter) const(sparkles.test_runner.model.Test[]) teststests)
{
import (package) stdstd.(module) std.convA one-stop shop for converting values from one type to another.
Category Functions Generic asOriginalType castFrom parse to toChars bitCast Strings text wtext dtext writeText writeWText writeDText hexString Numeric octal roundTo signed unsigned Exceptions ConvException ConvOverflowException
Source
std/conv.d
conv : (alias template) text = std.conv.text(T...)(T args) if (T.length > 0)Convenience functions for converting one or more arguments
of any type into _text (the three character widths).
text;
import (package) stdstd.(module) std.fileUtilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one file
at a time. For opening files and manipulating them via handles refer
to module std.stdio.
Category Functions General exists isDir isFile isSymlink rename thisExePath Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir Files append copy read readText remove slurp write Symlinks symlink readLink Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace
Source
std/file.d
file : (alias template) readText = std.file.readText(S = string, R)(auto ref R name) if (isSomeString!S && (isSomeFiniteCharInputRange!R || is(StringTypeOf!R)))Reads and validates (using $(REF validate, std, utf)) a text file. S can be
an array of any character type. However, no width or endian conversions are
performed. So, if the width or endianness of the characters in the given
file differ from the width or endianness of the element type of S, then
validation will fail.
Params:
S = the string type of the file
name = string or range of characters representing the file _name
Returns: Array of characters read.
Throws: $(LREF FileException) if there is an error reading the file,
$(REF UTFException, std, utf) on UTF decoding error.
See_Also: $(REF read, std,file) for reading a binary file.
readText;
(alias) object.string = stringstring[(alias) object.string = stringstring] (local variable) string[string] sourcessources;
(struct) sparkles.test_runner.extract.ExtractedTestOne extracted test, ready to be emitted into a generated program.
ExtractedTest[] (local variable) sparkles.test_runner.extract.ExtractedTest[] extractedextracted;
foreach (ref (parameter) const(sparkles.test_runner.model.Test) testtest; (parameter) const(sparkles.test_runner.model.Test[]) teststests)
{
auto (local variable) string* sourcesource = (local variable) const(sparkles.test_runner.model.Test) testtest.(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.locationlocation.(field) string sparkles.test_runner.model.TestLocation.filefile in (local variable) string[string] sourcessources;
if ((local variable) string* sourcesource is null)
{
string* core.internal.newaa._d_aaGetY!(string, string, string[string], string, string, const(string))(ref scope string[string] aa, ref const(string) key, out bool found) pure nothrow @safeLookup key in aa.
Called only from implementation of (aa[`key`]) expressions when value is mutable.
sources[string* core.internal.newaa._d_aaGetY!(string, string, string[string], string, string, const(string))(ref scope string[string] aa, ref const(string) key, out bool found) pure nothrow @safeLookup key in aa.
Called only from implementation of (aa[`key`]) expressions when value is mutable.
test.(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.locationlocation.(field) string sparkles.test_runner.model.TestLocation.filefile] = string std.file.readText!(string, const(string))(ref const(string) name) @safeReads and validates (using validate) a text file. S can be
an array of any character type. However, no width or endian conversions are
performed. So, if the width or endianness of the characters in the given
file differ from the width or endianness of the element type of S, then
validation will fail.
Examples
Read file with UTF-8 text.
write(deleteme, "abc"); // deleteme is the name of a temporary file
scope(exit) remove(deleteme);
string content = readText(deleteme);
assert(content == "abc");
readText((local variable) const(sparkles.test_runner.model.Test) testtest.(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.locationlocation.(field) string sparkles.test_runner.model.TestLocation.filefile);
(local variable) string* sourcesource = (local variable) const(sparkles.test_runner.model.Test) testtest.(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.locationlocation.(field) string sparkles.test_runner.model.TestLocation.filefile in (local variable) string[string] sourcessources;
}
const (local variable) const(string) body_body_ = string sparkles.test_runner.extract.extractUnittestBody(string source, ulong line) pure @safeExtracts the body of the unittest block declared at line (its
__traits(getLocation) line): the text between the block's braces,
without the braces themselves. Returns null when no block is found.
extractUnittestBody(*(local variable) string* sourcesource, (local variable) const(sparkles.test_runner.model.Test) testtest.(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.locationlocation.(field) ulong sparkles.test_runner.model.TestLocation.lineline);
if ((local variable) const(string) body_body_ is null)
throw new (class) object.ExceptionThe base class of all errors that are safe to catch and handle.
In principle, only thrown objects derived from this class are safe to catch
inside a catch block. Thrown objects not derived from Exception
represent runtime errors that should not be caught, as certain runtime
guarantees may not hold, making it unsafe to continue program execution.
Examples
bool gotCaught;
try
{
throw new Exception("msg");
}
catch (Exception e)
{
gotCaught = true;
assert(e.msg == "msg");
}
assert(gotCaught);
Exception(string std.conv.text!(string, string, string, const(ulong), string, string, string)(string __param_0, string __param_1, string __param_2, const(ulong) __param_3, string __param_4, string __param_5, string __param_6) pure nothrow @safeConvenience functions for converting one or more arguments
of any type into text (the three character widths).
text("could not extract the unittest at ",
(local variable) const(sparkles.test_runner.model.Test) testtest.(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.locationlocation.(field) string sparkles.test_runner.model.TestLocation.filefile, ":", (local variable) const(sparkles.test_runner.model.Test) testtest.(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.locationlocation.(field) ulong sparkles.test_runner.model.TestLocation.lineline, " (", (local variable) const(sparkles.test_runner.model.Test) testtest.(field) string sparkles.test_runner.model.Test.nameDisplay name: the first string UDA, or the symbol identifier.
name, ")"));
(local variable) sparkles.test_runner.extract.ExtractedTest[] extractedextracted ~= (struct) sparkles.test_runner.extract.ExtractedTestOne extracted test, ready to be emitted into a generated program.
ExtractedTest(
name: (local variable) const(sparkles.test_runner.model.Test) testtest.(field) string sparkles.test_runner.model.Test.nameDisplay name: the first string UDA, or the symbol identifier.
name,
// Strip aggregate qualifiers so a test nested in a struct/class emits
// `import pkg.mod;`, not `import pkg.mod.Aggregate;` (mirrors the @ctfe
// path, which also uses probeModuleName).
moduleName: string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safeThe actual module containing test: ``test.moduleName with aggregate
qualifiers stripped (a nested test's fullName includes its aggregate),
found by peeling trailing components until the name matches the file path.
probeModuleName((local variable) const(sparkles.test_runner.model.Test) testtest),
file: (local variable) const(sparkles.test_runner.model.Test) testtest.(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.locationlocation.(field) string sparkles.test_runner.model.TestLocation.filefile,
line: (local variable) const(sparkles.test_runner.model.Test) testtest.(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.locationlocation.(field) ulong sparkles.test_runner.model.TestLocation.lineline,
functionAttributes: (local variable) const(sparkles.test_runner.model.Test) testtest.(field) sparkles.test_runner.model.TestTraits sparkles.test_runner.model.Test.traitstraits.(field) string sparkles.test_runner.model.TestTraits.functionAttributesThe test's safety/purity attributes ("@safe pure nothrow @nogc"),
re-applied to extracted @betterC/@wasm test functions.
functionAttributes,
body_: (local variable) const(string) body_body_,
);
}
return (local variable) sparkles.test_runner.extract.ExtractedTest[] extractedextracted;
}
/// A fresh scratch directory for the generated program: beneath `own`, the
/// run's `DriverOptions.probeDir`, when it names one, so clients that run
/// several modes at once in one process keep them apart; else beneath
/// `setProbeDir`'s.
private (alias) object.string = stringstring string sparkles.test_runner.driver.makeWorkDir(string flavor, string own = null)A fresh scratch directory for the generated program: beneath own, the
run's DriverOptions.probeDir, when it names one, so clients that run
several modes at once in one process keep them apart; else beneath
setProbeDir's.
makeWorkDir((alias) object.string = stringstring (parameter) string flavorflavor, (alias) object.string = stringstring (parameter) string ownown = null)
{
import (package) stdstd.(module) std.convA one-stop shop for converting values from one type to another.
Category Functions Generic asOriginalType castFrom parse to toChars bitCast Strings text wtext dtext writeText writeWText writeDText hexString Numeric octal roundTo signed unsigned Exceptions ConvException ConvOverflowException
Source
std/conv.d
conv : (alias template) text = std.conv.text(T...)(T args) if (T.length > 0)Convenience functions for converting one or more arguments
of any type into _text (the three character widths).
text;
import (package) stdstd.(module) std.fileUtilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one file
at a time. For opening files and manipulating them via handles refer
to module std.stdio.
Category Functions General exists isDir isFile isSymlink rename thisExePath Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir Files append copy read readText remove slurp write Symlinks symlink readLink Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace
Source
std/file.d
file : (alias) mkdirRecurse = void std.file.mkdirRecurse(scope const(char)[] pathname) @safeMake directory and all parent directories as needed.
Does nothing if the directory specified by
pathname already exists.
Params:
pathname = the full path of the directory to create
Throws: $(LREF FileException) on error.
mkdirRecurse, (alias) tempDir = string std.file.tempDir() @trustedReturns the path to a directory for temporary files.
On POSIX platforms, it searches through the following list of directories
and returns the first one which is found to exist:
$(OL
$(LI The directory given by the TMPDIR environment variable.)
$(LI The directory given by the `TEMP` environment variable.)
$(LI The directory given by the TMP environment variable.)
$(LI `/tmp/`)
$(LI /var/tmp/)
$(LI /usr/tmp/)
)
On all platforms, tempDir returns the current working directory on failure.
The return value of the function is cached, so the procedures described
below will only be performed the first time the function is called. All
subsequent runs will return the same string, regardless of whether
environment variables and directory structures have changed in the
meantime.
The POSIX tempDir algorithm is inspired by Python's
$(LINK2 http://docs.python.org/library/tempfile.html#tempfile.tempdir, tempfile.tempdir).
Returns:
On Windows, this function returns the result of calling the Windows API function
$(LINK2 http://msdn.microsoft.com/en-us/library/windows/desktop/aa364992.aspx, GetTempPath).
On POSIX platforms, it searches through the following list of directories
and returns the first one which is found to exist:
$(OL
$(LI The directory given by the `TMPDIR` environment variable.)
$(LI The directory given by the `TEMP` environment variable.)
$(LI The directory given by the `TMP` environment variable.)
$(LI `/tmp`)
$(LI `/var/tmp`)
$(LI `/usr/tmp`)
)
On all platforms, `tempDir` returns `"."` on failure, representing
the current working directory.
tempDir;
import (package) stdstd.(module) std.pathThis module is used to manipulate path strings.
All functions, with the exception of expandTilde (and in some
cases absolutePath and relativePath), are pure
string manipulation functions; they don't depend on any state outside
the program, nor do they perform any actual file system actions.
This has the consequence that the module does not make any distinction
between a path that points to a directory and a path that points to a
file, and it does not know whether or not the object pointed to by the
path actually exists in the file system.
To differentiate between these cases, use isDir and
exists.
Note that on Windows, both the backslash (\) and the slash (/)
are in principle valid directory separators. This module treats them
both on equal footing, but in cases where a new separator is
added, a backslash will be used. Furthermore, the buildNormalizedPath
function will replace all slashes with backslashes on that platform.
In general, the functions in this module assume that the input paths
are well-formed. (That is, they should not contain invalid characters,
they should follow the file system's path format, etc.) The result
of calling a function on an ill-formed path is undefined. When there
is a chance that a path or a file name is invalid (for instance, when it
has been input by the user), it may sometimes be desirable to use the
isValidFilename and isValidPath functions to check
this.
Most functions do not perform any memory allocations, and if a string is
returned, it is usually a slice of an input string. If a function
allocates, this is explicitly mentioned in the documentation.
Category Functions Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension Other filenameCharCmp filenameCmp globMatch CaseSensitive
Source
std/path.d
path : (alias template) buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))Combines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by $(LREF isAbsolute)), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. $(D `\foo`)), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if `paths` is a forward
range.
Params:
segments = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
of segments to assemble the path from.
Returns: The assembled path.
buildPath;
import (package) stdstd.(module) std.processFunctions for starting and interacting with other processes, and for
working with the current process' execution environment.
Process handling
`spawnProcess` spawns a new `process`, optionally assigning it an
arbitrary set of standard input, output, and error streams.
The function returns immediately, leaving the child process to execute
in parallel with its parent. All other functions in this module that
spawn processes are built around spawnProcess.
`wait` makes the parent `process` wait for a child `process` to
terminate. In general one should always do this, to avoid
child processes becoming "zombies" when the parent process exits.
Scope guards are perfect for this – see the spawnProcess
documentation for examples. tryWait is similar to wait,
but does not block if the process has not yet terminated.
`pipeProcess` also spawns a child `process` which runs
in parallel with its parent. However, instead of taking
arbitrary streams, it automatically creates a set of
pipes that allow the parent to communicate with the child
through the child's standard input, output, and/or error streams.
This function corresponds roughly to C's popen function.
`execute` starts a new `process` and waits for it
to complete before returning. Additionally, it captures
the process' standard output and error streams and returns
the output of these as a string.
`spawnShell`, `pipeShell` and `executeShell` work like
spawnProcess, pipeProcess and execute, respectively,
except that they take a single command string and run it through
the current user's default command interpreter.
executeShell corresponds roughly to C's system function.
`kill` attempts to terminate a running `process`.
The following table compactly summarises the different process creation
functions and how they relate to each other:
Runs program directly
Runs shell command Low-level process creation spawnProcess spawnShell Automatic input/output redirection using pipes pipeProcess pipeShell Execute and wait for completion, collect output execute executeShell
Other functionality
`pipe` is used to create unidirectional pipes.
`environment` is an interface through which the current `process`'
environment variables can be read and manipulated.
`escapeShellCommand` and `escapeShellFileName` are useful
for constructing shell command lines in a portable way.
Source
std/process.d
Note
Most of the functionality in this module is not available on iOS, tvOS
and watchOS. The only functions available on those platforms are:
environment, thisProcessID and thisThreadID.
process : (alias) thisProcessID = int std.process.thisProcessID() nothrow @nogc @property @trustedReturns the process ID of the current process,
which is guaranteed to be unique on the system.
Example:
writefln("Current process ID: %d", thisProcessID);
---
thisProcessID;
const (local variable) const(string) rootroot = (parameter) string ownown.(field) ulong string.lengthlength ? (parameter) string ownown : (__gshared global) string sparkles.test_runner.driver.probeRootThe probe directory of the current run (DriverOptions.probeDir).
probeRoot;
const (local variable) const(string) dirdir = (local variable) const(string) rootroot.(field) ulong const(string).lengthlength ? string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath((local variable) const(string) rootroot, (parameter) string flavorflavor) : string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath(string std.file.tempDir() @trustedReturns the path to a directory for temporary files.
On POSIX platforms, it searches through the following list of directories
and returns the first one which is found to exist:
The directory given by the TMPDIR environment variable.
The directory given by the TEMP environment variable.
The directory given by the TMP environment variable.
/tmp/
/var/tmp/
/usr/tmp/
On all platforms, tempDir returns the current working directory on failure.
The return value of the function is cached, so the procedures described
below will only be performed the first time the function is called. All
subsequent runs will return the same string, regardless of whether
environment variables and directory structures have changed in the
meantime.
The POSIX tempDir algorithm is inspired by Python's
tempfile.tempdir.
Examples
import std.ascii : letters;
import std.conv : to;
import std.path : buildPath;
import std.random : randomSample;
import std.utf : byCodeUnit;
// random id with 20 letters
auto id = letters.byCodeUnit.randomSample(20).to!string;
auto myFile = tempDir.buildPath(id ~ "my_tmp_file");
scope(exit) myFile.remove;
myFile.write("hello");
assert(myFile.readText == "hello");
tempDir,
string std.conv.text!(string, string, string, int)(string __param_0, string __param_1, string __param_2, int __param_3) pure nothrow @safeConvenience functions for converting one or more arguments
of any type into text (the three character widths).
text("sparkles-test-runner-", (parameter) string flavorflavor, "-", int std.process.thisProcessID() nothrow @nogc @property @trustedReturns the process ID of the current process,
which is guaranteed to be unique on the system.
Example
writefln("Current process ID: %d", thisProcessID);
thisProcessID));
void std.file.mkdirRecurse(scope const(char)[] pathname) @safeMake directory and all parent directories as needed.
Does nothing if the directory specified by
pathname already exists.
Examples
import std.path : buildPath;
auto dir = deleteme ~ "dir";
scope(exit) dir.rmdirRecurse;
dir.mkdir;
assert(dir.exists);
dir.mkdirRecurse; // does nothing
// creates all parent directories as needed
auto nested = dir.buildPath("a", "b", "c");
nested.mkdirRecurse;
assert(nested.exists);
import std.exception : assertThrown;
scope(exit) deleteme.remove;
deleteme.write("a");
// cannot make directory as it's already a file
assertThrown!FileException(deleteme.mkdirRecurse);
mkdirRecurse((local variable) const(string) dirdir);
return (local variable) const(string) dirdir;
}
/// Runs `command`, echoing it when `verbose`, and returns (status, output).
/// A spawn failure (compiler binary vanished between the `detectCompiler`
/// check and here, or an unlaunchable absolute path) becomes a failed result
/// instead of a `ProcessException` stack trace.
private auto std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safeRuns command, echoing it when verbose, and returns (status, output).
A spawn failure (compiler binary vanished between the detectCompiler
check and here, or an unlaunchable absolute path) becomes a failed result
instead of a ProcessException stack trace.
run(const((alias) object.string = stringstring)[] (parameter) const(string)[] commandcommand, in (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions)
{
import (package) stdstd.(module) std.processFunctions for starting and interacting with other processes, and for
working with the current process' execution environment.
Process handling
`spawnProcess` spawns a new `process`, optionally assigning it an
arbitrary set of standard input, output, and error streams.
The function returns immediately, leaving the child process to execute
in parallel with its parent. All other functions in this module that
spawn processes are built around spawnProcess.
`wait` makes the parent `process` wait for a child `process` to
terminate. In general one should always do this, to avoid
child processes becoming "zombies" when the parent process exits.
Scope guards are perfect for this – see the spawnProcess
documentation for examples. tryWait is similar to wait,
but does not block if the process has not yet terminated.
`pipeProcess` also spawns a child `process` which runs
in parallel with its parent. However, instead of taking
arbitrary streams, it automatically creates a set of
pipes that allow the parent to communicate with the child
through the child's standard input, output, and/or error streams.
This function corresponds roughly to C's popen function.
`execute` starts a new `process` and waits for it
to complete before returning. Additionally, it captures
the process' standard output and error streams and returns
the output of these as a string.
`spawnShell`, `pipeShell` and `executeShell` work like
spawnProcess, pipeProcess and execute, respectively,
except that they take a single command string and run it through
the current user's default command interpreter.
executeShell corresponds roughly to C's system function.
`kill` attempts to terminate a running `process`.
The following table compactly summarises the different process creation
functions and how they relate to each other:
Runs program directly
Runs shell command Low-level process creation spawnProcess spawnShell Automatic input/output redirection using pipes pipeProcess pipeShell Execute and wait for completion, collect output execute executeShell
Other functionality
`pipe` is used to create unidirectional pipes.
`environment` is an interface through which the current `process`'
environment variables can be read and manipulated.
`escapeShellCommand` and `escapeShellFileName` are useful
for constructing shell command lines in a portable way.
Source
std/process.d
Note
Most of the functionality in this module is not available on iOS, tvOS
and watchOS. The only functions available on those platforms are:
environment, thisProcessID and thisThreadID.
process : (alias) execute = std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safeExecutes the given program or shell command and returns its exit
code and output.
execute and executeShell start a new process using
$(LREF spawnProcess) and $(LREF spawnShell), respectively, and wait
for the process to complete before returning. The functions capture
what the child process prints to both its standard output and
standard error streams, and return this together with its exit code.
auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);
auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
Params:
args = An array which contains the program name as the zeroth element
and any command-line arguments in the following elements.
(See $(LREF spawnProcess) for details.)
program = The program name, $(I without) command-line arguments.
(See $(LREF spawnProcess) for details.)
command = A shell command which is passed verbatim to the command
interpreter. (See $(LREF spawnShell) for details.)
env = Additional environment variables for the child process.
(See $(LREF spawnProcess) for details.)
config = Flags that control process creation. See $(LREF Config)
for an overview of available flags, and note that the
retainStd... flags have no effect in this function.
maxOutput = The maximum number of bytes of output that should be
captured.
workDir = The working directory for the new process.
By default the child process inherits the parent's working
directory.
shellPath = The path to the shell to use to run the specified program.
By default this is $(LREF nativeShell).
Returns:
An $(D std.typecons.Tuple!(int, "status", string, "output")).
POSIX_specific:
If the process is terminated by a signal, the status field of
the return value will contain a negative number whose absolute
value is the signal number. (See $(LREF wait) for details.)
Throws:
$(LREF ProcessException) on failure to start the process.$(BR)
$(REF StdioException, std,stdio) on failure to capture output.
execute, (class) std.process.ProcessExceptionAn exception that signals a problem with starting or waiting for a process.
ProcessException;
if ((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) bool sparkles.test_runner.driver.DriverOptions.verboseecho the commands that are run
verbose)
{
import (package) stdstd.(module) std.stringString handling functions.
Category Functions Searching column indexOf indexOfAny indexOfNeither lastIndexOf lastIndexOfAny lastIndexOfNeither Comparison isNumeric Mutation capitalize Pruning and Filling center chomp chompPrefix chop detabber detab entab entabber leftJustify outdent rightJustify strip stripLeft stripRight wrap Substitution abbrev soundex soundexer succ tr translate Miscellaneous assumeUTF fromStringz lineSplitter representation splitLines toStringz Objects of types string, wstring, and dstring are value types and cannot be mutated element-by-element. For using mutation during building strings, use char[], wchar[], or dchar[]. The xxxstring types are preferable because they don't exhibit undesired aliasing, thus making code more robust.
The following functions are publicly imported:
Module Functions Publicly imported functions std.algorithm cmp, std,algorithm,comparison count, std,algorithm,searching endsWith, std,algorithm,searching startsWith, std,algorithm,searching std.array join, std,array replace, std,array replaceInPlace, std,array split, std,array empty, std,array std.format format, std,format sformat, std,format std.uni icmp, std,uni toLower, std,uni toLowerInPlace, std,uni toUpper, std,uni toUpperInPlace, std,uni There is a rich set of functions for string handling defined in other modules. Functions related to Unicode and ASCII are found in std.uni and std.ascii, respectively. Other functions that have a wider generality than just strings can be found in std.algorithm and std.range.
Source
std/string.d
string : (alias template) join = std.array.join(RoR, R)(RoR ror, R sep) if (isInputRange!RoR && isInputRange!(Unqual!(ElementType!RoR)) && isInputRange!R && (is(immutable(ElementType!(ElementType!RoR)) == immutable(ElementType!R)) || isSomeChar!(ElementType!(ElementType!RoR)) && isSomeChar!(ElementType!R)))Eagerly concatenates all of the ranges in ror together (with the GC)
into one array using sep as the separator if present.
Params:
ror = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
of input ranges
sep = An input range, or a single element, to join the ranges on
Returns:
An array of elements
See_Also:
For a lazy version, see $(REF joiner, std,algorithm,iteration)
join;
void sparkles.test_runner.driver.warn!(string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2) @safeargs and a line feed, to report's diagnostics.
warn((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "$ ", (parameter) const(string)[] commandcommand.string std.array.join!(const(string)[], string)(const(string)[] ror, string sep) pure nothrow @safeEagerly concatenates all of the ranges in ror together (with the GC)
into one array using sep as the separator if present.
join(" "));
}
try
return std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safeExecutes the given program or shell command and returns its exit
code and output.
execute and executeShell start a new process using
spawnProcess and spawnShell, respectively, and wait
for the process to complete before returning. The functions capture
what the child process prints to both its standard output and
standard error streams, and return this together with its exit code.
auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);
auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
POSIX specific
If the process is terminated by a signal, the status field of
the return value will contain a negative number whose absolute
value is the signal number. (See wait for details.)
execute((parameter) const(string)[] commandcommand);
catch ((class) std.process.ProcessExceptionAn exception that signals a problem with starting or waiting for a process.
ProcessException (local variable) std.process.ProcessException ee)
return typeof(execute(command))(-1,
"failed to launch '" ~ (parameter) const(string)[] commandcommand[0] ~ "': " ~ (local variable) std.process.ProcessException ee.(field) string object.Throwable.msgA message describing the error.
msg);
}
/// The extra `-i=<pattern>` flags requested with `--include-import` (e.g.
/// `--include-import=std.ascii` to compile a std module in when an extracted
/// test needs one of its non-template functions).
private (alias) object.string = stringstring[] string[] sparkles.test_runner.driver.includeFlags(in sparkles.test_runner.driver.DriverOptions options) pure @safeThe extra -i=<pattern> flags requested with --include-import (e.g.
--include-import=std.ascii to compile a std module in when an extracted
test needs one of its non-template functions).
includeFlags(in (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions) @safe pure
{
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.iterationThis is a submodule of std.algorithm.
It contains generic iteration algorithms.
Function Name Description cache Eagerly evaluates and caches another range's front. lazyCache Lazily evaluates and caches another range's front, unlike cache. cacheBidirectional As above, but also provides back and popBack. chunkBy chunkBy!((a,b) => a[1] == b[1])([[1, 1], [1, 2], [2, 2], [2, 1]]) returns a range containing 3 subranges: the first with just [1, 1]; the second with the elements [1, 2] and [2, 2]; and the third with just [2, 1]. cumulativeFold cumulativeFold!((a, b) => a + b)([1, 2, 3, 4]) returns a lazily-evaluated range containing the successive reduced values 1, 3, 6, 10. each each!writeln([1, 2, 3]) eagerly prints the numbers 1, 2 and 3 on their own lines. filter filter!(a => a > 0)([1, -1, 2, 0, -3]) iterates over elements 1 and 2. filterBidirectional Similar to filter, but also provides back and popBack at a small increase in cost. fold fold!((a, b) => a + b)([1, 2, 3, 4]) returns 10. group group([5, 2, 2, 3, 3]) returns a range containing the tuples tuple(5, 1), tuple(2, 2), and tuple(3, 2). joiner joiner(["hello", "world!"], "; ") returns a range that iterates over the characters "hello; world!". No new string is created - the existing inputs are iterated. map map!(a => a * 2)([1, 2, 3]) lazily returns a range with the numbers 2, 4, 6. mean Colloquially known as the average, mean([1, 2, 3]) returns 2. permutations Lazily computes all permutations using Heap's algorithm. reduce reduce!((a, b) => a + b)([1, 2, 3, 4]) returns 10. This is the old implementation of fold. splitWhen Lazily splits a range by comparing adjacent elements. splitter Lazily splits a range by a separator, element predicate or whitespace. substitute [1, 2].substitute(1, 0.1) returns [0.1, 2]. sum Same as fold, but specialized for accurate summation. uniq Iterates over the unique elements in a range, which is assumed sorted.
Source
std/algorithm/iteration.d
iteration : (alias template) map = std.algorithm.iteration.map(fun...) if (fun.length >= 1)Implements the homonym function (also known as transform) present
in many languages of functional flavor. The call map!(fun)(range)
returns a range of which elements are obtained by applying fun(a)
left to right for all elements a in range. The original ranges are
not changed. Evaluation is done lazily.
Params:
fun = one or more transformation functions
See_Also:
$(HTTP en.wikipedia.org/wiki/Map_(higher-order_function), Map (higher-order function))
map;
import (package) stdstd.(module) std.arrayFunctions and types that manipulate built-in arrays and associative arrays.
This module provides all kinds of functions to create, manipulate or convert arrays:
Function Name Description
| array |
Returns a copy of the input in a newly allocated dynamic array.
|
| appender |
Returns a new Appender or RefAppender initialized with a given array.
|
| assocArray |
Returns a newly allocated associative array from a range/ranges of keys and values.
|
| byPair |
Construct a range iterating over an associative array by key/value tuples.
|
| insertInPlace |
Inserts into an existing array at a given position.
|
| join |
Concatenates a range of ranges into one array.
|
| minimallyInitializedArray |
Returns a new array of type T.
|
| replace |
Returns a new array with all occurrences of a certain subrange replaced.
|
| replaceFirst |
Returns a new array with the first occurrence of a certain subrange replaced.
|
| replaceInPlace |
Replaces all occurrences of a certain subrange and puts the result into a given array.
|
| replaceInto |
Replaces all occurrences of a certain subrange and puts the result into an output range.
|
| replaceLast |
Returns a new array with the last occurrence of a certain subrange replaced.
|
| replaceSlice |
Returns a new array with a given slice replaced.
|
| replicate |
Creates a new array out of several copies of an input array or range.
|
| sameHead |
Checks if the initial segments of two arrays refer to the same
place in memory.
|
| sameTail |
Checks if the final segments of two arrays refer to the same place
in memory.
|
| split |
Eagerly split a range or string into an array.
|
| staticArray |
Creates a new static array from given data.
|
| uninitializedArray |
Returns a new array of type T without initializing its elements.
|
Source
std/array.d
array : (alias template) array = std.array.array(Range)(Range r) if (isIterable!Range && !isAutodecodableString!Range && !isInfinite!Range)Allocates an array and initializes it with copies of the elements
of range r.
Narrow strings are handled as follows:
If autodecoding is turned on (default), then they are handled as a separate overload.
If autodecoding is turned off, then this is equivalent to duplicating the array.
Params:
r = range (or aggregate with opApply function) whose elements are copied into the allocated array
Returns:
allocated and initialized array
array;
return (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) string[] sparkles.test_runner.driver.DriverOptions.includeImportsextra -i=<pattern> module-inclusion patterns
includeImports.sparkles.test_runner.driver.includeFlags.MapResult!(__lambda_L402_C40, const(string)[]) sparkles.test_runner.driver.includeFlags.map!(const(string)[])(const(string)[] r) pure nothrow @nogc @safeImplements the homonym function (also known as transform) present
in many languages of functional flavor. The call ``map!(fun)(range)
returns a range of which elements are obtained by applying fun(a)
left to right for all elements a in range. The original ranges are
not changed. Evaluation is done lazily.
Examples
import std.algorithm.comparison : equal;
import std.range : chain, only;
auto squares =
chain(only(1, 2, 3, 4), only(5, 6)).map!(a => a * a);
assert(equal(squares, only(1, 4, 9, 16, 25, 36)));
Multiple functions can be passed to map. In that case, the
element type of map is a tuple containing one element for each
function.
auto sums = [2, 4, 6, 8];
auto products = [1, 4, 9, 16];
size_t i = 0;
foreach (result; [ 1, 2, 3, 4 ].map!("a + a", "a * a"))
{
assert(result[0] == sums[i]);
assert(result[1] == products[i]);
++i;
}
You may alias map with some function(s) to a symbol and use
it separately:
import std.algorithm.comparison : equal;
import std.conv : to;
alias stringize = map!(to!string);
assert(equal(stringize([ 1, 2, 3, 4 ]), [ "1", "2", "3", "4" ]));
map!(p => "-i=" ~ p).string[] std.array.array!(sparkles.test_runner.driver.includeFlags.MapResult!(__lambda_L402_C40, const(string)[]))(sparkles.test_runner.driver.includeFlags.MapResult!(__lambda_L402_C40, const(string)[]) r) pure @safeAllocates an array and initializes it with copies of the elements
of range r.
Narrow strings are handled as follows:
If autodecoding is turned on (default), then they are handled as a separate overload.
If autodecoding is turned off, then this is equivalent to duplicating the array.
array;
}
/// The `-i=<module>` flags derived from the tests being extracted: one per
/// distinct module that owns a test, minus the ones whose tests all opted out
/// with `selfContained`.
///
/// Compiling the owning module in is the useful default. Without it an
/// extracted program links against nothing but templates, so a `@betterC`
/// test that calls any ordinary function of the very module it lives in —
/// the common case — fails at link time with an undefined reference, which
/// made the marker attribute effectively decorative for such tests.
///
/// The opt-out is per test (`@betterC(selfContained: true)`) rather than
/// global because it is a property of the test: a module that is not itself
/// `-betterC`-codegen-clean can still host a template-only test, and that
/// self-containment is exactly what such a test asserts. `--no-auto-include`
/// disables the whole derivation for a one-off run.
(alias) object.string = stringstring[] string[] sparkles.test_runner.driver.autoIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safeThe -i=<module> flags derived from the tests being extracted: one per
distinct module that owns a test, minus the ones whose tests all opted out
with selfContained.
Compiling the owning module in is the useful default. Without it an
extracted program links against nothing but templates, so a @betterC
test that calls any ordinary function of the very module it lives in —
the common case — fails at link time with an undefined reference, which
made the marker attribute effectively decorative for such tests.
The opt-out is per test (@betterC(selfContained: true)) rather than
global because it is a property of the test: a module that is not itself
-betterC-codegen-clean can still host a template-only test, and that
self-containment is exactly what such a test asserts. --no-auto-include
disables the whole derivation for a one-off run.
autoIncludeFlags(in (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test[] (parameter) const(sparkles.test_runner.model.Test[]) extractedextracted, in (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions) @safe pure
{
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.searchingThis is a submodule of std.algorithm.
It contains generic searching algorithms.
Function Name Description all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses. boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm. canFind canFind("hello world", "or") returns true. count Counts all elements or elements matching a predicate, specific element or sub-range.
count([1, 2, 1]) returns 3,
count([1, 2, 1], 1) returns 2 and
count!"a < 0"([1, -3, 0]) returns 1. |
| countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. |
| commonPrefix | commonPrefix("parakeet", "parachute") returns "para". |
| endsWith | endsWith("rocks", "ks") returns true. |
| extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. |
| find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) |
| findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. |
| findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". |
| findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. |
| findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". |
| findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". |
| findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". |
| minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). |
| maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). |
| minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. |
| maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. |
| minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. |
| maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. |
| minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. |
| maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. |
| skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. |
| startsWith | startsWith("hello, world", "hello") returns true. |
| until | Lazily iterates a range until a specific value is found. |
Source
std/algorithm/searching.d
searching : (alias template) canFind = std.algorithm.searching.canFind(alias pred = "a == b")Convenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see $(LREF find).
See_Also:
$(REF among, std,algorithm,comparison) for checking a value against multiple arguments.
canFind;
if ((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) bool sparkles.test_runner.driver.DriverOptions.noAutoIncludedon't compile the extracted tests' own modules in
noAutoInclude)
return null;
(alias) object.string = stringstring[] (local variable) string[] flagsflags;
foreach (ref (parameter) const(sparkles.test_runner.model.Test) testtest; (parameter) const(sparkles.test_runner.model.Test[]) extractedextracted)
{
if ((local variable) const(sparkles.test_runner.model.Test) testtest.(field) sparkles.test_runner.model.TestTraits sparkles.test_runner.model.Test.traitstraits.(field) bool sparkles.test_runner.model.TestTraits.selfContainedThe test asserts it needs nothing linked from its own module, so the
extracted --better-c / --wasm program leaves that module out
(see betterC.selfContained``). One flag covers both modes: a test
marked self-contained under either is self-contained under both.
selfContained)
continue;
const (local variable) const(string) flagflag = "-i=" ~ (local variable) const(sparkles.test_runner.model.Test) testtest.string sparkles.test_runner.model.Test.moduleName() const pure nothrow @nogc return scope @safeThe module part of fullName (everything before the last .).
moduleName;
if (!(local variable) string[] flagsflags.bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind((local variable) const(string) flagflag))
(local variable) string[] flagsflags ~= (local variable) const(string) flagflag;
}
return (local variable) string[] flagsflags;
}
@("driver.autoIncludeFlags.oneFlagPerOwningModule")
@safe pure
unittest
{
static (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safeat((alias) object.string = stringstring (parameter) string fullNamefullName, bool (parameter) bool selfContainedselfContained = false)
{
(struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test (local variable) sparkles.test_runner.model.Test tt;
(local variable) sparkles.test_runner.model.Test tt.(field) string sparkles.test_runner.model.Test.fullNameFully qualified name of the unittest symbol,
e.g. sparkles.base.buffer.__unittest_L42_C1.
fullName = (parameter) string fullNamefullName;
(local variable) sparkles.test_runner.model.Test tt.(field) sparkles.test_runner.model.TestTraits sparkles.test_runner.model.Test.traitstraits.(field) bool sparkles.test_runner.model.TestTraits.selfContainedThe test asserts it needs nothing linked from its own module, so the
extracted --better-c / --wasm program leaves that module out
(see betterC.selfContained``). One flag covers both modes: a test
marked self-contained under either is self-contained under both.
selfContained = (parameter) bool selfContainedselfContained;
return (local variable) sparkles.test_runner.model.Test tt;
}
// One flag per distinct module, in first-seen order, deduplicated.
assert(string[] sparkles.test_runner.driver.autoIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safeThe -i=<module> flags derived from the tests being extracted: one per
distinct module that owns a test, minus the ones whose tests all opted out
with selfContained.
Compiling the owning module in is the useful default. Without it an
extracted program links against nothing but templates, so a @betterC
test that calls any ordinary function of the very module it lives in —
the common case — fails at link time with an undefined reference, which
made the marker attribute effectively decorative for such tests.
The opt-out is per test (@betterC(selfContained: true)) rather than
global because it is a property of the test: a module that is not itself
-betterC-codegen-clean can still host a template-only test, and that
self-containment is exactly what such a test asserts. --no-auto-include
disables the whole derivation for a one-off run.
autoIncludeFlags([
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safeat("pkg.a.__unittest_L1_C1"),
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safeat("pkg.b.__unittest_L2_C1"),
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safeat("pkg.a.__unittest_L3_C1"),
], (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions.(constant) sparkles.test_runner.driver.DriverOptions sparkles.test_runner.driver.DriverOptions.init = DriverOptions(null, null, null, false, false, false, ModeReport(null, null), null, null, null, null, false, null)init) == ["-i=pkg.a", "-i=pkg.b"]);
// A self-contained test contributes nothing — that is what lets a module
// which cannot compile under -betterC still host a template-only test.
assert(string[] sparkles.test_runner.driver.autoIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safeThe -i=<module> flags derived from the tests being extracted: one per
distinct module that owns a test, minus the ones whose tests all opted out
with selfContained.
Compiling the owning module in is the useful default. Without it an
extracted program links against nothing but templates, so a @betterC
test that calls any ordinary function of the very module it lives in —
the common case — fails at link time with an undefined reference, which
made the marker attribute effectively decorative for such tests.
The opt-out is per test (@betterC(selfContained: true)) rather than
global because it is a property of the test: a module that is not itself
-betterC-codegen-clean can still host a template-only test, and that
self-containment is exactly what such a test asserts. --no-auto-include
disables the whole derivation for a one-off run.
autoIncludeFlags([
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safeat("pkg.a.__unittest_L1_C1", true),
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safeat("pkg.b.__unittest_L2_C1"),
], (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions.(constant) sparkles.test_runner.driver.DriverOptions sparkles.test_runner.driver.DriverOptions.init = DriverOptions(null, null, null, false, false, false, ModeReport(null, null), null, null, null, null, false, null)init) == ["-i=pkg.b"]);
// ... but only when *every* test in that module opted out.
assert(string[] sparkles.test_runner.driver.autoIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safeThe -i=<module> flags derived from the tests being extracted: one per
distinct module that owns a test, minus the ones whose tests all opted out
with selfContained.
Compiling the owning module in is the useful default. Without it an
extracted program links against nothing but templates, so a @betterC
test that calls any ordinary function of the very module it lives in —
the common case — fails at link time with an undefined reference, which
made the marker attribute effectively decorative for such tests.
The opt-out is per test (@betterC(selfContained: true)) rather than
global because it is a property of the test: a module that is not itself
-betterC-codegen-clean can still host a template-only test, and that
self-containment is exactly what such a test asserts. --no-auto-include
disables the whole derivation for a one-off run.
autoIncludeFlags([
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safeat("pkg.a.__unittest_L1_C1", true),
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safeat("pkg.a.__unittest_L2_C1"),
], (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions.(constant) sparkles.test_runner.driver.DriverOptions sparkles.test_runner.driver.DriverOptions.init = DriverOptions(null, null, null, false, false, false, ModeReport(null, null), null, null, null, null, false, null)init) == ["-i=pkg.a"]);
// --no-auto-include restores the strict template-only behavior.
assert(string[] sparkles.test_runner.driver.autoIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safeThe -i=<module> flags derived from the tests being extracted: one per
distinct module that owns a test, minus the ones whose tests all opted out
with selfContained.
Compiling the owning module in is the useful default. Without it an
extracted program links against nothing but templates, so a @betterC
test that calls any ordinary function of the very module it lives in —
the common case — fails at link time with an undefined reference, which
made the marker attribute effectively decorative for such tests.
The opt-out is per test (@betterC(selfContained: true)) rather than
global because it is a property of the test: a module that is not itself
-betterC-codegen-clean can still host a template-only test, and that
self-containment is exactly what such a test asserts. --no-auto-include
disables the whole derivation for a one-off run.
autoIncludeFlags(
[sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safeat("pkg.a.__unittest_L1_C1")],
(struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions(noAutoInclude: true)) == []);
}
/// The compile context's flags: `-I` for the derived source roots, the
/// harness roots, `dub describe`d dependency paths unless `noDub`, and the
/// user's extras, then the string import paths, versions and flags
/// (process-model TRX1–TRX4).
private (alias) object.string = stringstring[] string[] sparkles.test_runner.driver.allImportFlags(in sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options)The compile context's flags: -I for the derived source roots, the
harness roots, dub described dependency paths unless noDub, and the
user's extras, then the string import paths, versions and flags
(process-model TRX1–TRX4).
allImportFlags(in (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test[] (parameter) const(sparkles.test_runner.model.Test[]) allTestsallTests, in (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions)
{
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.iterationThis is a submodule of std.algorithm.
It contains generic iteration algorithms.
Function Name Description cache Eagerly evaluates and caches another range's front. lazyCache Lazily evaluates and caches another range's front, unlike cache. cacheBidirectional As above, but also provides back and popBack. chunkBy chunkBy!((a,b) => a[1] == b[1])([[1, 1], [1, 2], [2, 2], [2, 1]]) returns a range containing 3 subranges: the first with just [1, 1]; the second with the elements [1, 2] and [2, 2]; and the third with just [2, 1]. cumulativeFold cumulativeFold!((a, b) => a + b)([1, 2, 3, 4]) returns a lazily-evaluated range containing the successive reduced values 1, 3, 6, 10. each each!writeln([1, 2, 3]) eagerly prints the numbers 1, 2 and 3 on their own lines. filter filter!(a => a > 0)([1, -1, 2, 0, -3]) iterates over elements 1 and 2. filterBidirectional Similar to filter, but also provides back and popBack at a small increase in cost. fold fold!((a, b) => a + b)([1, 2, 3, 4]) returns 10. group group([5, 2, 2, 3, 3]) returns a range containing the tuples tuple(5, 1), tuple(2, 2), and tuple(3, 2). joiner joiner(["hello", "world!"], "; ") returns a range that iterates over the characters "hello; world!". No new string is created - the existing inputs are iterated. map map!(a => a * 2)([1, 2, 3]) lazily returns a range with the numbers 2, 4, 6. mean Colloquially known as the average, mean([1, 2, 3]) returns 2. permutations Lazily computes all permutations using Heap's algorithm. reduce reduce!((a, b) => a + b)([1, 2, 3, 4]) returns 10. This is the old implementation of fold. splitWhen Lazily splits a range by comparing adjacent elements. splitter Lazily splits a range by a separator, element predicate or whitespace. substitute [1, 2].substitute(1, 0.1) returns [0.1, 2]. sum Same as fold, but specialized for accurate summation. uniq Iterates over the unique elements in a range, which is assumed sorted.
Source
std/algorithm/iteration.d
iteration : (alias template) map = std.algorithm.iteration.map(fun...) if (fun.length >= 1)Implements the homonym function (also known as transform) present
in many languages of functional flavor. The call map!(fun)(range)
returns a range of which elements are obtained by applying fun(a)
left to right for all elements a in range. The original ranges are
not changed. Evaluation is done lazily.
Params:
fun = one or more transformation functions
See_Also:
$(HTTP en.wikipedia.org/wiki/Map_(higher-order_function), Map (higher-order function))
map;
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.searchingThis is a submodule of std.algorithm.
It contains generic searching algorithms.
Function Name Description all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses. boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm. canFind canFind("hello world", "or") returns true. count Counts all elements or elements matching a predicate, specific element or sub-range.
count([1, 2, 1]) returns 3,
count([1, 2, 1], 1) returns 2 and
count!"a < 0"([1, -3, 0]) returns 1. |
| countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. |
| commonPrefix | commonPrefix("parakeet", "parachute") returns "para". |
| endsWith | endsWith("rocks", "ks") returns true. |
| extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. |
| find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) |
| findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. |
| findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". |
| findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. |
| findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". |
| findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". |
| findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". |
| minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). |
| maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). |
| minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. |
| maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. |
| minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. |
| maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. |
| minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. |
| maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. |
| skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. |
| startsWith | startsWith("hello, world", "hello") returns true. |
| until | Lazily iterates a range until a specific value is found. |
Source
std/algorithm/searching.d
searching : (alias template) canFind = std.algorithm.searching.canFind(alias pred = "a == b")Convenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see $(LREF find).
See_Also:
$(REF among, std,algorithm,comparison) for checking a value against multiple arguments.
canFind;
import (package) stdstd.(module) std.arrayFunctions and types that manipulate built-in arrays and associative arrays.
This module provides all kinds of functions to create, manipulate or convert arrays:
Function Name Description
| array |
Returns a copy of the input in a newly allocated dynamic array.
|
| appender |
Returns a new Appender or RefAppender initialized with a given array.
|
| assocArray |
Returns a newly allocated associative array from a range/ranges of keys and values.
|
| byPair |
Construct a range iterating over an associative array by key/value tuples.
|
| insertInPlace |
Inserts into an existing array at a given position.
|
| join |
Concatenates a range of ranges into one array.
|
| minimallyInitializedArray |
Returns a new array of type T.
|
| replace |
Returns a new array with all occurrences of a certain subrange replaced.
|
| replaceFirst |
Returns a new array with the first occurrence of a certain subrange replaced.
|
| replaceInPlace |
Replaces all occurrences of a certain subrange and puts the result into a given array.
|
| replaceInto |
Replaces all occurrences of a certain subrange and puts the result into an output range.
|
| replaceLast |
Returns a new array with the last occurrence of a certain subrange replaced.
|
| replaceSlice |
Returns a new array with a given slice replaced.
|
| replicate |
Creates a new array out of several copies of an input array or range.
|
| sameHead |
Checks if the initial segments of two arrays refer to the same
place in memory.
|
| sameTail |
Checks if the final segments of two arrays refer to the same place
in memory.
|
| split |
Eagerly split a range or string into an array.
|
| staticArray |
Creates a new static array from given data.
|
| uninitializedArray |
Returns a new array of type T without initializing its elements.
|
Source
std/array.d
array : (alias template) array = std.array.array(Range)(Range r) if (isIterable!Range && !isAutodecodableString!Range && !isInfinite!Range)Allocates an array and initializes it with copies of the elements
of range r.
Narrow strings are handled as follows:
If autodecoding is turned on (default), then they are handled as a separate overload.
If autodecoding is turned off, then this is equivalent to duplicating the array.
Params:
r = range (or aggregate with opApply function) whose elements are copied into the allocated array
Returns:
allocated and initialized array
array;
import (package) stdstd.(module) std.pathThis module is used to manipulate path strings.
All functions, with the exception of expandTilde (and in some
cases absolutePath and relativePath), are pure
string manipulation functions; they don't depend on any state outside
the program, nor do they perform any actual file system actions.
This has the consequence that the module does not make any distinction
between a path that points to a directory and a path that points to a
file, and it does not know whether or not the object pointed to by the
path actually exists in the file system.
To differentiate between these cases, use isDir and
exists.
Note that on Windows, both the backslash (\) and the slash (/)
are in principle valid directory separators. This module treats them
both on equal footing, but in cases where a new separator is
added, a backslash will be used. Furthermore, the buildNormalizedPath
function will replace all slashes with backslashes on that platform.
In general, the functions in this module assume that the input paths
are well-formed. (That is, they should not contain invalid characters,
they should follow the file system's path format, etc.) The result
of calling a function on an ill-formed path is undefined. When there
is a chance that a path or a file name is invalid (for instance, when it
has been input by the user), it may sometimes be desirable to use the
isValidFilename and isValidPath functions to check
this.
Most functions do not perform any memory allocations, and if a string is
returned, it is usually a slice of an input string. If a function
allocates, this is explicitly mentioned in the documentation.
Category Functions Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension Other filenameCharCmp filenameCmp globMatch CaseSensitive
Source
std/path.d
path : (alias template) baseName = std.path.baseName(R)(return scope R path) if (isRandomAccessRange!R && hasSlicing!R && isSomeChar!(ElementType!R) && !isSomeString!R)Params:
cs = Whether or not suffix matching is case-sensitive.
path = A path name. It can be a string, or any random-access range of
characters.
suffix = An optional suffix to be removed from the file name.
Returns: The name of the file in the path name, without any leading
directory and with an optional suffix chopped off.
If `suffix` is specified, it will be compared to `path`
using `filenameCmp!cs`,
where `cs` is an optional template parameter determining whether
the comparison is case sensitive or not. See the
$(LREF filenameCmp) documentation for details.
Note:
This function $(I only) strips away the specified suffix, which
doesn't necessarily have to represent an extension.
To remove the extension from a path, regardless of what the extension
is, use $(LREF stripExtension).
To obtain the filename without leading directories and without
an extension, combine the functions like this:
---
assert(baseName(stripExtension("dir/file.ext")) == "file");
---
Standards:
This function complies with
$(LINK2 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/basename.html,
the POSIX requirements for the 'basename' shell utility)
(with suitable adaptations for Windows paths).
baseName;
auto (local variable) string[] rootsroots = string[] sparkles.test_runner.driver.deriveImportPaths(in sparkles.test_runner.model.Test[] allTests, in string[] extra) pure @safe-I roots derived from every discovered test's module-name ↔ file-path
pair, after the extras: the user's, then the harness roots the binary
reported. Never the runner's own root: the pinned runner's copy of the
attributes is not the one the tested package was compiled against
(process-model TRX4).
deriveImportPaths((parameter) const(sparkles.test_runner.model.Test[]) allTestsallTests, (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) string[] sparkles.test_runner.driver.DriverOptions.importPathsextra -I paths
importPaths ~ (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) string[] sparkles.test_runner.driver.DriverOptions.harnessRootsthe source roots the test binary reported
harnessRoots);
if (!(parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) bool sparkles.test_runner.driver.DriverOptions.noDubnever run dub describe (process-model TRX2)
noDub)
foreach ((parameter) string pathpath; string[] sparkles.test_runner.driver.dubDescribeImportPaths(in string[] sourceRoots, in sparkles.test_runner.driver.DriverOptions options)Import paths reported by dub describe for the packages containing the
derived source roots — this is how paths of registry dependencies (e.g.
expected) are found. Best-effort: failures yield an empty list.
dubDescribeImportPaths((local variable) string[] rootsroots, (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions))
if (!(local variable) string[] rootsroots.bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind((local variable) string pathpath))
(local variable) string[] rootsroots ~= (local variable) string pathpath;
const (local variable) const(bool) ldcldc = string sparkles.test_runner.driver.detectCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report = ModeReport(null, null)) @safeThe D compiler to use: explicit choice, $DC, or the first of
ldc2/dmd found in $PATH (empty string when none). An explicit choice
that doesn't resolve is reported to report and treated as "no compiler", so
the caller's toolchain-missing skip fires instead of a raw
ProcessException escaping from the spawn.
detectCompiler((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) string sparkles.test_runner.driver.DriverOptions.compilerexplicit D compiler; empty = $DC, then ldc2, dmd
compiler, (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.reportwhere the modes' messages go
report).string std.path.baseName!(immutable(char))(return scope string path) pure nothrow @nogc @safeNote
This function only strips away the specified suffix, which
doesn't necessarily have to represent an extension.
To remove the extension from a path, regardless of what the extension
is, use stripExtension.
To obtain the filename without leading directories and without
an extension, combine the functions like this:
assert(baseName(stripExtension("dir/file.ext")) == "file");
baseName.bool std.algorithm.searching.canFind!().canFind!(string, string)(string haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind("ldc");
return (local variable) string[] rootsroots.sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L494_C23, string[]) sparkles.test_runner.driver.allImportFlags.map!(string[])(string[] r) pure nothrow @nogc @safeImplements the homonym function (also known as transform) present
in many languages of functional flavor. The call ``map!(fun)(range)
returns a range of which elements are obtained by applying fun(a)
left to right for all elements a in range. The original ranges are
not changed. Evaluation is done lazily.
Examples
import std.algorithm.comparison : equal;
import std.range : chain, only;
auto squares =
chain(only(1, 2, 3, 4), only(5, 6)).map!(a => a * a);
assert(equal(squares, only(1, 4, 9, 16, 25, 36)));
Multiple functions can be passed to map. In that case, the
element type of map is a tuple containing one element for each
function.
auto sums = [2, 4, 6, 8];
auto products = [1, 4, 9, 16];
size_t i = 0;
foreach (result; [ 1, 2, 3, 4 ].map!("a + a", "a * a"))
{
assert(result[0] == sums[i]);
assert(result[1] == products[i]);
++i;
}
You may alias map with some function(s) to a symbol and use
it separately:
import std.algorithm.comparison : equal;
import std.conv : to;
alias stringize = map!(to!string);
assert(equal(stringize([ 1, 2, 3, 4 ]), [ "1", "2", "3", "4" ]));
map!(p => "-I" ~ p).string[] std.array.array!(sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L494_C23, string[]))(sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L494_C23, string[]) r) pure @safeAllocates an array and initializes it with copies of the elements
of range r.
Narrow strings are handled as follows:
If autodecoding is turned on (default), then they are handled as a separate overload.
If autodecoding is turned off, then this is equivalent to duplicating the array.
array
~ (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) string[] sparkles.test_runner.driver.DriverOptions.stringImportPathsextra -J paths
stringImportPaths.sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L495_C42, const(string)[]) sparkles.test_runner.driver.allImportFlags.map!(const(string)[])(const(string)[] r) pure nothrow @nogc @safeImplements the homonym function (also known as transform) present
in many languages of functional flavor. The call ``map!(fun)(range)
returns a range of which elements are obtained by applying fun(a)
left to right for all elements a in range. The original ranges are
not changed. Evaluation is done lazily.
Examples
import std.algorithm.comparison : equal;
import std.range : chain, only;
auto squares =
chain(only(1, 2, 3, 4), only(5, 6)).map!(a => a * a);
assert(equal(squares, only(1, 4, 9, 16, 25, 36)));
Multiple functions can be passed to map. In that case, the
element type of map is a tuple containing one element for each
function.
auto sums = [2, 4, 6, 8];
auto products = [1, 4, 9, 16];
size_t i = 0;
foreach (result; [ 1, 2, 3, 4 ].map!("a + a", "a * a"))
{
assert(result[0] == sums[i]);
assert(result[1] == products[i]);
++i;
}
You may alias map with some function(s) to a symbol and use
it separately:
import std.algorithm.comparison : equal;
import std.conv : to;
alias stringize = map!(to!string);
assert(equal(stringize([ 1, 2, 3, 4 ]), [ "1", "2", "3", "4" ]));
map!(p => "-J" ~ p).string[] std.array.array!(sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L495_C42, const(string)[]))(sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L495_C42, const(string)[]) r) pure @safeAllocates an array and initializes it with copies of the elements
of range r.
Narrow strings are handled as follows:
If autodecoding is turned on (default), then they are handled as a separate overload.
If autodecoding is turned off, then this is equivalent to duplicating the array.
array
~ (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) string[] sparkles.test_runner.driver.DriverOptions.versionsversion identifiers
versions.sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L496_C33, const(string)[]) sparkles.test_runner.driver.allImportFlags.map!(const(string)[])(const(string)[] r) pure nothrow @nogc @safeImplements the homonym function (also known as transform) present
in many languages of functional flavor. The call ``map!(fun)(range)
returns a range of which elements are obtained by applying fun(a)
left to right for all elements a in range. The original ranges are
not changed. Evaluation is done lazily.
Examples
import std.algorithm.comparison : equal;
import std.range : chain, only;
auto squares =
chain(only(1, 2, 3, 4), only(5, 6)).map!(a => a * a);
assert(equal(squares, only(1, 4, 9, 16, 25, 36)));
Multiple functions can be passed to map. In that case, the
element type of map is a tuple containing one element for each
function.
auto sums = [2, 4, 6, 8];
auto products = [1, 4, 9, 16];
size_t i = 0;
foreach (result; [ 1, 2, 3, 4 ].map!("a + a", "a * a"))
{
assert(result[0] == sums[i]);
assert(result[1] == products[i]);
++i;
}
You may alias map with some function(s) to a symbol and use
it separately:
import std.algorithm.comparison : equal;
import std.conv : to;
alias stringize = map!(to!string);
assert(equal(stringize([ 1, 2, 3, 4 ]), [ "1", "2", "3", "4" ]));
map!(v => (ldc ? "-d-version=" : "-version=") ~ v).string[] std.array.array!(sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L496_C33, const(string)[]))(sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L496_C33, const(string)[]) r) pure @safeAllocates an array and initializes it with copies of the elements
of range r.
Narrow strings are handled as follows:
If autodecoding is turned on (default), then they are handled as a separate overload.
If autodecoding is turned off, then this is equivalent to duplicating the array.
array
~ (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) string[] sparkles.test_runner.driver.DriverOptions.dflagsextra compiler flags
dflags.string[] object.dup!string(const(string)[] a) pure nothrow @property @safedup;
}
// ─────────────────────────────────────────────────────────────────────────────
// @ctfe
// ─────────────────────────────────────────────────────────────────────────────
/// The outcome of evaluating `@ctfe` tests through a probe compile.
struct (struct) sparkles.test_runner.driver.CtfeOutcomeThe outcome of evaluating @ctfe tests through a probe compile.
CtfeOutcome
{
bool (field) bool sparkles.test_runner.driver.CtfeOutcome.skippedno D compiler found — reported but not a failure
skipped; /// no D compiler found — reported but not a failure
bool (field) bool sparkles.test_runner.driver.CtfeOutcome.succeededthe probe compiled: every selected test passed
succeeded; /// the probe compiled: every selected test passed
(alias) object.string = stringstring[] (field) string[] sparkles.test_runner.driver.CtfeOutcome.failedNamesfailing tests attributed from the compiler errors
failedNames; /// failing tests attributed from the compiler errors
(alias) object.string = stringstring (field) string sparkles.test_runner.driver.CtfeOutcome.outputfull compiler output (__ctfeWrite text, errors, …)
output; /// full compiler output (`__ctfeWrite` text, errors, …)
}
/// The actual module containing `test`: `test.moduleName` with aggregate
/// qualifiers stripped (a nested test's `fullName` includes its aggregate),
/// found by peeling trailing components until the name matches the file path.
(alias) object.string = stringstring string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safeThe actual module containing test: ``test.moduleName with aggregate
qualifiers stripped (a nested test's fullName includes its aggregate),
found by peeling trailing components until the name matches the file path.
probeModuleName(const (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test (parameter) const(sparkles.test_runner.model.Test) testtest) @safe pure nothrow
{
(alias) object.string = stringstring (local variable) string candidatecandidate = (parameter) const(sparkles.test_runner.model.Test) testtest.string sparkles.test_runner.model.Test.moduleName() const pure nothrow @nogc return scope @safeThe module part of fullName (everything before the last .).
moduleName;
while ((local variable) string candidatecandidate.length)
{
if (string sparkles.test_runner.extract.sourceRootOf(string file, string moduleName) pure nothrow @safeDerives the source root of a module from its file path and dotted name:
("libs/base/src/sparkles/base/buffer.d", "sparkles.base.buffer")
yields "libs/base/src". Returns null when the path does not end with
the module path. Either separator matches: on Windows the compiler reports
libs\base\src\sparkles\base\buffer.d, and the root keeps its own
separators.
sourceRootOf((parameter) const(sparkles.test_runner.model.Test) testtest.(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.locationlocation.(field) string sparkles.test_runner.model.TestLocation.filefile, (local variable) string candidatecandidate) !is null)
return (local variable) string candidatecandidate;
(alias) object.size_t = ulongsize_t (local variable) ulong cutcut = 0;
foreach_reverse ((parameter) ulong ii, (parameter) immutable(char) cc; (local variable) string candidatecandidate)
if ((local variable) immutable(char) cc == '.')
{
(local variable) ulong cutcut = (local variable) ulong ii;
break;
}
if (!(local variable) ulong cutcut)
break;
(local variable) string candidatecandidate = (local variable) string candidatecandidate[0 .. (local variable) ulong cutcut];
}
return (parameter) const(sparkles.test_runner.model.Test) testtest.string sparkles.test_runner.model.Test.moduleName() const pure nothrow @nogc return scope @safeThe module part of fullName (everything before the last .).
moduleName;
}
@("probeModuleName.nestedAndPlain")
@safe pure
unittest
{
import (package) sparklessparkles.(package) sparkles.test_runnertest_runner.(module) sparkles.test_runner.modelData model of the test runner: descriptions of discovered tests and the
results of executing them.
Everything here is runtime data — the compile-time discovery that produces
it lives in sparkles.test_runner.discovery.
model : (struct) sparkles.test_runner.model.TestLocationSource location of a unittest block, from __traits(getLocation).
The file path is as the compiler saw it (usually relative to the package
root that dub test runs in).
TestLocation;
const (local variable) const(sparkles.test_runner.model.Test) plainplain = (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test(fullName: "pkg.mod.__unittest_L1_C1", name: "t",
location: (struct) sparkles.test_runner.model.TestLocationSource location of a unittest block, from __traits(getLocation).
The file path is as the compiler saw it (usually relative to the package
root that dub test runs in).
TestLocation(file: "src/pkg/mod.d", line: 1, column: 1));
assert(string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safeThe actual module containing test: ``test.moduleName with aggregate
qualifiers stripped (a nested test's fullName includes its aggregate),
found by peeling trailing components until the name matches the file path.
probeModuleName((local variable) const(sparkles.test_runner.model.Test) plainplain) == "pkg.mod");
const (local variable) const(sparkles.test_runner.model.Test) nestednested = (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test(fullName: "pkg.mod.Host.__unittest_L9_C1", name: "t",
location: (struct) sparkles.test_runner.model.TestLocationSource location of a unittest block, from __traits(getLocation).
The file path is as the compiler saw it (usually relative to the package
root that dub test runs in).
TestLocation(file: "src/pkg/mod.d", line: 9, column: 1));
assert(string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safeThe actual module containing test: ``test.moduleName with aggregate
qualifiers stripped (a nested test's fullName includes its aggregate),
found by peeling trailing components until the name matches the file path.
probeModuleName((local variable) const(sparkles.test_runner.model.Test) nestednested) == "pkg.mod");
// Unresolvable path ↔ name pairs fall back to the raw module name.
const (local variable) const(sparkles.test_runner.model.Test) oddodd = (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test(fullName: "pkg.mod.__unittest_L1_C1", name: "t",
location: (struct) sparkles.test_runner.model.TestLocationSource location of a unittest block, from __traits(getLocation).
The file path is as the compiler saw it (usually relative to the package
root that dub test runs in).
TestLocation(file: "elsewhere.d", line: 1, column: 1));
assert(string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safeThe actual module containing test: ``test.moduleName with aggregate
qualifiers stripped (a nested test's fullName includes its aggregate),
found by peeling trailing components until the name matches the file path.
probeModuleName((local variable) const(sparkles.test_runner.model.Test) oddodd) == "pkg.mod");
// A Windows path names the same module.
const (local variable) const(sparkles.test_runner.model.Test) windowswindows = (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test(fullName: "pkg.mod.Host.__unittest_L9_C1", name: "t",
location: (struct) sparkles.test_runner.model.TestLocationSource location of a unittest block, from __traits(getLocation).
The file path is as the compiler saw it (usually relative to the package
root that dub test runs in).
TestLocation(file: `src\pkg\mod.d`, line: 9, column: 1));
assert(string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safeThe actual module containing test: ``test.moduleName with aggregate
qualifiers stripped (a nested test's fullName includes its aggregate),
found by peeling trailing components until the name matches the file path.
probeModuleName((local variable) const(sparkles.test_runner.model.Test) windowswindows) == "pkg.mod");
assert(string[] sparkles.test_runner.driver.deriveImportPaths(in sparkles.test_runner.model.Test[] allTests, in string[] extra) pure @safe-I roots derived from every discovered test's module-name ↔ file-path
pair, after the extras: the user's, then the harness roots the binary
reported. Never the runner's own root: the pinned runner's copy of the
attributes is not the one the tested package was compiled against
(process-model TRX4).
deriveImportPaths([(local variable) const(sparkles.test_runner.model.Test) windowswindows], null) == [`src`]);
}
/// Failing test names attributed from probe-compile output: the display-name
/// argument of `ctfePassed!(…, "name")` on `error instantiating` lines.
(alias) object.string = stringstring[] string[] sparkles.test_runner.driver.parseCtfeFailures(string output) pure @safeFailing test names attributed from probe-compile output: the display-name
argument of ctfePassed!(…, "name") on error instantiating lines.
parseCtfeFailures((alias) object.string = stringstring (parameter) string outputoutput) @safe pure
{
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.searchingThis is a submodule of std.algorithm.
It contains generic searching algorithms.
Function Name Description all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses. boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm. canFind canFind("hello world", "or") returns true. count Counts all elements or elements matching a predicate, specific element or sub-range.
count([1, 2, 1]) returns 3,
count([1, 2, 1], 1) returns 2 and
count!"a < 0"([1, -3, 0]) returns 1. |
| countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. |
| commonPrefix | commonPrefix("parakeet", "parachute") returns "para". |
| endsWith | endsWith("rocks", "ks") returns true. |
| extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. |
| find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) |
| findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. |
| findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". |
| findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. |
| findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". |
| findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". |
| findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". |
| minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). |
| maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). |
| minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. |
| maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. |
| minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. |
| maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. |
| minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. |
| maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. |
| skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. |
| startsWith | startsWith("hello, world", "hello") returns true. |
| until | Lazily iterates a range until a specific value is found. |
Source
std/algorithm/searching.d
searching : (alias template) canFind = std.algorithm.searching.canFind(alias pred = "a == b")Convenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see $(LREF find).
See_Also:
$(REF among, std,algorithm,comparison) for checking a value against multiple arguments.
canFind;
import (package) stdstd.(module) std.stringString handling functions.
Category Functions Searching column indexOf indexOfAny indexOfNeither lastIndexOf lastIndexOfAny lastIndexOfNeither Comparison isNumeric Mutation capitalize Pruning and Filling center chomp chompPrefix chop detabber detab entab entabber leftJustify outdent rightJustify strip stripLeft stripRight wrap Substitution abbrev soundex soundexer succ tr translate Miscellaneous assumeUTF fromStringz lineSplitter representation splitLines toStringz Objects of types string, wstring, and dstring are value types and cannot be mutated element-by-element. For using mutation during building strings, use char[], wchar[], or dchar[]. The xxxstring types are preferable because they don't exhibit undesired aliasing, thus making code more robust.
The following functions are publicly imported:
Module Functions Publicly imported functions std.algorithm cmp, std,algorithm,comparison count, std,algorithm,searching endsWith, std,algorithm,searching startsWith, std,algorithm,searching std.array join, std,array replace, std,array replaceInPlace, std,array split, std,array empty, std,array std.format format, std,format sformat, std,format std.uni icmp, std,uni toLower, std,uni toLowerInPlace, std,uni toUpper, std,uni toUpperInPlace, std,uni There is a rich set of functions for string handling defined in other modules. Functions related to Unicode and ASCII are found in std.uni and std.ascii, respectively. Other functions that have a wider generality than just strings can be found in std.algorithm and std.range.
Source
std/string.d
string : (alias template) indexOf = std.string.indexOf(Range)(Range s, dchar c, CaseSensitive cs = Yes.caseSensitive) if (isInputRange!Range && isSomeChar!(ElementType!Range) && !isSomeString!Range)Searches for a character in a string or range.
Params:
s = string or InputRange of characters to search for `c` in
c = character to search for in `s`
startIdx = index to a well-formed code point in `s` to start
searching from; defaults to 0
cs = specifies whether comparisons are case-sensitive
(`Yes.caseSensitive`) or not (`No.caseSensitive`).
Returns:
If `c` is found in `s`, then the index of its first occurrence is
returned. If `c` is not found or `startIdx` is greater than or equal to
`s.length`, then -1 is returned. If the parameters are not valid UTF,
the result will still be either -1 or in the range [`startIdx` ..
`s.length`], but will not be reliable otherwise.
Throws:
If the sequence starting at `startIdx` does not represent a well-formed
code point, then a $(REF UTFException, std,utf) may be thrown.
See_Also: $(REF countUntil, std,algorithm,searching)
indexOf, (alias template) lineSplitter = std.string.lineSplitter(Flag keepTerm = No.keepTerminator, Range)(Range r) if (hasSlicing!Range && hasLength!Range && isSomeChar!(ElementType!Range) && !isSomeString!Range)Split an array or slicable range of characters into a range of lines
using '\r', '\n', '\v', '\f', "\r\n",
$(REF lineSep, std,uni), $(REF paraSep, std,uni) and '\u0085' (NEL)
as delimiters. If keepTerm is set to Yes.keepTerminator, then the
delimiter is included in the slices returned.
Does not throw on invalid UTF; such is simply passed unchanged
to the output.
Adheres to $(HTTP www.unicode.org/versions/Unicode7.0.0/ch05.pdf, Unicode 7.0).
Does not allocate memory.
Params:
r = array of chars, wchars, or dchars or a slicable range
keepTerm = whether delimiter is included or not in the results
Returns:
range of slices of the input range r
See_Also:
$(LREF splitLines)
$(REF splitter, std,algorithm)
$(REF splitter, std,regex)
lineSplitter;
(alias) object.string = stringstring[] (local variable) string[] namesnames;
foreach ((local variable) string lineline; (parameter) string outputoutput.std.string.LineSplitter!(Flag.no, string) std.string.lineSplitter!(Flag.no, immutable(char))(string r) pure nothrow @nogc @safeSplit an array or slicable range of characters into a range of lines
using '\r', '\n', '\v', '\f', "\r\n",
lineSep, paraSep and '\u0085' (NEL)
as delimiters. If keepTerm is set to Yes.keepTerminator, then the
delimiter is included in the slices returned.
Does not throw on invalid UTF; such is simply passed unchanged
to the output.
Adheres to Unicode 7.0.
Does not allocate memory.
Examples
import std.array : array;
string s = "Hello\nmy\rname\nis";
/* notice the call to 'array' to turn the lazy range created by
lineSplitter comparable to the string[] created by splitLines.
*/
assert(lineSplitter(s).array == splitLines(s));
auto s = "\rpeter\n\rpaul\r\njerry\u2028ice\u2029cream\n\nsunday\nmon\u2030day\n";
auto lines = s.lineSplitter();
static immutable witness = ["", "peter", "", "paul", "jerry", "ice", "cream", "", "sunday", "mon\u2030day"];
uint i;
foreach (line; lines)
{
assert(line == witness[i++]);
}
assert(i == witness.length);
lineSplitter)
{
if (!(local variable) string lineline.bool std.algorithm.searching.canFind!().canFind!(string, string)(string haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind("error instantiating"))
continue;
auto (local variable) long atat = (local variable) string lineline.long std.string.indexOf!(string, char)(string s, const(char)[] sub) pure nothrow @nogc @safeSearches for a substring in a string or range.
indexOf("ctfePassed!(");
if ((local variable) long atat < 0)
continue;
const (local variable) const(long) openopen = (local variable) string lineline.long std.string.indexOf!char(scope const(char)[] s, dchar c, ulong startIdx, std.typecons.Flag!"caseSensitive" cs = Flag.yes) pure nothrow @nogc @safeSearches for a character in a string or range.
Examples
import std.typecons : No;
string s = "Hello World";
assert(indexOf(s, 'W') == 6);
assert(indexOf(s, 'Z') == -1);
assert(indexOf(s, 'w', No.caseSensitive) == 6);
import std.typecons : No;
string s = "Hello World";
assert(indexOf(s, 'W', 4) == 6);
assert(indexOf(s, 'Z', 100) == -1);
assert(indexOf(s, 'w', 3, No.caseSensitive) == 6);
indexOf('"', (local variable) long atat);
if ((local variable) const(long) openopen < 0)
continue;
(alias) object.size_t = ulongsize_t (local variable) ulong closeclose = (local variable) const(long) openopen + 1;
while ((local variable) ulong closeclose < (local variable) string lineline.(field) ulong string.lengthlength && !((local variable) string lineline[(local variable) ulong closeclose] == '"' && (local variable) string lineline[(local variable) ulong closeclose - 1] != '\\'))
(local variable) ulong closeclose++;
if ((local variable) ulong closeclose >= (local variable) string lineline.(field) ulong string.lengthlength)
continue;
const (local variable) const(string) namename = (local variable) string lineline[(local variable) const(long) openopen + 1 .. (local variable) ulong closeclose];
if (!(local variable) string[] namesnames.bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind((local variable) const(string) namename))
(local variable) string[] namesnames ~= (local variable) const(string) namename;
}
return (local variable) string[] namesnames;
}
@("parseCtfeFailures.trailLines")
@safe pure
unittest
{
enum (constant) string sparkles.test_runner.driver.__unittest_L595_C1.output = "src/m.d(12,5): Error: boom\nprobe.d(60,27): Error: template instance `sparkles_test_runner_ctfe.ctfePassed!(__unittest_L12_C1, \"a.one\")` error instantiating\nprobe.d(60,13): while evaluating: `static assert(ctfePassed!(__unittest_L12_C1, \"a.one\"))`\nprobe.d(64,27): Error: template instance `sparkles_test_runner_ctfe.ctfePassed!(__unittest_L30_C1, \"b.two\")` error instantiating\n"output = "src/m.d(12,5): Error: boom\n" ~
"probe.d(60,27): Error: template instance " ~
"`sparkles_test_runner_ctfe.ctfePassed!(__unittest_L12_C1, \"a.one\")` " ~
"error instantiating\n" ~
"probe.d(60,13): while evaluating: `static assert(ctfePassed!" ~
"(__unittest_L12_C1, \"a.one\"))`\n" ~
"probe.d(64,27): Error: template instance " ~
"`sparkles_test_runner_ctfe.ctfePassed!(__unittest_L30_C1, \"b.two\")` " ~
"error instantiating\n";
assert(string[] sparkles.test_runner.driver.parseCtfeFailures(string output) pure @safeFailing test names attributed from probe-compile output: the display-name
argument of ctfePassed!(…, "name") on error instantiating lines.
parseCtfeFailures((constant) string sparkles.test_runner.driver.__unittest_L595_C1.output = "src/m.d(12,5): Error: boom\nprobe.d(60,27): Error: template instance `sparkles_test_runner_ctfe.ctfePassed!(__unittest_L12_C1, \"a.one\")` error instantiating\nprobe.d(60,13): while evaluating: `static assert(ctfePassed!(__unittest_L12_C1, \"a.one\"))`\nprobe.d(64,27): Error: template instance `sparkles_test_runner_ctfe.ctfePassed!(__unittest_L30_C1, \"b.two\")` error instantiating\n"output) == ["a.one", "b.two"]);
assert(string[] sparkles.test_runner.driver.parseCtfeFailures(string output) pure @safeFailing test names attributed from probe-compile output: the display-name
argument of ctfePassed!(…, "name") on error instantiating lines.
parseCtfeFailures("all fine") == []);
}
/// Evaluates the given `@ctfe` tests: generates a probe program selecting
/// exactly those tests, and compiles it — together with the tests' module
/// sources — with `-o- -unittest` (semantic analysis only, so CTFE runs but
/// nothing is codegen'd or linked). When `traceFile` is given, LDC's
/// `-ftime-trace` flags are added and the trace is written there.
(struct) sparkles.test_runner.driver.CtfeOutcomeThe outcome of evaluating @ctfe tests through a probe compile.
CtfeOutcome sparkles.test_runner.driver.CtfeOutcome sparkles.test_runner.driver.runCtfeTests(in sparkles.test_runner.model.Test[] ctfeTests, in sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options, string traceFile = null)Evaluates the given @ctfe tests: generates a probe program selecting
exactly those tests, and compiles it — together with the tests' module
sources — with -o- -unittest (semantic analysis only, so CTFE runs but
nothing is codegen'd or linked). When traceFile is given, LDC's
-ftime-trace flags are added and the trace is written there.
runCtfeTests(
in (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test[] (parameter) const(sparkles.test_runner.model.Test[]) ctfeTestsctfeTests, in (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test[] (parameter) const(sparkles.test_runner.model.Test[]) allTestsallTests, in (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions,
(alias) object.string = stringstring (parameter) string traceFiletraceFile = null)
{
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.searchingThis is a submodule of std.algorithm.
It contains generic searching algorithms.
Function Name Description all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses. boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm. canFind canFind("hello world", "or") returns true. count Counts all elements or elements matching a predicate, specific element or sub-range.
count([1, 2, 1]) returns 3,
count([1, 2, 1], 1) returns 2 and
count!"a < 0"([1, -3, 0]) returns 1. |
| countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. |
| commonPrefix | commonPrefix("parakeet", "parachute") returns "para". |
| endsWith | endsWith("rocks", "ks") returns true. |
| extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. |
| find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) |
| findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. |
| findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". |
| findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. |
| findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". |
| findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". |
| findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". |
| minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). |
| maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). |
| minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. |
| maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. |
| minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. |
| maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. |
| minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. |
| maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. |
| skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. |
| startsWith | startsWith("hello, world", "hello") returns true. |
| until | Lazily iterates a range until a specific value is found. |
Source
std/algorithm/searching.d
searching : (alias template) canFind = std.algorithm.searching.canFind(alias pred = "a == b")Convenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see $(LREF find).
See_Also:
$(REF among, std,algorithm,comparison) for checking a value against multiple arguments.
canFind;
import (package) stdstd.(module) std.fileUtilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one file
at a time. For opening files and manipulating them via handles refer
to module std.stdio.
Category Functions General exists isDir isFile isSymlink rename thisExePath Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir Files append copy read readText remove slurp write Symlinks symlink readLink Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace
Source
std/file.d
file : (alias) mkdirRecurse = void std.file.mkdirRecurse(scope const(char)[] pathname) @safeMake directory and all parent directories as needed.
Does nothing if the directory specified by
pathname already exists.
Params:
pathname = the full path of the directory to create
Throws: $(LREF FileException) on error.
mkdirRecurse, (alias template) write = std.file.write(R)(R name, const void[] buffer) if ((isSomeFiniteCharInputRange!R || isSomeString!R) && !isConvertibleToString!R)Write buffer to file name.
Creates the file if it does not already exist.
Params:
name = string or range of characters representing the file _name
buffer = data to be written to file
Throws: $(LREF FileException) on error.
See_also: $(REF toFile, std,stdio)
write;
import (package) stdstd.(module) std.pathThis module is used to manipulate path strings.
All functions, with the exception of expandTilde (and in some
cases absolutePath and relativePath), are pure
string manipulation functions; they don't depend on any state outside
the program, nor do they perform any actual file system actions.
This has the consequence that the module does not make any distinction
between a path that points to a directory and a path that points to a
file, and it does not know whether or not the object pointed to by the
path actually exists in the file system.
To differentiate between these cases, use isDir and
exists.
Note that on Windows, both the backslash (\) and the slash (/)
are in principle valid directory separators. This module treats them
both on equal footing, but in cases where a new separator is
added, a backslash will be used. Furthermore, the buildNormalizedPath
function will replace all slashes with backslashes on that platform.
In general, the functions in this module assume that the input paths
are well-formed. (That is, they should not contain invalid characters,
they should follow the file system's path format, etc.) The result
of calling a function on an ill-formed path is undefined. When there
is a chance that a path or a file name is invalid (for instance, when it
has been input by the user), it may sometimes be desirable to use the
isValidFilename and isValidPath functions to check
this.
Most functions do not perform any memory allocations, and if a string is
returned, it is usually a slice of an input string. If a function
allocates, this is explicitly mentioned in the documentation.
Category Functions Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension Other filenameCharCmp filenameCmp globMatch CaseSensitive
Source
std/path.d
path : (alias template) buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))Combines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by $(LREF isAbsolute)), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. $(D `\foo`)), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if `paths` is a forward
range.
Params:
segments = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
of segments to assemble the path from.
Returns: The assembled path.
buildPath, (alias template) dirName = std.path.dirName(R)(return scope R path) if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R)Returns the parent directory of path. On Windows, this
includes the drive letter if present. If path is a relative path and
the parent directory is the current working directory, returns ".".
Params:
path = A path name.
Returns:
A slice of `path` or `"."`.
Standards:
This function complies with
$(LINK2 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/dirname.html,
the POSIX requirements for the 'dirname' shell utility)
(with suitable adaptations for Windows paths).
dirName;
(struct) sparkles.test_runner.driver.CtfeOutcomeThe outcome of evaluating @ctfe tests through a probe compile.
CtfeOutcome (local variable) sparkles.test_runner.driver.CtfeOutcome outcomeoutcome;
const (local variable) const(string) compilercompiler = string sparkles.test_runner.driver.detectCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report = ModeReport(null, null)) @safeThe D compiler to use: explicit choice, $DC, or the first of
ldc2/dmd found in $PATH (empty string when none). An explicit choice
that doesn't resolve is reported to report and treated as "no compiler", so
the caller's toolchain-missing skip fires instead of a raw
ProcessException escaping from the spawn.
detectCompiler((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) string sparkles.test_runner.driver.DriverOptions.compilerexplicit D compiler; empty = $DC, then ldc2, dmd
compiler, (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.reportwhere the modes' messages go
report);
if (!(local variable) const(string) compilercompiler.(field) ulong const(string).lengthlength)
{
(local variable) sparkles.test_runner.driver.CtfeOutcome outcomeoutcome.(field) bool sparkles.test_runner.driver.CtfeOutcome.skippedno D compiler found — reported but not a failure
skipped = true;
return (local variable) sparkles.test_runner.driver.CtfeOutcome outcomeoutcome;
}
(struct) sparkles.test_runner.extract.CtfeTargetOne @ctfe test to force through CTFE in a generated probe program.
CtfeTarget[] (local variable) sparkles.test_runner.extract.CtfeTarget[] targetstargets;
(alias) object.string = stringstring[] (local variable) string[] moduleFilesmoduleFiles;
foreach (ref (parameter) const(sparkles.test_runner.model.Test) testtest; (parameter) const(sparkles.test_runner.model.Test[]) ctfeTestsctfeTests)
{
(local variable) sparkles.test_runner.extract.CtfeTarget[] targetstargets ~= (struct) sparkles.test_runner.extract.CtfeTargetOne @ctfe test to force through CTFE in a generated probe program.
CtfeTarget(
moduleName: string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safeThe actual module containing test: ``test.moduleName with aggregate
qualifiers stripped (a nested test's fullName includes its aggregate),
found by peeling trailing components until the name matches the file path.
probeModuleName((local variable) const(sparkles.test_runner.model.Test) testtest),
file: (local variable) const(sparkles.test_runner.model.Test) testtest.(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.locationlocation.(field) string sparkles.test_runner.model.TestLocation.filefile,
line: (local variable) const(sparkles.test_runner.model.Test) testtest.(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.locationlocation.(field) ulong sparkles.test_runner.model.TestLocation.lineline,
name: (local variable) const(sparkles.test_runner.model.Test) testtest.(field) string sparkles.test_runner.model.Test.nameDisplay name: the first string UDA, or the symbol identifier.
name,
);
if (!(local variable) string[] moduleFilesmoduleFiles.bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind((local variable) const(sparkles.test_runner.model.Test) testtest.(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.locationlocation.(field) string sparkles.test_runner.model.TestLocation.filefile))
(local variable) string[] moduleFilesmoduleFiles ~= (local variable) const(sparkles.test_runner.model.Test) testtest.(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.locationlocation.(field) string sparkles.test_runner.model.TestLocation.filefile;
}
const (local variable) const(string) workDirworkDir = string sparkles.test_runner.driver.makeWorkDir(string flavor, string own = null)A fresh scratch directory for the generated program: beneath own, the
run's DriverOptions.probeDir, when it names one, so clients that run
several modes at once in one process keep them apart; else beneath
setProbeDir's.
makeWorkDir("ctfe", (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) string sparkles.test_runner.driver.DriverOptions.probeDirwhere generated programs go; empty = the temp directory
probeDir);
const (local variable) const(string) sourceFilesourceFile = string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath((local variable) const(string) workDirworkDir, "ctfe_tests.d");
void std.file.write!string(string name, const(void[]) buffer) @safeWrite buffer to file name.
Creates the file if it does not already exist.
Examples
scope(exit)
{
assert(exists(deleteme));
remove(deleteme);
}
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write(deleteme, a); // deleteme is the name of a temporary file
const bytes = read(deleteme);
const fileInts = () @trusted { return cast(int[]) bytes; }();
assert(fileInts == a);
write((local variable) const(string) sourceFilesourceFile, string sparkles.test_runner.extract.generateCtfeProgram(in sparkles.test_runner.extract.CtfeTarget[] targets) pure @safeA complete probe program forcing the given @ctfe tests through CTFE.
The probe imports each test's module and selects the tests by
reflection (matching __traits(getLocation) lines), so test bodies stay
in their home modules — private symbols keep working and no source
extraction is involved. It is meant to be compiled with -o- -unittest
together with the modules' source files: semantic analysis (and therefore
CTFE) only, no code generation. A failing test is a compile error whose
closing error instantiating line carries the test's display name.
generateCtfeProgram((local variable) sparkles.test_runner.extract.CtfeTarget[] targetstargets));
(alias) object.string = stringstring[] (local variable) string[] traceFlagstraceFlags;
if ((parameter) string traceFiletraceFile.(field) ulong string.lengthlength)
{
try
void std.file.mkdirRecurse(scope const(char)[] pathname) @safeMake directory and all parent directories as needed.
Does nothing if the directory specified by
pathname already exists.
Examples
import std.path : buildPath;
auto dir = deleteme ~ "dir";
scope(exit) dir.rmdirRecurse;
dir.mkdir;
assert(dir.exists);
dir.mkdirRecurse; // does nothing
// creates all parent directories as needed
auto nested = dir.buildPath("a", "b", "c");
nested.mkdirRecurse;
assert(nested.exists);
import std.exception : assertThrown;
scope(exit) deleteme.remove;
deleteme.write("a");
// cannot make directory as it's already a file
assertThrown!FileException(deleteme.mkdirRecurse);
mkdirRecurse((parameter) string traceFiletraceFile.string std.path.dirName!(immutable(char))(return scope string path) pure nothrow @nogc @safeReturns the parent directory of path. On Windows, this
includes the drive letter if present. If path is a relative path and
the parent directory is the current working directory, returns ".".
Examples
assert(dirName("") == ".");
assert(dirName("file"w) == ".");
assert(dirName("dir/"d) == ".");
assert(dirName("dir///") == ".");
assert(dirName("dir/file"w.dup) == "dir");
assert(dirName("dir///file"d.dup) == "dir");
assert(dirName("dir/subdir/") == "dir");
assert(dirName("/dir/file"w) == "/dir");
assert(dirName("/file"d) == "/");
assert(dirName("/") == "/");
assert(dirName("///") == "/");
version (Windows)
{
assert(dirName(`dir\`) == `.`);
assert(dirName(`dir\\\`) == `.`);
assert(dirName(`dir\file`) == `dir`);
assert(dirName(`dir\\\file`) == `dir`);
assert(dirName(`dir\subdir\`) == `dir`);
assert(dirName(`\dir\file`) == `\dir`);
assert(dirName(`\file`) == `\`);
assert(dirName(`\`) == `\`);
assert(dirName(`\\\`) == `\`);
assert(dirName(`d:`) == `d:`);
assert(dirName(`d:file`) == `d:`);
assert(dirName(`d:\`) == `d:\`);
assert(dirName(`d:\file`) == `d:\`);
assert(dirName(`d:\dir\file`) == `d:\dir`);
assert(dirName(`\\server\share\dir\file`) == `\\server\share\dir`);
assert(dirName(`\\server\share\file`) == `\\server\share`);
assert(dirName(`\\server\share\`) == `\\server\share`);
assert(dirName(`\\server\share`) == `\\server\share`);
}
dirName);
catch ((class) object.ExceptionThe base class of all errors that are safe to catch and handle.
In principle, only thrown objects derived from this class are safe to catch
inside a catch block. Thrown objects not derived from Exception
represent runtime errors that should not be caught, as certain runtime
guarantees may not hold, making it unsafe to continue program execution.
Examples
bool gotCaught;
try
{
throw new Exception("msg");
}
catch (Exception e)
{
gotCaught = true;
assert(e.msg == "msg");
}
assert(gotCaught);
Exception (local variable) object.Exception ee)
{
// An uncreatable trace directory must not escape the unittest hook
// as a raw FileException stack trace; fail readably (the caller
// prints `output` and recognizes the `--ctfe-trace:` prefix as an
// environment problem, not a test failure).
import (package) stdstd.(module) std.convA one-stop shop for converting values from one type to another.
Category Functions Generic asOriginalType castFrom parse to toChars bitCast Strings text wtext dtext writeText writeWText writeDText hexString Numeric octal roundTo signed unsigned Exceptions ConvException ConvOverflowException
Source
std/conv.d
conv : (alias template) text = std.conv.text(T...)(T args) if (T.length > 0)Convenience functions for converting one or more arguments
of any type into _text (the three character widths).
text;
(local variable) sparkles.test_runner.driver.CtfeOutcome outcomeoutcome.(field) string sparkles.test_runner.driver.CtfeOutcome.outputfull compiler output (__ctfeWrite text, errors, …)
output = string std.conv.text!(string, string, string, string, string)(string __param_0, string __param_1, string __param_2, string __param_3, string __param_4) pure nothrow @safeConvenience functions for converting one or more arguments
of any type into text (the three character widths).
text("--ctfe-trace: cannot create '",
(parameter) string traceFiletraceFile.string std.path.dirName!(immutable(char))(return scope string path) pure nothrow @nogc @safeReturns the parent directory of path. On Windows, this
includes the drive letter if present. If path is a relative path and
the parent directory is the current working directory, returns ".".
Examples
assert(dirName("") == ".");
assert(dirName("file"w) == ".");
assert(dirName("dir/"d) == ".");
assert(dirName("dir///") == ".");
assert(dirName("dir/file"w.dup) == "dir");
assert(dirName("dir///file"d.dup) == "dir");
assert(dirName("dir/subdir/") == "dir");
assert(dirName("/dir/file"w) == "/dir");
assert(dirName("/file"d) == "/");
assert(dirName("/") == "/");
assert(dirName("///") == "/");
version (Windows)
{
assert(dirName(`dir\`) == `.`);
assert(dirName(`dir\\\`) == `.`);
assert(dirName(`dir\file`) == `dir`);
assert(dirName(`dir\\\file`) == `dir`);
assert(dirName(`dir\subdir\`) == `dir`);
assert(dirName(`\dir\file`) == `\dir`);
assert(dirName(`\file`) == `\`);
assert(dirName(`\`) == `\`);
assert(dirName(`\\\`) == `\`);
assert(dirName(`d:`) == `d:`);
assert(dirName(`d:file`) == `d:`);
assert(dirName(`d:\`) == `d:\`);
assert(dirName(`d:\file`) == `d:\`);
assert(dirName(`d:\dir\file`) == `d:\dir`);
assert(dirName(`\\server\share\dir\file`) == `\\server\share\dir`);
assert(dirName(`\\server\share\file`) == `\\server\share`);
assert(dirName(`\\server\share\`) == `\\server\share`);
assert(dirName(`\\server\share`) == `\\server\share`);
}
dirName, "': ", (local variable) object.Exception ee.(field) string object.Throwable.msgA message describing the error.
msg, "\n");
(local variable) sparkles.test_runner.driver.CtfeOutcome outcomeoutcome.(field) bool sparkles.test_runner.driver.CtfeOutcome.succeededthe probe compiled: every selected test passed
succeeded = false;
return (local variable) sparkles.test_runner.driver.CtfeOutcome outcomeoutcome;
}
(local variable) string[] traceFlagstraceFlags = ["-ftime-trace", "-ftime-trace-file=" ~ (parameter) string traceFiletraceFile,
"--ftime-trace-granularity=0"];
}
// -verrors=0 lifts the default 20-error limit: parseCtfeFailures attributes
// failures from the `error instantiating` trail lines, and a truncated
// trail would report the cut-off failing tests as passed.
const (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compilecompile = std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safeRuns command, echoing it when verbose, and returns (status, output).
A spawn failure (compiler binary vanished between the detectCompiler
check and here, or an unlaunchable absolute path) becomes a failed result
instead of a ProcessException stack trace.
run(
[(local variable) const(string) compilercompiler, "-o-", "-unittest", "-checkaction=context", "-verrors=0"]
~ (local variable) string[] traceFlagstraceFlags ~ string[] sparkles.test_runner.driver.includeFlags(in sparkles.test_runner.driver.DriverOptions options) pure @safeThe extra -i=<pattern> flags requested with --include-import (e.g.
--include-import=std.ascii to compile a std module in when an extracted
test needs one of its non-template functions).
includeFlags((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions)
~ string[] sparkles.test_runner.driver.allImportFlags(in sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options)The compile context's flags: -I for the derived source roots, the
harness roots, dub described dependency paths unless noDub, and the
user's extras, then the string import paths, versions and flags
(process-model TRX1–TRX4).
allImportFlags((parameter) const(sparkles.test_runner.model.Test[]) allTestsallTests, (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions) ~ (local variable) string[] moduleFilesmoduleFiles ~ [(local variable) const(string) sourceFilesourceFile],
(parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions);
(local variable) sparkles.test_runner.driver.CtfeOutcome outcomeoutcome.(field) bool sparkles.test_runner.driver.CtfeOutcome.succeededthe probe compiled: every selected test passed
succeeded = (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compilecompile.status == 0;
(local variable) sparkles.test_runner.driver.CtfeOutcome outcomeoutcome.(field) string sparkles.test_runner.driver.CtfeOutcome.outputfull compiler output (__ctfeWrite text, errors, …)
output = (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compilecompile.(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1output;
if (!(local variable) sparkles.test_runner.driver.CtfeOutcome outcomeoutcome.(field) bool sparkles.test_runner.driver.CtfeOutcome.succeededthe probe compiled: every selected test passed
succeeded)
(local variable) sparkles.test_runner.driver.CtfeOutcome outcomeoutcome.(field) string[] sparkles.test_runner.driver.CtfeOutcome.failedNamesfailing tests attributed from the compiler errors
failedNames = string[] sparkles.test_runner.driver.parseCtfeFailures(string output) pure @safeFailing test names attributed from probe-compile output: the display-name
argument of ctfePassed!(…, "name") on error instantiating lines.
parseCtfeFailures((local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compilecompile.(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1output);
if ((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) bool sparkles.test_runner.driver.DriverOptions.keepkeep the generated files and print their location
keep)
void sparkles.test_runner.driver.say!(string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2) @safeargs and a line feed, to report's output.
say((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "generated files kept in ", (local variable) const(string) workDirworkDir);
return (local variable) sparkles.test_runner.driver.CtfeOutcome outcomeoutcome;
}
// ─────────────────────────────────────────────────────────────────────────────
// --better-c
// ─────────────────────────────────────────────────────────────────────────────
/// Extracts the `@betterC` tests, compiles them with `-betterC` (no
/// druntime), runs the result, and reports.
(struct) sparkles.test_runner.driver.DriverOutcomeThe outcome of one driver run.
DriverOutcome sparkles.test_runner.driver.DriverOutcome sparkles.test_runner.driver.runBetterCTests(sparkles.test_runner.model.Test[] betterCTests, sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options)Extracts the @betterC tests, compiles them with -betterC (no
druntime), runs the result, and reports.
runBetterCTests((struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test[] (parameter) sparkles.test_runner.model.Test[] betterCTestsbetterCTests, (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test[] (parameter) sparkles.test_runner.model.Test[] allTestsallTests, in (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions)
{
import (package) stdstd.(module) std.arrayFunctions and types that manipulate built-in arrays and associative arrays.
This module provides all kinds of functions to create, manipulate or convert arrays:
Function Name Description
| array |
Returns a copy of the input in a newly allocated dynamic array.
|
| appender |
Returns a new Appender or RefAppender initialized with a given array.
|
| assocArray |
Returns a newly allocated associative array from a range/ranges of keys and values.
|
| byPair |
Construct a range iterating over an associative array by key/value tuples.
|
| insertInPlace |
Inserts into an existing array at a given position.
|
| join |
Concatenates a range of ranges into one array.
|
| minimallyInitializedArray |
Returns a new array of type T.
|
| replace |
Returns a new array with all occurrences of a certain subrange replaced.
|
| replaceFirst |
Returns a new array with the first occurrence of a certain subrange replaced.
|
| replaceInPlace |
Replaces all occurrences of a certain subrange and puts the result into a given array.
|
| replaceInto |
Replaces all occurrences of a certain subrange and puts the result into an output range.
|
| replaceLast |
Returns a new array with the last occurrence of a certain subrange replaced.
|
| replaceSlice |
Returns a new array with a given slice replaced.
|
| replicate |
Creates a new array out of several copies of an input array or range.
|
| sameHead |
Checks if the initial segments of two arrays refer to the same
place in memory.
|
| sameTail |
Checks if the final segments of two arrays refer to the same place
in memory.
|
| split |
Eagerly split a range or string into an array.
|
| staticArray |
Creates a new static array from given data.
|
| uninitializedArray |
Returns a new array of type T without initializing its elements.
|
Source
std/array.d
array : (alias template) array = std.array.array(Range)(Range r) if (isIterable!Range && !isAutodecodableString!Range && !isInfinite!Range)Allocates an array and initializes it with copies of the elements
of range r.
Narrow strings are handled as follows:
If autodecoding is turned on (default), then they are handled as a separate overload.
If autodecoding is turned off, then this is equivalent to duplicating the array.
Params:
r = range (or aggregate with opApply function) whose elements are copied into the allocated array
Returns:
allocated and initialized array
array;
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.iterationThis is a submodule of std.algorithm.
It contains generic iteration algorithms.
Function Name Description cache Eagerly evaluates and caches another range's front. lazyCache Lazily evaluates and caches another range's front, unlike cache. cacheBidirectional As above, but also provides back and popBack. chunkBy chunkBy!((a,b) => a[1] == b[1])([[1, 1], [1, 2], [2, 2], [2, 1]]) returns a range containing 3 subranges: the first with just [1, 1]; the second with the elements [1, 2] and [2, 2]; and the third with just [2, 1]. cumulativeFold cumulativeFold!((a, b) => a + b)([1, 2, 3, 4]) returns a lazily-evaluated range containing the successive reduced values 1, 3, 6, 10. each each!writeln([1, 2, 3]) eagerly prints the numbers 1, 2 and 3 on their own lines. filter filter!(a => a > 0)([1, -1, 2, 0, -3]) iterates over elements 1 and 2. filterBidirectional Similar to filter, but also provides back and popBack at a small increase in cost. fold fold!((a, b) => a + b)([1, 2, 3, 4]) returns 10. group group([5, 2, 2, 3, 3]) returns a range containing the tuples tuple(5, 1), tuple(2, 2), and tuple(3, 2). joiner joiner(["hello", "world!"], "; ") returns a range that iterates over the characters "hello; world!". No new string is created - the existing inputs are iterated. map map!(a => a * 2)([1, 2, 3]) lazily returns a range with the numbers 2, 4, 6. mean Colloquially known as the average, mean([1, 2, 3]) returns 2. permutations Lazily computes all permutations using Heap's algorithm. reduce reduce!((a, b) => a + b)([1, 2, 3, 4]) returns 10. This is the old implementation of fold. splitWhen Lazily splits a range by comparing adjacent elements. splitter Lazily splits a range by a separator, element predicate or whitespace. substitute [1, 2].substitute(1, 0.1) returns [0.1, 2]. sum Same as fold, but specialized for accurate summation. uniq Iterates over the unique elements in a range, which is assumed sorted.
Source
std/algorithm/iteration.d
iteration : (alias template) map = std.algorithm.iteration.map(fun...) if (fun.length >= 1)Implements the homonym function (also known as transform) present
in many languages of functional flavor. The call map!(fun)(range)
returns a range of which elements are obtained by applying fun(a)
left to right for all elements a in range. The original ranges are
not changed. Evaluation is done lazily.
Params:
fun = one or more transformation functions
See_Also:
$(HTTP en.wikipedia.org/wiki/Map_(higher-order_function), Map (higher-order function))
map;
import (package) stdstd.(module) std.fileUtilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one file
at a time. For opening files and manipulating them via handles refer
to module std.stdio.
Category Functions General exists isDir isFile isSymlink rename thisExePath Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir Files append copy read readText remove slurp write Symlinks symlink readLink Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace
Source
std/file.d
file : (alias template) write = std.file.write(R)(R name, const void[] buffer) if ((isSomeFiniteCharInputRange!R || isSomeString!R) && !isConvertibleToString!R)Write buffer to file name.
Creates the file if it does not already exist.
Params:
name = string or range of characters representing the file _name
buffer = data to be written to file
Throws: $(LREF FileException) on error.
See_also: $(REF toFile, std,stdio)
write;
import (package) stdstd.(module) std.pathThis module is used to manipulate path strings.
All functions, with the exception of expandTilde (and in some
cases absolutePath and relativePath), are pure
string manipulation functions; they don't depend on any state outside
the program, nor do they perform any actual file system actions.
This has the consequence that the module does not make any distinction
between a path that points to a directory and a path that points to a
file, and it does not know whether or not the object pointed to by the
path actually exists in the file system.
To differentiate between these cases, use isDir and
exists.
Note that on Windows, both the backslash (\) and the slash (/)
are in principle valid directory separators. This module treats them
both on equal footing, but in cases where a new separator is
added, a backslash will be used. Furthermore, the buildNormalizedPath
function will replace all slashes with backslashes on that platform.
In general, the functions in this module assume that the input paths
are well-formed. (That is, they should not contain invalid characters,
they should follow the file system's path format, etc.) The result
of calling a function on an ill-formed path is undefined. When there
is a chance that a path or a file name is invalid (for instance, when it
has been input by the user), it may sometimes be desirable to use the
isValidFilename and isValidPath functions to check
this.
Most functions do not perform any memory allocations, and if a string is
returned, it is usually a slice of an input string. If a function
allocates, this is explicitly mentioned in the documentation.
Category Functions Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension Other filenameCharCmp filenameCmp globMatch CaseSensitive
Source
std/path.d
path : (alias template) buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))Combines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by $(LREF isAbsolute)), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. $(D `\foo`)), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if `paths` is a forward
range.
Params:
segments = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
of segments to assemble the path from.
Returns: The assembled path.
buildPath;
(struct) sparkles.test_runner.driver.DriverOutcomeThe outcome of one driver run.
DriverOutcome (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
(local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome.(field) ulong sparkles.test_runner.driver.DriverOutcome.testCounttestCount = (parameter) sparkles.test_runner.model.Test[] betterCTestsbetterCTests.(field) ulong sparkles.test_runner.model.Test[].lengthlength;
if (!(parameter) sparkles.test_runner.model.Test[] betterCTestsbetterCTests.(field) ulong sparkles.test_runner.model.Test[].lengthlength)
{
void sparkles.test_runner.driver.say!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safeargs and a line feed, to report's output.
say((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "no @betterC tests found");
return (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
}
const (local variable) const(string) compilercompiler = string sparkles.test_runner.driver.detectCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report = ModeReport(null, null)) @safeThe D compiler to use: explicit choice, $DC, or the first of
ldc2/dmd found in $PATH (empty string when none). An explicit choice
that doesn't resolve is reported to report and treated as "no compiler", so
the caller's toolchain-missing skip fires instead of a raw
ProcessException escaping from the spawn.
detectCompiler((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) string sparkles.test_runner.driver.DriverOptions.compilerexplicit D compiler; empty = $DC, then ldc2, dmd
compiler, (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.reportwhere the modes' messages go
report);
if (!(local variable) const(string) compilercompiler.(field) ulong const(string).lengthlength)
{
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safeargs and a line feed, to report's diagnostics.
warn((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "skipping @betterC tests: no D compiler found (set $DC or --compiler)");
(local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome.(field) bool sparkles.test_runner.driver.DriverOutcome.skippedmissing toolchain — reported but not a failure
skipped = true;
return (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
}
const (local variable) const(string) workDirworkDir = string sparkles.test_runner.driver.makeWorkDir(string flavor, string own = null)A fresh scratch directory for the generated program: beneath own, the
run's DriverOptions.probeDir, when it names one, so clients that run
several modes at once in one process keep them apart; else beneath
setProbeDir's.
makeWorkDir("betterc", (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) string sparkles.test_runner.driver.DriverOptions.probeDirwhere generated programs go; empty = the temp directory
probeDir);
const (local variable) const(string) sourceFilesourceFile = string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath((local variable) const(string) workDirworkDir, "betterc_tests.d");
const (local variable) const(string) binarybinary = string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath((local variable) const(string) workDirworkDir, "betterc_tests");
void std.file.write!string(string name, const(void[]) buffer) @safeWrite buffer to file name.
Creates the file if it does not already exist.
Examples
scope(exit)
{
assert(exists(deleteme));
remove(deleteme);
}
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write(deleteme, a); // deleteme is the name of a temporary file
const bytes = read(deleteme);
const fileInts = () @trusted { return cast(int[]) bytes; }();
assert(fileInts == a);
write((local variable) const(string) sourceFilesourceFile, string sparkles.test_runner.extract.generateBetterCProgram(in sparkles.test_runner.extract.ExtractedTest[] tests) pure @safeA complete standalone -betterC program running the given tests: the
extracted functions plus an extern(C) main announcing each test before
running it (so an assert abort is attributable).
generateBetterCProgram(sparkles.test_runner.extract.ExtractedTest[] sparkles.test_runner.driver.extractTests(in sparkles.test_runner.model.Test[] tests)Slices the bodies of tests out of their source files. Files are read
relative to the working directory — the same place the compiler resolved
them from when the test build was created.
extractTests((parameter) sparkles.test_runner.model.Test[] betterCTestsbetterCTests)));
const (local variable) const(string[]) importFlagsimportFlags = string[] sparkles.test_runner.driver.allImportFlags(in sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options)The compile context's flags: -I for the derived source roots, the
harness roots, dub described dependency paths unless noDub, and the
user's extras, then the string import paths, versions and flags
(process-model TRX1–TRX4).
allImportFlags((parameter) sparkles.test_runner.model.Test[] allTestsallTests, (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions);
// Each test's own module is compiled in by default (see
// `autoIncludeFlags`), so a test can call its module's ordinary functions
// and not just its templates. Anything beyond that — a sibling module, or
// a std module such as `--include-import=std.ascii` — is opt-in, and every
// module compiled in must be betterC-codegen-clean.
// `-checkaction=C` states the assert action the tests are written against
// rather than inheriting it: a failed `assert` goes to the C library's,
// which prints the message and aborts. `-betterC` already implies this
// (verified: identical output with and without the flag), but the helpers
// in `sparkles.base.buffer` reach for `assert(false, msg)` precisely
// *because* `throw` is illegal here, so the pairing should be visible at
// the compile site instead of resting on another switch's default.
const (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compilecompile = std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safeRuns command, echoing it when verbose, and returns (status, output).
A spawn failure (compiler binary vanished between the detectCompiler
check and here, or an unlaunchable absolute path) becomes a failed result
instead of a ProcessException stack trace.
run(
[(local variable) const(string) compilercompiler, "-betterC", "-checkaction=C", "-of=" ~ (local variable) const(string) binarybinary]
~ string[] sparkles.test_runner.driver.autoIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safeThe -i=<module> flags derived from the tests being extracted: one per
distinct module that owns a test, minus the ones whose tests all opted out
with selfContained.
Compiling the owning module in is the useful default. Without it an
extracted program links against nothing but templates, so a @betterC
test that calls any ordinary function of the very module it lives in —
the common case — fails at link time with an undefined reference, which
made the marker attribute effectively decorative for such tests.
The opt-out is per test (@betterC(selfContained: true)) rather than
global because it is a property of the test: a module that is not itself
-betterC-codegen-clean can still host a template-only test, and that
self-containment is exactly what such a test asserts. --no-auto-include
disables the whole derivation for a one-off run.
autoIncludeFlags((parameter) sparkles.test_runner.model.Test[] betterCTestsbetterCTests, (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions) ~ string[] sparkles.test_runner.driver.includeFlags(in sparkles.test_runner.driver.DriverOptions options) pure @safeThe extra -i=<pattern> flags requested with --include-import (e.g.
--include-import=std.ascii to compile a std module in when an extracted
test needs one of its non-template functions).
includeFlags((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions)
~ (local variable) const(string[]) importFlagsimportFlags ~ [(local variable) const(string) sourceFilesourceFile],
(parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions);
if ((local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compilecompile.status != 0)
{
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safeargs and a line feed, to report's diagnostics.
warn((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compilecompile.(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1output);
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safeargs and a line feed, to report's diagnostics.
warn((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "failed to compile the extracted @betterC tests (see above)");
(local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome.(field) bool sparkles.test_runner.driver.DriverOutcome.succeededsucceeded = false;
return (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
}
const (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult = std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safeRuns command, echoing it when verbose, and returns (status, output).
A spawn failure (compiler binary vanished between the detectCompiler
check and here, or an unlaunchable absolute path) becomes a failed result
instead of a ProcessException stack trace.
run([(local variable) const(string) binarybinary], (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions);
void sparkles.test_runner.driver.sayRaw(in sparkles.test_runner.driver.DriverOptions options, string text)text, as it is, to report's output.
sayRaw((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult.(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1output);
(local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome.(field) bool sparkles.test_runner.driver.DriverOutcome.succeededsucceeded = (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult.status == 0;
if ((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) bool sparkles.test_runner.driver.DriverOptions.keepkeep the generated files and print their location
keep)
void sparkles.test_runner.driver.say!(string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2) @safeargs and a line feed, to report's output.
say((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "generated files kept in ", (local variable) const(string) workDirworkDir);
return (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
}
// ─────────────────────────────────────────────────────────────────────────────
// --wasm
// ─────────────────────────────────────────────────────────────────────────────
/// The WASI target of `--wasm` (docs/specs/test-runner/SPEC.md, `@wasm`).
enum (constant) string sparkles.test_runner.driver.wasiTriple = "wasm32-unknown-wasip1"The WASI target of --wasm (docs/specs/test-runner/SPEC.md, @wasm).
wasiTriple = "wasm32-unknown-wasip1";
/// The variable naming an LDC that has the WASI runtime, when `$DC` does not.
enum (constant) string sparkles.test_runner.driver.wasiCompilerVariable = "SPARKLES_WASI_LDC"The variable naming an LDC that has the WASI runtime, when $DC does not.
wasiCompilerVariable = "SPARKLES_WASI_LDC";
/++
The compiler for `--wasm`: `--compiler`, then `$SPARKLES_WASI_LDC`, then the
usual choice (`$DC`, `ldc2`); empty when none resolves.
+/
private (alias) object.string = stringstring string sparkles.test_runner.driver.wasiCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report) @safeThe compiler for --wasm: --compiler, then $SPARKLES_WASI_LDC, then the
usual choice ($DC, ldc2); empty when none resolves.
wasiCompiler((alias) object.string = stringstring (parameter) string preferredpreferred, in (struct) sparkles.test_runner.driver.ModeReportWhere the modes' messages go. The core prints nothing (process-model
TRM1): its client renders these, to a terminal or as task output.
ModeReport (parameter) const(sparkles.test_runner.driver.ModeReport) reportreport) @safe
{
import (package) stdstd.(module) std.processFunctions for starting and interacting with other processes, and for
working with the current process' execution environment.
Process handling
`spawnProcess` spawns a new `process`, optionally assigning it an
arbitrary set of standard input, output, and error streams.
The function returns immediately, leaving the child process to execute
in parallel with its parent. All other functions in this module that
spawn processes are built around spawnProcess.
`wait` makes the parent `process` wait for a child `process` to
terminate. In general one should always do this, to avoid
child processes becoming "zombies" when the parent process exits.
Scope guards are perfect for this – see the spawnProcess
documentation for examples. tryWait is similar to wait,
but does not block if the process has not yet terminated.
`pipeProcess` also spawns a child `process` which runs
in parallel with its parent. However, instead of taking
arbitrary streams, it automatically creates a set of
pipes that allow the parent to communicate with the child
through the child's standard input, output, and/or error streams.
This function corresponds roughly to C's popen function.
`execute` starts a new `process` and waits for it
to complete before returning. Additionally, it captures
the process' standard output and error streams and returns
the output of these as a string.
`spawnShell`, `pipeShell` and `executeShell` work like
spawnProcess, pipeProcess and execute, respectively,
except that they take a single command string and run it through
the current user's default command interpreter.
executeShell corresponds roughly to C's system function.
`kill` attempts to terminate a running `process`.
The following table compactly summarises the different process creation
functions and how they relate to each other:
Runs program directly
Runs shell command Low-level process creation spawnProcess spawnShell Automatic input/output redirection using pipes pipeProcess pipeShell Execute and wait for completion, collect output execute executeShell
Other functionality
`pipe` is used to create unidirectional pipes.
`environment` is an interface through which the current `process`'
environment variables can be read and manipulated.
`escapeShellCommand` and `escapeShellFileName` are useful
for constructing shell command lines in a portable way.
Source
std/process.d
Note
Most of the functionality in this module is not available on iOS, tvOS
and watchOS. The only functions available on those platforms are:
environment, thisProcessID and thisThreadID.
process : (class) std.process.environmentManipulates environment variables using an associative-array-like
interface.
This class contains only static methods, and cannot be instantiated.
See below for examples of use.
environment;
if (!(parameter) string preferredpreferred.(field) ulong string.lengthlength)
if (const (local variable) const(string) wasiwasi = (class) std.process.environmentManipulates environment variables using an associative-array-like
interface.
This class contains only static methods, and cannot be instantiated.
See below for examples of use.
environment.string std.process.environment.get(scope const(char)[] name, string defaultValue = null) @safeRetrieves the value of the environment variable with the given name,
or a default value if the variable doesn't exist.
Unlike environment.opIndex, this function never throws on Posix.
auto sh = environment.get("SHELL", "/bin/sh");
This function is also useful in checking for the existence of an
environment variable.
auto myVar = environment.get("MYVAR");
if (myVar is null)
{
// Environment variable doesn't exist.
// Note that we have to use 'is' for the comparison, since
// myVar == null is also true if the variable exists but is
// empty.
}
get((constant) string sparkles.test_runner.driver.wasiCompilerVariable = "SPARKLES_WASI_LDC"The variable naming an LDC that has the WASI runtime, when $DC does not.
wasiCompilerVariable, null))
return string sparkles.test_runner.driver.detectCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report = ModeReport(null, null)) @safeThe D compiler to use: explicit choice, $DC, or the first of
ldc2/dmd found in $PATH (empty string when none). An explicit choice
that doesn't resolve is reported to report and treated as "no compiler", so
the caller's toolchain-missing skip fires instead of a raw
ProcessException escaping from the spawn.
detectCompiler((local variable) const(string) wasiwasi, (parameter) const(sparkles.test_runner.driver.ModeReport) reportreport);
return string sparkles.test_runner.driver.detectCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report = ModeReport(null, null)) @safeThe D compiler to use: explicit choice, $DC, or the first of
ldc2/dmd found in $PATH (empty string when none). An explicit choice
that doesn't resolve is reported to report and treated as "no compiler", so
the caller's toolchain-missing skip fires instead of a raw
ProcessException escaping from the spawn.
detectCompiler((parameter) string preferredpreferred, (parameter) const(sparkles.test_runner.driver.ModeReport) reportreport);
}
/++
The `-i` flags of a `--wasm` program. With the full druntime and Phobos there
is no codegen restriction, so every module the tests import is compiled in
(`-i`, which leaves out druntime and Phobos), except the owning modules of
tests that are all `selfContained`. `--no-auto-include` compiles in nothing.
+/
(alias) object.string = stringstring[] string[] sparkles.test_runner.driver.wasiIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safeThe -i flags of a --wasm program. With the full druntime and Phobos there
is no codegen restriction, so every module the tests import is compiled in
(-i, which leaves out druntime and Phobos), except the owning modules of
tests that are all selfContained. --no-auto-include compiles in nothing.
wasiIncludeFlags(in (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test[] (parameter) const(sparkles.test_runner.model.Test[]) extractedextracted, in (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions) @safe pure
{
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.searchingThis is a submodule of std.algorithm.
It contains generic searching algorithms.
Function Name Description all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses. boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm. canFind canFind("hello world", "or") returns true. count Counts all elements or elements matching a predicate, specific element or sub-range.
count([1, 2, 1]) returns 3,
count([1, 2, 1], 1) returns 2 and
count!"a < 0"([1, -3, 0]) returns 1. |
| countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. |
| commonPrefix | commonPrefix("parakeet", "parachute") returns "para". |
| endsWith | endsWith("rocks", "ks") returns true. |
| extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. |
| find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) |
| findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. |
| findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". |
| findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. |
| findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". |
| findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". |
| findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". |
| minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). |
| maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). |
| minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. |
| maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. |
| minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. |
| maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. |
| minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. |
| maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. |
| skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. |
| startsWith | startsWith("hello, world", "hello") returns true. |
| until | Lazily iterates a range until a specific value is found. |
Source
std/algorithm/searching.d
searching : (alias template) all = std.algorithm.searching.all(alias pred = "a")Checks if $(I _all) of the elements satisfy pred.
all, (alias template) canFind = std.algorithm.searching.canFind(alias pred = "a == b")Convenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see $(LREF find).
See_Also:
$(REF among, std,algorithm,comparison) for checking a value against multiple arguments.
canFind;
if ((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) bool sparkles.test_runner.driver.DriverOptions.noAutoIncludedon't compile the extracted tests' own modules in
noAutoInclude)
return null;
(alias) object.string = stringstring[] (local variable) string[] flagsflags = ["-i"];
foreach (ref (parameter) const(sparkles.test_runner.model.Test) testtest; (parameter) const(sparkles.test_runner.model.Test[]) extractedextracted)
{
const (local variable) const(string) namename = string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safeThe actual module containing test: ``test.moduleName with aggregate
qualifiers stripped (a nested test's fullName includes its aggregate),
found by peeling trailing components until the name matches the file path.
probeModuleName((local variable) const(sparkles.test_runner.model.Test) testtest);
const (local variable) const(string) excludeexclude = "-i=-" ~ (local variable) const(string) namename;
if (!(local variable) string[] flagsflags.bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind((local variable) const(string) excludeexclude)
&& (parameter) const(sparkles.test_runner.model.Test[]) extractedextracted.bool sparkles.test_runner.driver.wasiIncludeFlags.all!(const(sparkles.test_runner.model.Test)[])(const(sparkles.test_runner.model.Test)[] range) pure nothrow @safeChecks if all of the elements satisfy pred.
Returns true if and only if the input range range is empty
or all values found in range satisfy the predicate pred.
Performs (at most) O(range.length) evaluations of pred.
Examples
assert( all!"a & 1"([1, 3, 5, 7, 9]));
assert(!all!"a & 1"([1, 2, 3, 5, 7, 9]));
all can also be used without a predicate, if its items can be
evaluated to true or false in a conditional statement. This can be a
convenient way to quickly evaluate that all of the elements of a range
are true.
int[3] vals = [5, 3, 18];
assert( all(vals[]));
all!(t => probeModuleName(t) != name || t.traits.selfContained))
(local variable) string[] flagsflags ~= (local variable) const(string) excludeexclude;
}
return (local variable) string[] flagsflags;
}
@("driver.wasiIncludeFlags.everythingButSelfContainedModules")
@safe pure
unittest
{
static (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L808_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safeat((alias) object.string = stringstring (parameter) string fullNamefullName, bool (parameter) bool selfContainedselfContained = false)
{
(struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test (local variable) sparkles.test_runner.model.Test tt;
(local variable) sparkles.test_runner.model.Test tt.(field) string sparkles.test_runner.model.Test.fullNameFully qualified name of the unittest symbol,
e.g. sparkles.base.buffer.__unittest_L42_C1.
fullName = (parameter) string fullNamefullName;
(local variable) sparkles.test_runner.model.Test tt.(field) sparkles.test_runner.model.TestTraits sparkles.test_runner.model.Test.traitstraits.(field) bool sparkles.test_runner.model.TestTraits.selfContainedThe test asserts it needs nothing linked from its own module, so the
extracted --better-c / --wasm program leaves that module out
(see betterC.selfContained``). One flag covers both modes: a test
marked self-contained under either is self-contained under both.
selfContained = (parameter) bool selfContainedselfContained;
return (local variable) sparkles.test_runner.model.Test tt;
}
assert(string[] sparkles.test_runner.driver.wasiIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safeThe -i flags of a --wasm program. With the full druntime and Phobos there
is no codegen restriction, so every module the tests import is compiled in
(-i, which leaves out druntime and Phobos), except the owning modules of
tests that are all selfContained. --no-auto-include compiles in nothing.
wasiIncludeFlags([sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L808_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safeat("pkg.a.__unittest_L1_C1")], (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions.(constant) sparkles.test_runner.driver.DriverOptions sparkles.test_runner.driver.DriverOptions.init = DriverOptions(null, null, null, false, false, false, ModeReport(null, null), null, null, null, null, false, null)init) == ["-i"]);
assert(string[] sparkles.test_runner.driver.wasiIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safeThe -i flags of a --wasm program. With the full druntime and Phobos there
is no codegen restriction, so every module the tests import is compiled in
(-i, which leaves out druntime and Phobos), except the owning modules of
tests that are all selfContained. --no-auto-include compiles in nothing.
wasiIncludeFlags([
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L808_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safeat("pkg.a.__unittest_L1_C1", true),
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L808_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safeat("pkg.b.__unittest_L2_C1", true),
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L808_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safeat("pkg.b.__unittest_L3_C1"),
], (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions.(constant) sparkles.test_runner.driver.DriverOptions sparkles.test_runner.driver.DriverOptions.init = DriverOptions(null, null, null, false, false, false, ModeReport(null, null), null, null, null, null, false, null)init) == ["-i", "-i=-pkg.a"]);
assert(string[] sparkles.test_runner.driver.wasiIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safeThe -i flags of a --wasm program. With the full druntime and Phobos there
is no codegen restriction, so every module the tests import is compiled in
(-i, which leaves out druntime and Phobos), except the owning modules of
tests that are all selfContained. --no-auto-include compiles in nothing.
wasiIncludeFlags([sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L808_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safeat("pkg.a.__unittest_L1_C1")],
(struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions(noAutoInclude: true)) is null);
}
/// Extracts the `@wasm` tests, compiles them for `wasm32-unknown-wasip1` with
/// the full druntime and Phobos of an LDC that has the WASI runtime (linked
/// through that runtime's compiler driver, so no `wasm-ld` is needed), and
/// runs the program under `wasmtime`. A missing runtime or `wasmtime` skips,
/// naming what is missing.
(struct) sparkles.test_runner.driver.DriverOutcomeThe outcome of one driver run.
DriverOutcome sparkles.test_runner.driver.DriverOutcome sparkles.test_runner.driver.runWasmTests(sparkles.test_runner.model.Test[] wasmTests, sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options)Extracts the @wasm tests, compiles them for wasm32-unknown-wasip1 with
the full druntime and Phobos of an LDC that has the WASI runtime (linked
through that runtime's compiler driver, so no wasm-ld is needed), and
runs the program under wasmtime. A missing runtime or wasmtime skips,
naming what is missing.
runWasmTests((struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test[] (parameter) sparkles.test_runner.model.Test[] wasmTestswasmTests, (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test[] (parameter) sparkles.test_runner.model.Test[] allTestsallTests, in (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions)
{
import (package) stdstd.(module) std.fileUtilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one file
at a time. For opening files and manipulating them via handles refer
to module std.stdio.
Category Functions General exists isDir isFile isSymlink rename thisExePath Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir Files append copy read readText remove slurp write Symlinks symlink readLink Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace
Source
std/file.d
file : (alias template) write = std.file.write(R)(R name, const void[] buffer) if ((isSomeFiniteCharInputRange!R || isSomeString!R) && !isConvertibleToString!R)Write buffer to file name.
Creates the file if it does not already exist.
Params:
name = string or range of characters representing the file _name
buffer = data to be written to file
Throws: $(LREF FileException) on error.
See_also: $(REF toFile, std,stdio)
write;
import (package) stdstd.(module) std.pathThis module is used to manipulate path strings.
All functions, with the exception of expandTilde (and in some
cases absolutePath and relativePath), are pure
string manipulation functions; they don't depend on any state outside
the program, nor do they perform any actual file system actions.
This has the consequence that the module does not make any distinction
between a path that points to a directory and a path that points to a
file, and it does not know whether or not the object pointed to by the
path actually exists in the file system.
To differentiate between these cases, use isDir and
exists.
Note that on Windows, both the backslash (\) and the slash (/)
are in principle valid directory separators. This module treats them
both on equal footing, but in cases where a new separator is
added, a backslash will be used. Furthermore, the buildNormalizedPath
function will replace all slashes with backslashes on that platform.
In general, the functions in this module assume that the input paths
are well-formed. (That is, they should not contain invalid characters,
they should follow the file system's path format, etc.) The result
of calling a function on an ill-formed path is undefined. When there
is a chance that a path or a file name is invalid (for instance, when it
has been input by the user), it may sometimes be desirable to use the
isValidFilename and isValidPath functions to check
this.
Most functions do not perform any memory allocations, and if a string is
returned, it is usually a slice of an input string. If a function
allocates, this is explicitly mentioned in the documentation.
Category Functions Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension Other filenameCharCmp filenameCmp globMatch CaseSensitive
Source
std/path.d
path : (alias template) buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))Combines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by $(LREF isAbsolute)), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. $(D `\foo`)), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if `paths` is a forward
range.
Params:
segments = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
of segments to assemble the path from.
Returns: The assembled path.
buildPath;
(struct) sparkles.test_runner.driver.DriverOutcomeThe outcome of one driver run.
DriverOutcome (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
(local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome.(field) ulong sparkles.test_runner.driver.DriverOutcome.testCounttestCount = (parameter) sparkles.test_runner.model.Test[] wasmTestswasmTests.(field) ulong sparkles.test_runner.model.Test[].lengthlength;
if (!(parameter) sparkles.test_runner.model.Test[] wasmTestswasmTests.(field) ulong sparkles.test_runner.model.Test[].lengthlength)
{
void sparkles.test_runner.driver.say!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safeargs and a line feed, to report's output.
say((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "no @wasm tests found");
return (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
}
const (local variable) const(string) compilercompiler = string sparkles.test_runner.driver.wasiCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report) @safeThe compiler for --wasm: --compiler, then $SPARKLES_WASI_LDC, then the
usual choice ($DC, ldc2); empty when none resolves.
wasiCompiler((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) string sparkles.test_runner.driver.DriverOptions.compilerexplicit D compiler; empty = $DC, then ldc2, dmd
compiler, (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.reportwhere the modes' messages go
report);
if (!(local variable) const(string) compilercompiler.(field) ulong const(string).lengthlength)
{
void sparkles.test_runner.driver.warn!(string, string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2, string __param_3) @safeargs and a line feed, to report's diagnostics.
warn((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "skipping @wasm tests: no D compiler found (set $", (constant) string sparkles.test_runner.driver.wasiCompilerVariable = "SPARKLES_WASI_LDC"The variable naming an LDC that has the WASI runtime, when $DC does not.
wasiCompilerVariable,
", --compiler or $DC)");
(local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome.(field) bool sparkles.test_runner.driver.DriverOutcome.skippedmissing toolchain — reported but not a failure
skipped = true;
return (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
}
if (!bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safeWhether an executable is reachable through searchPath ($PATH by
default). On Windows the file is ``name.exe, as CreateProcess finds it:
$DC=ldc2 names ldc2.exe there.
A local re-implementation rather than sparkles.core_cli.process_utils.isInPath:
this module is source-compiled into base's test build, which has no
core-cli dependency (the impl-library cycle is impl → base).
inPath("wasmtime"))
{
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safeargs and a line feed, to report's diagnostics.
warn((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "skipping @wasm tests: wasmtime not found on PATH");
(local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome.(field) bool sparkles.test_runner.driver.DriverOutcome.skippedmissing toolchain — reported but not a failure
skipped = true;
return (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
}
const (local variable) const(string) workDirworkDir = string sparkles.test_runner.driver.makeWorkDir(string flavor, string own = null)A fresh scratch directory for the generated program: beneath own, the
run's DriverOptions.probeDir, when it names one, so clients that run
several modes at once in one process keep them apart; else beneath
setProbeDir's.
makeWorkDir("wasi", (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) string sparkles.test_runner.driver.DriverOptions.probeDirwhere generated programs go; empty = the temp directory
probeDir);
// A compiler without the WASI runtime fails this, not the tests.
const (local variable) const(string) probeSourceprobeSource = string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath((local variable) const(string) workDirworkDir, "probe.d");
void std.file.write!string(string name, const(void[]) buffer) @safeWrite buffer to file name.
Creates the file if it does not already exist.
Examples
scope(exit)
{
assert(exists(deleteme));
remove(deleteme);
}
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write(deleteme, a); // deleteme is the name of a temporary file
const bytes = read(deleteme);
const fileInts = () @trusted { return cast(int[]) bytes; }();
assert(fileInts == a);
write((local variable) const(string) probeSourceprobeSource, "void main() {}\n");
const (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) probeprobe = std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safeRuns command, echoing it when verbose, and returns (status, output).
A spawn failure (compiler binary vanished between the detectCompiler
check and here, or an unlaunchable absolute path) becomes a failed result
instead of a ProcessException stack trace.
run([(local variable) const(string) compilercompiler, "-mtriple=" ~ (constant) string sparkles.test_runner.driver.wasiTriple = "wasm32-unknown-wasip1"The WASI target of --wasm (docs/specs/test-runner/SPEC.md, @wasm).
wasiTriple, "-of=" ~ string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath((local variable) const(string) workDirworkDir, "probe.wasm"),
(local variable) const(string) probeSourceprobeSource], (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions);
if ((local variable) const(std.typecons.Tuple!(int, "status", string, "output")) probeprobe.status != 0)
{
void sparkles.test_runner.driver.warn!(string, string, string, string, string, string, string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2, string __param_3, string __param_4, string __param_5, string __param_6, string __param_7, string __param_8) @safeargs and a line feed, to report's diagnostics.
warn((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "skipping @wasm tests: ", (local variable) const(string) compilercompiler, " cannot link a ", (constant) string sparkles.test_runner.driver.wasiTriple = "wasm32-unknown-wasip1"The WASI target of --wasm (docs/specs/test-runner/SPEC.md, @wasm).
wasiTriple,
" program (no WASI runtime; set $", (constant) string sparkles.test_runner.driver.wasiCompilerVariable = "SPARKLES_WASI_LDC"The variable naming an LDC that has the WASI runtime, when $DC does not.
wasiCompilerVariable, "):\n", (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) probeprobe.(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1output);
(local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome.(field) bool sparkles.test_runner.driver.DriverOutcome.skippedmissing toolchain — reported but not a failure
skipped = true;
return (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
}
const (local variable) const(string) sourceFilesourceFile = string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath((local variable) const(string) workDirworkDir, "wasm_tests.d");
const (local variable) const(string) wasmFilewasmFile = string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath((local variable) const(string) workDirworkDir, "wasm_tests.wasm");
void std.file.write!string(string name, const(void[]) buffer) @safeWrite buffer to file name.
Creates the file if it does not already exist.
Examples
scope(exit)
{
assert(exists(deleteme));
remove(deleteme);
}
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write(deleteme, a); // deleteme is the name of a temporary file
const bytes = read(deleteme);
const fileInts = () @trusted { return cast(int[]) bytes; }();
assert(fileInts == a);
write((local variable) const(string) sourceFilesourceFile, string sparkles.test_runner.extract.generateWasiProgram(in sparkles.test_runner.extract.ExtractedTest[] tests) pure @safeA complete WASI program running the given tests (--wasm): the extracted
functions plus a main that announces and runs each one, catching what it
throws, so one failing test does not hide the rest. The full druntime is
there, so a failed assert is an AssertError like any other Throwable.
The exit status is 1 when any test failed.
generateWasiProgram(sparkles.test_runner.extract.ExtractedTest[] sparkles.test_runner.driver.extractTests(in sparkles.test_runner.model.Test[] tests)Slices the bodies of tests out of their source files. Files are read
relative to the working directory — the same place the compiler resolved
them from when the test build was created.
extractTests((parameter) sparkles.test_runner.model.Test[] wasmTestswasmTests)));
const (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compilecompile = std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safeRuns command, echoing it when verbose, and returns (status, output).
A spawn failure (compiler binary vanished between the detectCompiler
check and here, or an unlaunchable absolute path) becomes a failed result
instead of a ProcessException stack trace.
run(
[(local variable) const(string) compilercompiler, "-mtriple=" ~ (constant) string sparkles.test_runner.driver.wasiTriple = "wasm32-unknown-wasip1"The WASI target of --wasm (docs/specs/test-runner/SPEC.md, @wasm).
wasiTriple, "-of=" ~ (local variable) const(string) wasmFilewasmFile]
~ string[] sparkles.test_runner.driver.wasiIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safeThe -i flags of a --wasm program. With the full druntime and Phobos there
is no codegen restriction, so every module the tests import is compiled in
(-i, which leaves out druntime and Phobos), except the owning modules of
tests that are all selfContained. --no-auto-include compiles in nothing.
wasiIncludeFlags((parameter) sparkles.test_runner.model.Test[] wasmTestswasmTests, (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions) ~ string[] sparkles.test_runner.driver.includeFlags(in sparkles.test_runner.driver.DriverOptions options) pure @safeThe extra -i=<pattern> flags requested with --include-import (e.g.
--include-import=std.ascii to compile a std module in when an extracted
test needs one of its non-template functions).
includeFlags((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions)
~ ((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) bool sparkles.test_runner.driver.DriverOptions.noDubnever run dub describe (process-model TRX2)
noDub ? null : string[] sparkles.test_runner.driver.dubDescribeLanguageFlags(in string[] sourceRoots, in sparkles.test_runner.driver.DriverOptions options)The language-semantics switches (-preview=, -revert=, -transition=) that
dub describe reports for the packages containing the derived source roots.
A program compiled outside dub needs them to see the packages' code the way
their own builds do (-preview=dip1000 changes attribute inference).
Best-effort: failures yield an empty list.
dubDescribeLanguageFlags(
string[] sparkles.test_runner.driver.deriveImportPaths(in sparkles.test_runner.model.Test[] allTests, in string[] extra) pure @safe-I roots derived from every discovered test's module-name ↔ file-path
pair, after the extras: the user's, then the harness roots the binary
reported. Never the runner's own root: the pinned runner's copy of the
attributes is not the one the tested package was compiled against
(process-model TRX4).
deriveImportPaths((parameter) sparkles.test_runner.model.Test[] wasmTestswasmTests, (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) string[] sparkles.test_runner.driver.DriverOptions.importPathsextra -I paths
importPaths), (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions))
~ string[] sparkles.test_runner.driver.allImportFlags(in sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options)The compile context's flags: -I for the derived source roots, the
harness roots, dub described dependency paths unless noDub, and the
user's extras, then the string import paths, versions and flags
(process-model TRX1–TRX4).
allImportFlags((parameter) sparkles.test_runner.model.Test[] allTestsallTests, (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions) ~ [(local variable) const(string) sourceFilesourceFile],
(parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions);
if ((local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compilecompile.status != 0)
{
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safeargs and a line feed, to report's diagnostics.
warn((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compilecompile.(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1output);
void sparkles.test_runner.driver.warn!(string, string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2, string __param_3) @safeargs and a line feed, to report's diagnostics.
warn((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "failed to compile the extracted @wasm tests for ", (constant) string sparkles.test_runner.driver.wasiTriple = "wasm32-unknown-wasip1"The WASI target of --wasm (docs/specs/test-runner/SPEC.md, @wasm).
wasiTriple, " (see above)");
(local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome.(field) bool sparkles.test_runner.driver.DriverOutcome.succeededsucceeded = false;
return (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
}
const (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult = std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safeRuns command, echoing it when verbose, and returns (status, output).
A spawn failure (compiler binary vanished between the detectCompiler
check and here, or an unlaunchable absolute path) becomes a failed result
instead of a ProcessException stack trace.
run(["wasmtime", "run", (local variable) const(string) wasmFilewasmFile], (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions);
void sparkles.test_runner.driver.sayRaw(in sparkles.test_runner.driver.DriverOptions options, string text)text, as it is, to report's output.
sayRaw((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult.(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1output);
(local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome.(field) bool sparkles.test_runner.driver.DriverOutcome.succeededsucceeded = (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult.status == 0;
if ((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) bool sparkles.test_runner.driver.DriverOptions.keepkeep the generated files and print their location
keep)
void sparkles.test_runner.driver.say!(string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2) @safeargs and a line feed, to report's output.
say((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "generated files kept in ", (local variable) const(string) workDirworkDir);
return (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
}
// ─────────────────────────────────────────────────────────────────────────────
// --wasm-bare
// ─────────────────────────────────────────────────────────────────────────────
/// Extracts the `@wasm` tests, cross-compiles them to bare `wasm32` with
/// `-betterC` and LDC's internal linker, and runs them with the first
/// available WebAssembly-capable runtime (`node`, `deno`, `bun`, or
/// `wasmtime`).
(struct) sparkles.test_runner.driver.DriverOutcomeThe outcome of one driver run.
DriverOutcome sparkles.test_runner.driver.DriverOutcome sparkles.test_runner.driver.runWasmBareTests(sparkles.test_runner.model.Test[] wasmTests, sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options)Extracts the @wasm tests, cross-compiles them to bare wasm32 with
-betterC and LDC's internal linker, and runs them with the first
available WebAssembly-capable runtime (node, deno, bun, or
wasmtime).
runWasmBareTests((struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test[] (parameter) sparkles.test_runner.model.Test[] wasmTestswasmTests, (struct) sparkles.test_runner.model.TestOne discovered unittest block.
Test[] (parameter) sparkles.test_runner.model.Test[] allTestsallTests, in (struct) sparkles.test_runner.driver.DriverOptionsOptions shared by both driver modes.
DriverOptions (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions)
{
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.iterationThis is a submodule of std.algorithm.
It contains generic iteration algorithms.
Function Name Description cache Eagerly evaluates and caches another range's front. lazyCache Lazily evaluates and caches another range's front, unlike cache. cacheBidirectional As above, but also provides back and popBack. chunkBy chunkBy!((a,b) => a[1] == b[1])([[1, 1], [1, 2], [2, 2], [2, 1]]) returns a range containing 3 subranges: the first with just [1, 1]; the second with the elements [1, 2] and [2, 2]; and the third with just [2, 1]. cumulativeFold cumulativeFold!((a, b) => a + b)([1, 2, 3, 4]) returns a lazily-evaluated range containing the successive reduced values 1, 3, 6, 10. each each!writeln([1, 2, 3]) eagerly prints the numbers 1, 2 and 3 on their own lines. filter filter!(a => a > 0)([1, -1, 2, 0, -3]) iterates over elements 1 and 2. filterBidirectional Similar to filter, but also provides back and popBack at a small increase in cost. fold fold!((a, b) => a + b)([1, 2, 3, 4]) returns 10. group group([5, 2, 2, 3, 3]) returns a range containing the tuples tuple(5, 1), tuple(2, 2), and tuple(3, 2). joiner joiner(["hello", "world!"], "; ") returns a range that iterates over the characters "hello; world!". No new string is created - the existing inputs are iterated. map map!(a => a * 2)([1, 2, 3]) lazily returns a range with the numbers 2, 4, 6. mean Colloquially known as the average, mean([1, 2, 3]) returns 2. permutations Lazily computes all permutations using Heap's algorithm. reduce reduce!((a, b) => a + b)([1, 2, 3, 4]) returns 10. This is the old implementation of fold. splitWhen Lazily splits a range by comparing adjacent elements. splitter Lazily splits a range by a separator, element predicate or whitespace. substitute [1, 2].substitute(1, 0.1) returns [0.1, 2]. sum Same as fold, but specialized for accurate summation. uniq Iterates over the unique elements in a range, which is assumed sorted.
Source
std/algorithm/iteration.d
iteration : (alias template) map = std.algorithm.iteration.map(fun...) if (fun.length >= 1)Implements the homonym function (also known as transform) present
in many languages of functional flavor. The call map!(fun)(range)
returns a range of which elements are obtained by applying fun(a)
left to right for all elements a in range. The original ranges are
not changed. Evaluation is done lazily.
Params:
fun = one or more transformation functions
See_Also:
$(HTTP en.wikipedia.org/wiki/Map_(higher-order_function), Map (higher-order function))
map;
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.searchingThis is a submodule of std.algorithm.
It contains generic searching algorithms.
Function Name Description all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses. boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm. canFind canFind("hello world", "or") returns true. count Counts all elements or elements matching a predicate, specific element or sub-range.
count([1, 2, 1]) returns 3,
count([1, 2, 1], 1) returns 2 and
count!"a < 0"([1, -3, 0]) returns 1. |
| countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. |
| commonPrefix | commonPrefix("parakeet", "parachute") returns "para". |
| endsWith | endsWith("rocks", "ks") returns true. |
| extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. |
| find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) |
| findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. |
| findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". |
| findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. |
| findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". |
| findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". |
| findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". |
| minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). |
| maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). |
| minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. |
| maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. |
| minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. |
| maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. |
| minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. |
| maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. |
| skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. |
| startsWith | startsWith("hello, world", "hello") returns true. |
| until | Lazily iterates a range until a specific value is found. |
Source
std/algorithm/searching.d
searching : (alias template) canFind = std.algorithm.searching.canFind(alias pred = "a == b")Convenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see $(LREF find).
See_Also:
$(REF among, std,algorithm,comparison) for checking a value against multiple arguments.
canFind;
import (package) stdstd.(module) std.arrayFunctions and types that manipulate built-in arrays and associative arrays.
This module provides all kinds of functions to create, manipulate or convert arrays:
Function Name Description
| array |
Returns a copy of the input in a newly allocated dynamic array.
|
| appender |
Returns a new Appender or RefAppender initialized with a given array.
|
| assocArray |
Returns a newly allocated associative array from a range/ranges of keys and values.
|
| byPair |
Construct a range iterating over an associative array by key/value tuples.
|
| insertInPlace |
Inserts into an existing array at a given position.
|
| join |
Concatenates a range of ranges into one array.
|
| minimallyInitializedArray |
Returns a new array of type T.
|
| replace |
Returns a new array with all occurrences of a certain subrange replaced.
|
| replaceFirst |
Returns a new array with the first occurrence of a certain subrange replaced.
|
| replaceInPlace |
Replaces all occurrences of a certain subrange and puts the result into a given array.
|
| replaceInto |
Replaces all occurrences of a certain subrange and puts the result into an output range.
|
| replaceLast |
Returns a new array with the last occurrence of a certain subrange replaced.
|
| replaceSlice |
Returns a new array with a given slice replaced.
|
| replicate |
Creates a new array out of several copies of an input array or range.
|
| sameHead |
Checks if the initial segments of two arrays refer to the same
place in memory.
|
| sameTail |
Checks if the final segments of two arrays refer to the same place
in memory.
|
| split |
Eagerly split a range or string into an array.
|
| staticArray |
Creates a new static array from given data.
|
| uninitializedArray |
Returns a new array of type T without initializing its elements.
|
Source
std/array.d
array : (alias template) array = std.array.array(Range)(Range r) if (isIterable!Range && !isAutodecodableString!Range && !isInfinite!Range)Allocates an array and initializes it with copies of the elements
of range r.
Narrow strings are handled as follows:
If autodecoding is turned on (default), then they are handled as a separate overload.
If autodecoding is turned off, then this is equivalent to duplicating the array.
Params:
r = range (or aggregate with opApply function) whose elements are copied into the allocated array
Returns:
allocated and initialized array
array;
import (package) stdstd.(module) std.convA one-stop shop for converting values from one type to another.
Category Functions Generic asOriginalType castFrom parse to toChars bitCast Strings text wtext dtext writeText writeWText writeDText hexString Numeric octal roundTo signed unsigned Exceptions ConvException ConvOverflowException
Source
std/conv.d
conv : (alias template) text = std.conv.text(T...)(T args) if (T.length > 0)Convenience functions for converting one or more arguments
of any type into _text (the three character widths).
text;
import (package) stdstd.(module) std.fileUtilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one file
at a time. For opening files and manipulating them via handles refer
to module std.stdio.
Category Functions General exists isDir isFile isSymlink rename thisExePath Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir Files append copy read readText remove slurp write Symlinks symlink readLink Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace
Source
std/file.d
file : (alias template) write = std.file.write(R)(R name, const void[] buffer) if ((isSomeFiniteCharInputRange!R || isSomeString!R) && !isConvertibleToString!R)Write buffer to file name.
Creates the file if it does not already exist.
Params:
name = string or range of characters representing the file _name
buffer = data to be written to file
Throws: $(LREF FileException) on error.
See_also: $(REF toFile, std,stdio)
write;
import (package) stdstd.(module) std.pathThis module is used to manipulate path strings.
All functions, with the exception of expandTilde (and in some
cases absolutePath and relativePath), are pure
string manipulation functions; they don't depend on any state outside
the program, nor do they perform any actual file system actions.
This has the consequence that the module does not make any distinction
between a path that points to a directory and a path that points to a
file, and it does not know whether or not the object pointed to by the
path actually exists in the file system.
To differentiate between these cases, use isDir and
exists.
Note that on Windows, both the backslash (\) and the slash (/)
are in principle valid directory separators. This module treats them
both on equal footing, but in cases where a new separator is
added, a backslash will be used. Furthermore, the buildNormalizedPath
function will replace all slashes with backslashes on that platform.
In general, the functions in this module assume that the input paths
are well-formed. (That is, they should not contain invalid characters,
they should follow the file system's path format, etc.) The result
of calling a function on an ill-formed path is undefined. When there
is a chance that a path or a file name is invalid (for instance, when it
has been input by the user), it may sometimes be desirable to use the
isValidFilename and isValidPath functions to check
this.
Most functions do not perform any memory allocations, and if a string is
returned, it is usually a slice of an input string. If a function
allocates, this is explicitly mentioned in the documentation.
Category Functions Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension Other filenameCharCmp filenameCmp globMatch CaseSensitive
Source
std/path.d
path : (alias template) buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))Combines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by $(LREF isAbsolute)), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. $(D `\foo`)), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if `paths` is a forward
range.
Params:
segments = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
of segments to assemble the path from.
Returns: The assembled path.
buildPath;
(struct) sparkles.test_runner.driver.DriverOutcomeThe outcome of one driver run.
DriverOutcome (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
(local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome.(field) ulong sparkles.test_runner.driver.DriverOutcome.testCounttestCount = (parameter) sparkles.test_runner.model.Test[] wasmTestswasmTests.(field) ulong sparkles.test_runner.model.Test[].lengthlength;
if (!(parameter) sparkles.test_runner.model.Test[] wasmTestswasmTests.(field) ulong sparkles.test_runner.model.Test[].lengthlength)
{
void sparkles.test_runner.driver.say!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safeargs and a line feed, to report's output.
say((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "no @wasm tests found");
return (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
}
// llvm_trap + -mtriple make this LDC-specific.
const (local variable) const(string) compilercompiler = string sparkles.test_runner.driver.detectCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report = ModeReport(null, null)) @safeThe D compiler to use: explicit choice, $DC, or the first of
ldc2/dmd found in $PATH (empty string when none). An explicit choice
that doesn't resolve is reported to report and treated as "no compiler", so
the caller's toolchain-missing skip fires instead of a raw
ProcessException escaping from the spawn.
detectCompiler((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) string sparkles.test_runner.driver.DriverOptions.compilerexplicit D compiler; empty = $DC, then ldc2, dmd
compiler, (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.reportwhere the modes' messages go
report);
if (!(local variable) const(string) compilercompiler.bool std.algorithm.searching.canFind!().canFind!(string, string)(string haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind("ldc"))
{
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safeargs and a line feed, to report's diagnostics.
warn((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "skipping @wasm tests: an LDC compiler is required (set $DC or --compiler)");
(local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome.(field) bool sparkles.test_runner.driver.DriverOutcome.skippedmissing toolchain — reported but not a failure
skipped = true;
return (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
}
const (local variable) const(string) workDirworkDir = string sparkles.test_runner.driver.makeWorkDir(string flavor, string own = null)A fresh scratch directory for the generated program: beneath own, the
run's DriverOptions.probeDir, when it names one, so clients that run
several modes at once in one process keep them apart; else beneath
setProbeDir's.
makeWorkDir("wasm", (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) string sparkles.test_runner.driver.DriverOptions.probeDirwhere generated programs go; empty = the temp directory
probeDir);
const (local variable) const(string) sourceFilesourceFile = string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath((local variable) const(string) workDirworkDir, "wasm_tests.d");
const (local variable) const(string) wasmFilewasmFile = string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath((local variable) const(string) workDirworkDir, "wasm_tests.wasm");
const (local variable) const(string) shimFileshimFile = string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath((local variable) const(string) workDirworkDir, "wasm_tests.js");
const (local variable) const(sparkles.test_runner.extract.ExtractedTest[]) extractedextracted = sparkles.test_runner.extract.ExtractedTest[] sparkles.test_runner.driver.extractTests(in sparkles.test_runner.model.Test[] tests)Slices the bodies of tests out of their source files. Files are read
relative to the working directory — the same place the compiler resolved
them from when the test build was created.
extractTests((parameter) sparkles.test_runner.model.Test[] wasmTestswasmTests);
void std.file.write!string(string name, const(void[]) buffer) @safeWrite buffer to file name.
Creates the file if it does not already exist.
Examples
scope(exit)
{
assert(exists(deleteme));
remove(deleteme);
}
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write(deleteme, a); // deleteme is the name of a temporary file
const bytes = read(deleteme);
const fileInts = () @trusted { return cast(int[]) bytes; }();
assert(fileInts == a);
write((local variable) const(string) sourceFilesourceFile, string sparkles.test_runner.extract.generateWasmBareProgram(in sparkles.test_runner.extract.ExtractedTest[] tests) pure @safeA complete bare wasm32 test module (--wasm-bare): the extracted
functions, each exported as test_<i> for individual invocation by the
host shim, plus a trapping __assert handler (there is no libc on bare
wasm32, so a failed assert traps and surfaces as a host-side
RuntimeError).
generateWasmBareProgram((local variable) const(sparkles.test_runner.extract.ExtractedTest[]) extractedextracted));
void std.file.write!string(string name, const(void[]) buffer) @safeWrite buffer to file name.
Creates the file if it does not already exist.
Examples
scope(exit)
{
assert(exists(deleteme));
remove(deleteme);
}
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write(deleteme, a); // deleteme is the name of a temporary file
const bytes = read(deleteme);
const fileInts = () @trusted { return cast(int[]) bytes; }();
assert(fileInts == a);
write((local variable) const(string) shimFileshimFile, string sparkles.test_runner.extract.generateWasmBareJsShim(in sparkles.test_runner.extract.ExtractedTest[] tests, string wasmFile) pure @safeThe JavaScript shim executing a generated wasm test module under node,
deno, or bun: instantiates the module and calls each run_test_<i>
export, reporting per-test outcomes.
generateWasmBareJsShim((local variable) const(sparkles.test_runner.extract.ExtractedTest[]) extractedextracted, (local variable) const(string) wasmFilewasmFile));
const (local variable) const(string[]) importFlagsimportFlags = string[] sparkles.test_runner.driver.allImportFlags(in sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options)The compile context's flags: -I for the derived source roots, the
harness roots, dub described dependency paths unless noDub, and the
user's extras, then the string import paths, versions and flags
(process-model TRX1–TRX4).
allImportFlags((parameter) sparkles.test_runner.model.Test[] allTestsallTests, (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions);
const (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compilecompile = std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safeRuns command, echoing it when verbose, and returns (status, output).
A spawn failure (compiler binary vanished between the detectCompiler
check and here, or an unlaunchable absolute path) becomes a failed result
instead of a ProcessException stack trace.
run(
[(local variable) const(string) compilercompiler, "-mtriple=wasm32-unknown-unknown-wasm", "-betterC",
// LDC's own LLD: bare wasm32 has no C compiler driver to link with
"-link-internally",
// reactor-style module: no _start, tests are individual exports
"-L--no-entry",
// `export` alone does not make wasm-ld export a symbol; only some
// LDC configurations add this switch themselves
"-L--export-dynamic",
"-of=" ~ (local variable) const(string) wasmFilewasmFile]
~ string[] sparkles.test_runner.driver.autoIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safeThe -i=<module> flags derived from the tests being extracted: one per
distinct module that owns a test, minus the ones whose tests all opted out
with selfContained.
Compiling the owning module in is the useful default. Without it an
extracted program links against nothing but templates, so a @betterC
test that calls any ordinary function of the very module it lives in —
the common case — fails at link time with an undefined reference, which
made the marker attribute effectively decorative for such tests.
The opt-out is per test (@betterC(selfContained: true)) rather than
global because it is a property of the test: a module that is not itself
-betterC-codegen-clean can still host a template-only test, and that
self-containment is exactly what such a test asserts. --no-auto-include
disables the whole derivation for a one-off run.
autoIncludeFlags((parameter) sparkles.test_runner.model.Test[] wasmTestswasmTests, (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions) ~ string[] sparkles.test_runner.driver.includeFlags(in sparkles.test_runner.driver.DriverOptions options) pure @safeThe extra -i=<pattern> flags requested with --include-import (e.g.
--include-import=std.ascii to compile a std module in when an extracted
test needs one of its non-template functions).
includeFlags((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions)
~ (local variable) const(string[]) importFlagsimportFlags ~ [(local variable) const(string) sourceFilesourceFile],
(parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions);
if ((local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compilecompile.status != 0)
{
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safeargs and a line feed, to report's diagnostics.
warn((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compilecompile.(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1output);
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safeargs and a line feed, to report's diagnostics.
warn((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "failed to cross-compile the extracted @wasm tests (see above)");
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safeargs and a line feed, to report's diagnostics.
warn((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "note: with a stock LDC, the import chain of a @wasm test's " ~
"module must avoid druntime headers that do not support wasm32;\n" ~
"point --compiler (or $DC) at a wasm-enabled LDC build for full " ~
"druntime/Phobos support");
(local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome.(field) bool sparkles.test_runner.driver.DriverOutcome.succeededsucceeded = false;
return (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
}
const((alias) object.string = stringstring)[] (local variable) const(string)[] runCommandrunCommand;
if (bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safeWhether an executable is reachable through searchPath ($PATH by
default). On Windows the file is ``name.exe, as CreateProcess finds it:
$DC=ldc2 names ldc2.exe there.
A local re-implementation rather than sparkles.core_cli.process_utils.isInPath:
this module is source-compiled into base's test build, which has no
core-cli dependency (the impl-library cycle is impl → base).
inPath("node"))
(local variable) const(string)[] runCommandrunCommand = ["node", (local variable) const(string) shimFileshimFile];
else if (bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safeWhether an executable is reachable through searchPath ($PATH by
default). On Windows the file is ``name.exe, as CreateProcess finds it:
$DC=ldc2 names ldc2.exe there.
A local re-implementation rather than sparkles.core_cli.process_utils.isInPath:
this module is source-compiled into base's test build, which has no
core-cli dependency (the impl-library cycle is impl → base).
inPath("deno"))
(local variable) const(string)[] runCommandrunCommand = ["deno", "run", "--allow-read", (local variable) const(string) shimFileshimFile];
else if (bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safeWhether an executable is reachable through searchPath ($PATH by
default). On Windows the file is ``name.exe, as CreateProcess finds it:
$DC=ldc2 names ldc2.exe there.
A local re-implementation rather than sparkles.core_cli.process_utils.isInPath:
this module is source-compiled into base's test build, which has no
core-cli dependency (the impl-library cycle is impl → base).
inPath("bun"))
(local variable) const(string)[] runCommandrunCommand = ["bun", (local variable) const(string) shimFileshimFile];
else if (bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safeWhether an executable is reachable through searchPath ($PATH by
default). On Windows the file is ``name.exe, as CreateProcess finds it:
$DC=ldc2 names ldc2.exe there.
A local re-implementation rather than sparkles.core_cli.process_utils.isInPath:
this module is source-compiled into base's test build, which has no
core-cli dependency (the impl-library cycle is impl → base).
inPath("wasmtime"))
{
// No JS runtime: invoke each exported test directly.
foreach ((parameter) ulong ii, ref (parameter) const(sparkles.test_runner.extract.ExtractedTest) testtest; (local variable) const(sparkles.test_runner.extract.ExtractedTest[]) extractedextracted)
{
const (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult = std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safeRuns command, echoing it when verbose, and returns (status, output).
A spawn failure (compiler binary vanished between the detectCompiler
check and here, or an unlaunchable absolute path) becomes a failed result
instead of a ProcessException stack trace.
run(["wasmtime", "run",
"--invoke", string std.conv.text!(string, ulong)(string __param_0, ulong __param_1) pure nothrow @safeConvenience functions for converting one or more arguments
of any type into text (the three character widths).
text("run_test_", (local variable) ulong ii), (local variable) const(string) wasmFilewasmFile], (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions);
const (local variable) const(bool) okok = (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult.status == 0;
void sparkles.test_runner.driver.say!(string, string, string, string, string, const(ulong), string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2, string __param_3, string __param_4, string __param_5, const(ulong) __param_6, string __param_7) @safeargs and a line feed, to report's output.
say((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, (local variable) const(bool) okok ? " ✓ " : " ✗ ", (local variable) const(sparkles.test_runner.extract.ExtractedTest) testtest.(field) string sparkles.test_runner.extract.ExtractedTest.namedisplay name
name,
" [", (local variable) const(sparkles.test_runner.extract.ExtractedTest) testtest.(field) string sparkles.test_runner.extract.ExtractedTest.filefile, ":", (local variable) const(sparkles.test_runner.extract.ExtractedTest) testtest.(field) ulong sparkles.test_runner.extract.ExtractedTest.lineline, "]");
if (!(local variable) const(bool) okok)
{
void sparkles.test_runner.driver.sayRaw(in sparkles.test_runner.driver.DriverOptions options, string text)text, as it is, to report's output.
sayRaw((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult.(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1output);
(local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome.(field) bool sparkles.test_runner.driver.DriverOutcome.succeededsucceeded = false;
}
}
if ((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) bool sparkles.test_runner.driver.DriverOptions.keepkeep the generated files and print their location
keep)
void sparkles.test_runner.driver.say!(string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2) @safeargs and a line feed, to report's output.
say((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "generated files kept in ", (local variable) const(string) workDirworkDir);
return (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
}
else
{
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safeargs and a line feed, to report's diagnostics.
warn((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "skipping @wasm tests: no WebAssembly runtime found " ~
"(looked for node, deno, bun, wasmtime)");
(local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome.(field) bool sparkles.test_runner.driver.DriverOutcome.skippedmissing toolchain — reported but not a failure
skipped = true;
return (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
}
const (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult = std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safeRuns command, echoing it when verbose, and returns (status, output).
A spawn failure (compiler binary vanished between the detectCompiler
check and here, or an unlaunchable absolute path) becomes a failed result
instead of a ProcessException stack trace.
run((local variable) const(string)[] runCommandrunCommand, (parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions);
void sparkles.test_runner.driver.sayRaw(in sparkles.test_runner.driver.DriverOptions options, string text)text, as it is, to report's output.
sayRaw((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult.(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1output);
(local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome.(field) bool sparkles.test_runner.driver.DriverOutcome.succeededsucceeded = (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult.status == 0;
if ((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions.(field) bool sparkles.test_runner.driver.DriverOptions.keepkeep the generated files and print their location
keep)
void sparkles.test_runner.driver.say!(string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2) @safeargs and a line feed, to report's output.
say((parameter) const(sparkles.test_runner.driver.DriverOptions) optionsoptions, "generated files kept in ", (local variable) const(string) workDirworkDir);
return (local variable) sparkles.test_runner.driver.DriverOutcome outcomeoutcome;
}