code stringlengths 3 10M | language stringclasses 31 values |
|---|---|
module app.form.UserForm;
import hunt.framework;
class UserForm : Form
{
mixin MakeForm;
@Length (4, 30, "user name length must be between {min} and {Max}} bits.")
string username;
@Length (8, 32, "password length must be between {min} and {Max} bits.")
string password;
@Notempty ("email address cannot be empty.")
string email;
}
| D |
/**
* This module crawl the AST to resolve identifiers and process types.
*/
module d.semantic.semantic;
public import util.visitor;
import d.semantic.scheduler;
import d.ast.declaration;
import d.ast.expression;
import d.ast.statement;
import d.ir.expression;
import d.ir.symbol;
import d.ir.type;
import d.context.name;
alias AstModule = d.ast.declaration.Module;
alias Module = d.ir.symbol.Module;
alias CallExpression = d.ir.expression.CallExpression;
final class SemanticPass {
import d.context.context;
Context context;
Scheduler scheduler;
static struct State {
import d.ir.dscope;
Scope currentScope;
ParamType returnType;
ParamType thisType;
Function ctxSym;
string manglePrefix;
}
State state;
alias state this;
alias Step = d.ir.symbol.Step;
import d.semantic.evaluator;
Evaluator evaluator;
import d.semantic.datalayout;
DataLayout dataLayout;
import d.semantic.dmodule;
ModuleVisitor moduleVisitor;
import d.object;
ObjectReference object;
Name[] versions = getDefaultVersions();
alias EvaluatorBuilder = Evaluator delegate(Scheduler, ObjectReference);
alias DataLayoutBuilder = DataLayout delegate(ObjectReference);
this(
Context context,
EvaluatorBuilder evBuilder,
DataLayoutBuilder dlBuilder,
string[] includePaths,
) {
this.context = context;
moduleVisitor = new ModuleVisitor(this, includePaths);
scheduler = new Scheduler(this);
import d.context.name;
auto obj = importModule([BuiltinName!"object"]);
this.object = new ObjectReference(obj);
evaluator = evBuilder(scheduler, this.object);
dataLayout = dlBuilder(this.object);
scheduler.require(obj, Step.Populated);
}
Module add(string filename) {
return moduleVisitor.add(filename);
}
void terminate() {
scheduler.terminate();
}
auto evaluate(Expression e) {
return evaluator.evaluate(e);
}
auto evalIntegral(Expression e) {
return evaluator.evalIntegral(e);
}
auto evalString(Expression e) {
return evaluator.evalString(e);
}
auto importModule(Name[] pkgs) {
return moduleVisitor.importModule(pkgs);
}
Function buildMain(Module[] mods) {
import std.algorithm, std.array;
auto candidates = mods.map!(m => m.members).joiner.map!((s) {
if (auto fun = cast(Function) s) {
if (fun.name == BuiltinName!"main") {
return fun;
}
}
return null;
}).filter!(s => !!s).array();
assert(candidates.length < 2, "Several main functions");
assert(candidates.length == 1, "No main function");
auto main = candidates[0];
auto location = main.location;
auto type = main.type;
auto returnType = type.returnType.getType();
auto call = new CallExpression(location, returnType, new FunctionExpression(location, main), []);
import d.ir.instruction;
Body fbody;
auto bb = fbody.newBasicBlock(BuiltinName!"entry");
if (returnType.kind == TypeKind.Builtin && returnType.builtin == BuiltinType.Void) {
fbody[bb].eval(location, call);
fbody[bb].ret(location, new IntegerLiteral(location, 0, BuiltinType.Int));
} else {
fbody[bb].ret(location, call);
}
auto bootstrap = new Function(
main.location,
main.getModule(),
FunctionType(
Linkage.C,
Type.get(BuiltinType.Int).getParamType(false, false),
[],
false,
),
BuiltinName!"_Dmain",
[],
);
bootstrap.fbody = fbody;
bootstrap.visibility = Visibility.Public;
bootstrap.step = Step.Processed;
bootstrap.mangle = BuiltinName!"_Dmain";
return bootstrap;
}
}
private:
auto getDefaultVersions() {
import d.context.name;
auto versions = [BuiltinName!"SDC", BuiltinName!"D_LP64", BuiltinName!"X86_64", BuiltinName!"Posix"];
version(linux) {
versions ~= BuiltinName!"linux";
}
version(OSX) {
versions ~= BuiltinName!"OSX";
}
version(Posix) {
versions ~= BuiltinName!"Posix";
}
return versions;
}
| D |
// Written in the D programming language.
/**
This module implements a variety of type constructors, i.e., templates
that allow construction of new, useful general-purpose types.
$(SCRIPT inhibitQuickIndex = 1;)
$(BOOKTABLE,
$(TR $(TH Category) $(TH Functions))
$(TR $(TD Tuple) $(TD
$(LREF isTuple)
$(LREF Tuple)
$(LREF tuple)
$(LREF reverse)
))
$(TR $(TD Flags) $(TD
$(LREF BitFlags)
$(LREF isBitFlagEnum)
$(LREF Flag)
$(LREF No)
$(LREF Yes)
))
$(TR $(TD Memory allocation) $(TD
$(LREF RefCounted)
$(LREF refCounted)
$(LREF RefCountedAutoInitialize)
$(LREF scoped)
$(LREF Unique)
))
$(TR $(TD Code generation) $(TD
$(LREF AutoImplement)
$(LREF BlackHole)
$(LREF generateAssertTrap)
$(LREF generateEmptyFunction)
$(LREF WhiteHole)
))
$(TR $(TD Nullable) $(TD
$(LREF Nullable)
$(LREF nullable)
$(LREF NullableRef)
$(LREF nullableRef)
))
$(TR $(TD Proxies) $(TD
$(LREF Proxy)
$(LREF rebindable)
$(LREF Rebindable)
$(LREF ReplaceType)
$(LREF unwrap)
$(LREF wrap)
))
$(TR $(TD Types) $(TD
$(LREF alignForSize)
$(LREF Ternary)
$(LREF Typedef)
$(LREF TypedefType)
$(LREF UnqualRef)
))
)
Copyright: Copyright the respective authors, 2008-
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Source: $(PHOBOSSRC std/typecons.d)
Authors: $(HTTP erdani.org, Andrei Alexandrescu),
$(HTTP bartoszmilewski.wordpress.com, Bartosz Milewski),
Don Clugston,
Shin Fujishiro,
Kenji Hara
*/
module std.typecons;
import std.format : singleSpec, FormatSpec, formatValue;
import std.meta; // : AliasSeq, allSatisfy;
import std.range.primitives : isOutputRange;
import std.traits;
///
@safe unittest
{
// value tuples
alias Coord = Tuple!(int, "x", int, "y", int, "z");
Coord c;
c[1] = 1; // access by index
c.z = 1; // access by given name
assert(c == Coord(0, 1, 1));
// names can be omitted
alias DicEntry = Tuple!(string, string);
// tuples can also be constructed on instantiation
assert(tuple(2, 3, 4)[1] == 3);
// construction on instantiation works with names too
assert(tuple!("x", "y", "z")(2, 3, 4).y == 3);
// Rebindable references to const and immutable objects
{
class Widget { void foo() const @safe {} }
const w1 = new Widget, w2 = new Widget;
w1.foo();
// w1 = w2 would not work; can't rebind const object
auto r = Rebindable!(const Widget)(w1);
// invoke method as if r were a Widget object
r.foo();
// rebind r to refer to another object
r = w2;
}
}
/**
Encapsulates unique ownership of a resource.
When a `Unique!T` goes out of scope it will call `destroy`
on the resource `T` that it manages, unless it is transferred.
One important consequence of `destroy` is that it will call the
destructor of the resource `T`. GC-managed references are not
guaranteed to be valid during a destructor call, but other members of
`T`, such as file handles or pointers to `malloc` memory, will
still be valid during the destructor call. This allows the resource
`T` to deallocate or clean up any non-GC resources.
If it is desirable to persist a `Unique!T` outside of its original
scope, then it can be transferred. The transfer can be explicit, by
calling `release`, or implicit, when returning Unique from a
function. The resource `T` can be a polymorphic class object or
instance of an interface, in which case Unique behaves polymorphically
too.
If `T` is a value type, then `Unique!T` will be implemented
as a reference to a `T`.
*/
struct Unique(T)
{
/** Represents a reference to `T`. Resolves to `T*` if `T` is a value type. */
static if (is(T == class) || is(T == interface))
alias RefT = T;
else
alias RefT = T*;
public:
// Deferred in case we get some language support for checking uniqueness.
version (None)
/**
Allows safe construction of `Unique`. It creates the resource and
guarantees unique ownership of it (unless `T` publishes aliases of
`this`).
Note: Nested structs/classes cannot be created.
Params:
args = Arguments to pass to `T`'s constructor.
---
static class C {}
auto u = Unique!(C).create();
---
*/
static Unique!T create(A...)(auto ref A args)
if (__traits(compiles, new T(args)))
{
Unique!T u;
u._p = new T(args);
return u;
}
/**
Constructor that takes an rvalue.
It will ensure uniqueness, as long as the rvalue
isn't just a view on an lvalue (e.g., a cast).
Typical usage:
----
Unique!Foo f = new Foo;
----
*/
this(RefT p)
{
_p = p;
}
/**
Constructor that takes an lvalue. It nulls its source.
The nulling will ensure uniqueness as long as there
are no previous aliases to the source.
*/
this(ref RefT p)
{
_p = p;
p = null;
assert(p is null);
}
/**
Constructor that takes a `Unique` of a type that is convertible to our type.
Typically used to transfer a `Unique` rvalue of derived type to
a `Unique` of base type.
Example:
---
class C : Object {}
Unique!C uc = new C;
Unique!Object uo = uc.release;
---
*/
this(U)(Unique!U u)
if (is(u.RefT:RefT))
{
_p = u._p;
u._p = null;
}
/// Transfer ownership from a `Unique` of a type that is convertible to our type.
void opAssign(U)(Unique!U u)
if (is(u.RefT:RefT))
{
// first delete any resource we own
destroy(this);
_p = u._p;
u._p = null;
}
~this()
{
if (_p !is null)
{
destroy(_p);
_p = null;
}
}
/** Returns whether the resource exists. */
@property bool isEmpty() const
{
return _p is null;
}
/** Transfer ownership to a `Unique` rvalue. Nullifies the current contents.
Same as calling std.algorithm.move on it.
*/
Unique release()
{
import std.algorithm.mutation : move;
return this.move;
}
/** Forwards member access to contents. */
mixin Proxy!_p;
/**
Postblit operator is undefined to prevent the cloning of `Unique` objects.
*/
@disable this(this);
private:
RefT _p;
}
///
@safe unittest
{
static struct S
{
int i;
this(int i){this.i = i;}
}
Unique!S produce()
{
// Construct a unique instance of S on the heap
Unique!S ut = new S(5);
// Implicit transfer of ownership
return ut;
}
// Borrow a unique resource by ref
void increment(ref Unique!S ur)
{
ur.i++;
}
void consume(Unique!S u2)
{
assert(u2.i == 6);
// Resource automatically deleted here
}
Unique!S u1;
assert(u1.isEmpty);
u1 = produce();
increment(u1);
assert(u1.i == 6);
//consume(u1); // Error: u1 is not copyable
// Transfer ownership of the resource
consume(u1.release);
assert(u1.isEmpty);
}
@system unittest
{
// test conversion to base ref
int deleted = 0;
class C
{
~this(){deleted++;}
}
// constructor conversion
Unique!Object u = Unique!C(new C);
static assert(!__traits(compiles, {u = new C;}));
assert(!u.isEmpty);
destroy(u);
assert(deleted == 1);
Unique!C uc = new C;
static assert(!__traits(compiles, {Unique!Object uo = uc;}));
Unique!Object uo = new C;
// opAssign conversion, deleting uo resource first
uo = uc.release;
assert(uc.isEmpty);
assert(!uo.isEmpty);
assert(deleted == 2);
}
@system unittest
{
class Bar
{
~this() { debug(Unique) writeln(" Bar destructor"); }
int val() const { return 4; }
}
alias UBar = Unique!(Bar);
UBar g(UBar u)
{
debug(Unique) writeln("inside g");
return u.release;
}
auto ub = UBar(new Bar);
assert(!ub.isEmpty);
assert(ub.val == 4);
static assert(!__traits(compiles, {auto ub3 = g(ub);}));
auto ub2 = g(ub.release);
assert(ub.isEmpty);
assert(!ub2.isEmpty);
}
@system unittest
{
interface Bar
{
int val() const;
}
class BarImpl : Bar
{
static int count;
this()
{
count++;
}
~this()
{
count--;
}
int val() const { return 4; }
}
alias UBar = Unique!Bar;
UBar g(UBar u)
{
debug(Unique) writeln("inside g");
return u.release;
}
void consume(UBar u)
{
assert(u.val() == 4);
// Resource automatically deleted here
}
auto ub = UBar(new BarImpl);
assert(BarImpl.count == 1);
assert(!ub.isEmpty);
assert(ub.val == 4);
static assert(!__traits(compiles, {auto ub3 = g(ub);}));
auto ub2 = g(ub.release);
assert(ub.isEmpty);
assert(!ub2.isEmpty);
consume(ub2.release);
assert(BarImpl.count == 0);
}
@safe unittest
{
struct Foo
{
~this() { }
int val() const { return 3; }
@disable this(this);
}
alias UFoo = Unique!(Foo);
UFoo f(UFoo u)
{
return u.release;
}
auto uf = UFoo(new Foo);
assert(!uf.isEmpty);
assert(uf.val == 3);
static assert(!__traits(compiles, {auto uf3 = f(uf);}));
auto uf2 = f(uf.release);
assert(uf.isEmpty);
assert(!uf2.isEmpty);
}
// ensure Unique behaves correctly through const access paths
@system unittest
{
struct Bar {int val;}
struct Foo
{
Unique!Bar bar = new Bar;
}
Foo foo;
foo.bar.val = 6;
const Foo* ptr = &foo;
static assert(is(typeof(ptr) == const(Foo*)));
static assert(is(typeof(ptr.bar) == const(Unique!Bar)));
static assert(is(typeof(ptr.bar.val) == const(int)));
assert(ptr.bar.val == 6);
foo.bar.val = 7;
assert(ptr.bar.val == 7);
}
// Used in Tuple.toString
private template sharedToString(alias field)
if (is(typeof(field) == shared))
{
static immutable sharedToString = typeof(field).stringof;
}
private template sharedToString(alias field)
if (!is(typeof(field) == shared))
{
alias sharedToString = field;
}
private enum bool distinctFieldNames(names...) = __traits(compiles,
{
static foreach (__name; names)
static if (is(typeof(__name) : string))
mixin("enum int " ~ __name ~ " = 0;");
});
@safe unittest
{
static assert(!distinctFieldNames!(string, "abc", string, "abc"));
static assert(distinctFieldNames!(string, "abc", int, "abd"));
static assert(!distinctFieldNames!(int, "abc", string, "abd", int, "abc"));
// Issue 19240
static assert(!distinctFieldNames!(int, "int"));
}
/**
_Tuple of values, for example $(D Tuple!(int, string)) is a record that
stores an `int` and a `string`. `Tuple` can be used to bundle
values together, notably when returning multiple values from a
function. If `obj` is a `Tuple`, the individual members are
accessible with the syntax `obj[0]` for the first field, `obj[1]`
for the second, and so on.
See_Also: $(LREF tuple).
Params:
Specs = A list of types (and optionally, member names) that the `Tuple` contains.
*/
template Tuple(Specs...)
if (distinctFieldNames!(Specs))
{
import std.meta : staticMap;
// Parse (type,name) pairs (FieldSpecs) out of the specified
// arguments. Some fields would have name, others not.
template parseSpecs(Specs...)
{
static if (Specs.length == 0)
{
alias parseSpecs = AliasSeq!();
}
else static if (is(Specs[0]))
{
static if (is(typeof(Specs[1]) : string))
{
alias parseSpecs =
AliasSeq!(FieldSpec!(Specs[0 .. 2]),
parseSpecs!(Specs[2 .. $]));
}
else
{
alias parseSpecs =
AliasSeq!(FieldSpec!(Specs[0]),
parseSpecs!(Specs[1 .. $]));
}
}
else
{
static assert(0, "Attempted to instantiate Tuple with an "
~"invalid argument: "~ Specs[0].stringof);
}
}
template FieldSpec(T, string s = "")
{
alias Type = T;
alias name = s;
}
alias fieldSpecs = parseSpecs!Specs;
// Used with staticMap.
alias extractType(alias spec) = spec.Type;
alias extractName(alias spec) = spec.name;
// Generates named fields as follows:
// alias name_0 = Identity!(field[0]);
// alias name_1 = Identity!(field[1]);
// :
// NOTE: field[k] is an expression (which yields a symbol of a
// variable) and can't be aliased directly.
string injectNamedFields()
{
string decl = "";
static foreach (i, val; fieldSpecs)
{{
immutable si = i.stringof;
decl ~= "alias _" ~ si ~ " = Identity!(field[" ~ si ~ "]);";
if (val.name.length != 0)
{
decl ~= "alias " ~ val.name ~ " = _" ~ si ~ ";";
}
}}
return decl;
}
// Returns Specs for a subtuple this[from .. to] preserving field
// names if any.
alias sliceSpecs(size_t from, size_t to) =
staticMap!(expandSpec, fieldSpecs[from .. to]);
template expandSpec(alias spec)
{
static if (spec.name.length == 0)
{
alias expandSpec = AliasSeq!(spec.Type);
}
else
{
alias expandSpec = AliasSeq!(spec.Type, spec.name);
}
}
enum areCompatibleTuples(Tup1, Tup2, string op) = isTuple!Tup2 && is(typeof(
(ref Tup1 tup1, ref Tup2 tup2)
{
static assert(tup1.field.length == tup2.field.length);
static foreach (i; 0 .. Tup1.Types.length)
{{
auto lhs = typeof(tup1.field[i]).init;
auto rhs = typeof(tup2.field[i]).init;
static if (op == "=")
lhs = rhs;
else
auto result = mixin("lhs "~op~" rhs");
}}
}));
enum areBuildCompatibleTuples(Tup1, Tup2) = isTuple!Tup2 && is(typeof(
{
static assert(Tup1.Types.length == Tup2.Types.length);
static foreach (i; 0 .. Tup1.Types.length)
static assert(isBuildable!(Tup1.Types[i], Tup2.Types[i]));
}));
/+ Returns `true` iff a `T` can be initialized from a `U`. +/
enum isBuildable(T, U) = is(typeof(
{
U u = U.init;
T t = u;
}));
/+ Helper for partial instantiation +/
template isBuildableFrom(U)
{
enum isBuildableFrom(T) = isBuildable!(T, U);
}
struct Tuple
{
/**
* The types of the `Tuple`'s components.
*/
alias Types = staticMap!(extractType, fieldSpecs);
private alias _Fields = Specs;
///
static if (Specs.length == 0) @safe unittest
{
alias Fields = Tuple!(int, "id", string, float);
static assert(is(Fields.Types == AliasSeq!(int, string, float)));
}
/**
* The names of the `Tuple`'s components. Unnamed fields have empty names.
*/
alias fieldNames = staticMap!(extractName, fieldSpecs);
///
static if (Specs.length == 0) @safe unittest
{
alias Fields = Tuple!(int, "id", string, float);
static assert(Fields.fieldNames == AliasSeq!("id", "", ""));
}
/**
* Use `t.expand` for a `Tuple` `t` to expand it into its
* components. The result of `expand` acts as if the `Tuple`'s components
* were listed as a list of values. (Ordinarily, a `Tuple` acts as a
* single value.)
*/
Types expand;
mixin(injectNamedFields());
///
static if (Specs.length == 0) @safe unittest
{
auto t1 = tuple(1, " hello ", 'a');
assert(t1.toString() == `Tuple!(int, string, char)(1, " hello ", 'a')`);
void takeSeveralTypes(int n, string s, bool b)
{
assert(n == 4 && s == "test" && b == false);
}
auto t2 = tuple(4, "test", false);
//t.expand acting as a list of values
takeSeveralTypes(t2.expand);
}
static if (is(Specs))
{
// This is mostly to make t[n] work.
alias expand this;
}
else
{
@property
ref inout(Tuple!Types) _Tuple_super() inout @trusted
{
static foreach (i; 0 .. Types.length) // Rely on the field layout
{
static assert(typeof(return).init.tupleof[i].offsetof ==
expand[i].offsetof);
}
return *cast(typeof(return)*) &(field[0]);
}
// This is mostly to make t[n] work.
alias _Tuple_super this;
}
// backwards compatibility
alias field = expand;
/**
* Constructor taking one value for each field.
*
* Params:
* values = A list of values that are either the same
* types as those given by the `Types` field
* of this `Tuple`, or can implicitly convert
* to those types. They must be in the same
* order as they appear in `Types`.
*/
static if (Types.length > 0)
{
this(Types values)
{
field[] = values[];
}
}
///
static if (Specs.length == 0) @safe unittest
{
alias ISD = Tuple!(int, string, double);
auto tup = ISD(1, "test", 3.2);
assert(tup.toString() == `Tuple!(int, string, double)(1, "test", 3.2)`);
}
/**
* Constructor taking a compatible array.
*
* Params:
* values = A compatible static array to build the `Tuple` from.
* Array slices are not supported.
*/
this(U, size_t n)(U[n] values)
if (n == Types.length && allSatisfy!(isBuildableFrom!U, Types))
{
static foreach (i; 0 .. Types.length)
{
field[i] = values[i];
}
}
///
static if (Specs.length == 0) @safe unittest
{
int[2] ints;
Tuple!(int, int) t = ints;
}
/**
* Constructor taking a compatible `Tuple`. Two `Tuple`s are compatible
* $(B iff) they are both of the same length, and, for each type `T` on the
* left-hand side, the corresponding type `U` on the right-hand side can
* implicitly convert to `T`.
*
* Params:
* another = A compatible `Tuple` to build from. Its type must be
* compatible with the target `Tuple`'s type.
*/
this(U)(U another)
if (areBuildCompatibleTuples!(typeof(this), U))
{
field[] = another.field[];
}
///
static if (Specs.length == 0) @safe unittest
{
alias IntVec = Tuple!(int, int, int);
alias DubVec = Tuple!(double, double, double);
IntVec iv = tuple(1, 1, 1);
//Ok, int can implicitly convert to double
DubVec dv = iv;
//Error: double cannot implicitly convert to int
//IntVec iv2 = dv;
}
/**
* Comparison for equality. Two `Tuple`s are considered equal
* $(B iff) they fulfill the following criteria:
*
* $(UL
* $(LI Each `Tuple` is the same length.)
* $(LI For each type `T` on the left-hand side and each type
* `U` on the right-hand side, values of type `T` can be
* compared with values of type `U`.)
* $(LI For each value `v1` on the left-hand side and each value
* `v2` on the right-hand side, the expression `v1 == v2` is
* true.))
*
* Params:
* rhs = The `Tuple` to compare against. It must meeting the criteria
* for comparison between `Tuple`s.
*
* Returns:
* true if both `Tuple`s are equal, otherwise false.
*/
bool opEquals(R)(R rhs)
if (areCompatibleTuples!(typeof(this), R, "=="))
{
return field[] == rhs.field[];
}
/// ditto
bool opEquals(R)(R rhs) const
if (areCompatibleTuples!(typeof(this), R, "=="))
{
return field[] == rhs.field[];
}
/// ditto
bool opEquals(R...)(auto ref R rhs)
if (R.length > 1 && areCompatibleTuples!(typeof(this), Tuple!R, "=="))
{
static foreach (i; 0 .. Types.length)
if (field[i] != rhs[i])
return false;
return true;
}
///
static if (Specs.length == 0) @safe unittest
{
Tuple!(int, string) t1 = tuple(1, "test");
Tuple!(double, string) t2 = tuple(1.0, "test");
//Ok, int can be compared with double and
//both have a value of 1
assert(t1 == t2);
}
/**
* Comparison for ordering.
*
* Params:
* rhs = The `Tuple` to compare against. It must meet the criteria
* for comparison between `Tuple`s.
*
* Returns:
* For any values `v1` on the right-hand side and `v2` on the
* left-hand side:
*
* $(UL
* $(LI A negative integer if the expression `v1 < v2` is true.)
* $(LI A positive integer if the expression `v1 > v2` is true.)
* $(LI 0 if the expression `v1 == v2` is true.))
*/
int opCmp(R)(R rhs)
if (areCompatibleTuples!(typeof(this), R, "<"))
{
static foreach (i; 0 .. Types.length)
{
if (field[i] != rhs.field[i])
{
return field[i] < rhs.field[i] ? -1 : 1;
}
}
return 0;
}
/// ditto
int opCmp(R)(R rhs) const
if (areCompatibleTuples!(typeof(this), R, "<"))
{
static foreach (i; 0 .. Types.length)
{
if (field[i] != rhs.field[i])
{
return field[i] < rhs.field[i] ? -1 : 1;
}
}
return 0;
}
/**
The first `v1` for which `v1 > v2` is true determines
the result. This could lead to unexpected behaviour.
*/
static if (Specs.length == 0) @safe unittest
{
auto tup1 = tuple(1, 1, 1);
auto tup2 = tuple(1, 100, 100);
assert(tup1 < tup2);
//Only the first result matters for comparison
tup1[0] = 2;
assert(tup1 > tup2);
}
/**
Concatenate Tuples.
Tuple concatenation is only allowed if all named fields are distinct (no named field of this tuple occurs in `t`
and no named field of `t` occurs in this tuple).
Params:
t = The `Tuple` to concatenate with
Returns: A concatenation of this tuple and `t`
*/
auto opBinary(string op, T)(auto ref T t)
if (op == "~" && !(is(T : U[], U) && isTuple!U))
{
static if (isTuple!T)
{
static assert(distinctFieldNames!(_Fields, T._Fields),
"Cannot concatenate tuples with duplicate fields: " ~ fieldNames.stringof ~
" - " ~ T.fieldNames.stringof);
return Tuple!(_Fields, T._Fields)(expand, t.expand);
}
else
{
return Tuple!(_Fields, T)(expand, t);
}
}
/// ditto
auto opBinaryRight(string op, T)(auto ref T t)
if (op == "~" && !(is(T : U[], U) && isTuple!U))
{
static if (isTuple!T)
{
static assert(distinctFieldNames!(_Fields, T._Fields),
"Cannot concatenate tuples with duplicate fields: " ~ T.stringof ~
" - " ~ fieldNames.fieldNames.stringof);
return Tuple!(T._Fields, _Fields)(t.expand, expand);
}
else
{
return Tuple!(T, _Fields)(t, expand);
}
}
/**
* Assignment from another `Tuple`.
*
* Params:
* rhs = The source `Tuple` to assign from. Each element of the
* source `Tuple` must be implicitly assignable to each
* respective element of the target `Tuple`.
*/
ref Tuple opAssign(R)(auto ref R rhs)
if (areCompatibleTuples!(typeof(this), R, "="))
{
import std.algorithm.mutation : swap;
static if (is(R : Tuple!Types) && !__traits(isRef, rhs))
{
if (__ctfe)
{
// Cannot use swap at compile time
field[] = rhs.field[];
}
else
{
// Use swap-and-destroy to optimize rvalue assignment
swap!(Tuple!Types)(this, rhs);
}
}
else
{
// Do not swap; opAssign should be called on the fields.
field[] = rhs.field[];
}
return this;
}
/**
* Renames the elements of a $(LREF Tuple).
*
* `rename` uses the passed `names` and returns a new
* $(LREF Tuple) using these names, with the content
* unchanged.
* If fewer names are passed than there are members
* of the $(LREF Tuple) then those trailing members are unchanged.
* An empty string will remove the name for that member.
* It is an compile-time error to pass more names than
* there are members of the $(LREF Tuple).
*/
ref rename(names...)() return
if (names.length == 0 || allSatisfy!(isSomeString, typeof(names)))
{
import std.algorithm.comparison : equal;
// to circumvent bug 16418
static if (names.length == 0 || equal([names], [fieldNames]))
return this;
else
{
enum nT = Types.length;
enum nN = names.length;
static assert(nN <= nT, "Cannot have more names than tuple members");
alias allNames = AliasSeq!(names, fieldNames[nN .. $]);
template GetItem(size_t idx)
{
import std.array : empty;
static if (idx < nT)
alias GetItem = Alias!(Types[idx]);
else static if (allNames[idx - nT].empty)
alias GetItem = AliasSeq!();
else
alias GetItem = Alias!(allNames[idx - nT]);
}
import std.range : roundRobin, iota;
alias NewTupleT = Tuple!(staticMap!(GetItem, aliasSeqOf!(
roundRobin(iota(nT), iota(nT, 2*nT)))));
return *(() @trusted => cast(NewTupleT*)&this)();
}
}
///
static if (Specs.length == 0) @safe unittest
{
auto t0 = tuple(4, "hello");
auto t0Named = t0.rename!("val", "tag");
assert(t0Named.val == 4);
assert(t0Named.tag == "hello");
Tuple!(float, "dat", size_t[2], "pos") t1;
t1.pos = [2, 1];
auto t1Named = t1.rename!"height";
t1Named.height = 3.4f;
assert(t1Named.height == 3.4f);
assert(t1Named.pos == [2, 1]);
t1Named.rename!"altitude".altitude = 5;
assert(t1Named.height == 5);
Tuple!(int, "a", int, int, "c") t2;
t2 = tuple(3,4,5);
auto t2Named = t2.rename!("", "b");
// "a" no longer has a name
static assert(!hasMember!(typeof(t2Named), "a"));
assert(t2Named[0] == 3);
assert(t2Named.b == 4);
assert(t2Named.c == 5);
// not allowed to specify more names than the tuple has members
static assert(!__traits(compiles, t2.rename!("a","b","c","d")));
// use it in a range pipeline
import std.range : iota, zip;
import std.algorithm.iteration : map, sum;
auto res = zip(iota(1, 4), iota(10, 13))
.map!(t => t.rename!("a", "b"))
.map!(t => t.a * t.b)
.sum;
assert(res == 68);
}
/**
* Overload of $(LREF _rename) that takes an associative array
* `translate` as a template parameter, where the keys are
* either the names or indices of the members to be changed
* and the new names are the corresponding values.
* Every key in `translate` must be the name of a member of the
* $(LREF tuple).
* The same rules for empty strings apply as for the variadic
* template overload of $(LREF _rename).
*/
ref rename(alias translate)()
if (is(typeof(translate) : V[K], V, K) && isSomeString!V &&
(isSomeString!K || is(K : size_t)))
{
import std.range : ElementType;
static if (isSomeString!(ElementType!(typeof(translate.keys))))
{
{
import std.conv : to;
import std.algorithm.iteration : filter;
import std.algorithm.searching : canFind;
enum notFound = translate.keys
.filter!(k => fieldNames.canFind(k) == -1);
static assert(notFound.empty, "Cannot find members "
~ notFound.to!string ~ " in type "
~ typeof(this).stringof);
}
return this.rename!(aliasSeqOf!(
{
import std.array : empty;
auto names = [fieldNames];
foreach (ref n; names)
if (!n.empty)
if (auto p = n in translate)
n = *p;
return names;
}()));
}
else
{
{
import std.algorithm.iteration : filter;
import std.conv : to;
enum invalid = translate.keys.
filter!(k => k < 0 || k >= this.length);
static assert(invalid.empty, "Indices " ~ invalid.to!string
~ " are out of bounds for tuple with length "
~ this.length.to!string);
}
return this.rename!(aliasSeqOf!(
{
auto names = [fieldNames];
foreach (k, v; translate)
names[k] = v;
return names;
}()));
}
}
///
static if (Specs.length == 0) @safe unittest
{
//replacing names by their current name
Tuple!(float, "dat", size_t[2], "pos") t1;
t1.pos = [2, 1];
auto t1Named = t1.rename!(["dat": "height"]);
t1Named.height = 3.4;
assert(t1Named.pos == [2, 1]);
t1Named.rename!(["height": "altitude"]).altitude = 5;
assert(t1Named.height == 5);
Tuple!(int, "a", int, "b") t2;
t2 = tuple(3, 4);
auto t2Named = t2.rename!(["a": "b", "b": "c"]);
assert(t2Named.b == 3);
assert(t2Named.c == 4);
}
///
static if (Specs.length == 0) @safe unittest
{
//replace names by their position
Tuple!(float, "dat", size_t[2], "pos") t1;
t1.pos = [2, 1];
auto t1Named = t1.rename!([0: "height"]);
t1Named.height = 3.4;
assert(t1Named.pos == [2, 1]);
t1Named.rename!([0: "altitude"]).altitude = 5;
assert(t1Named.height == 5);
Tuple!(int, "a", int, "b", int, "c") t2;
t2 = tuple(3, 4, 5);
auto t2Named = t2.rename!([0: "c", 2: "a"]);
assert(t2Named.a == 5);
assert(t2Named.b == 4);
assert(t2Named.c == 3);
}
static if (Specs.length == 0) @safe unittest
{
//check that empty translations work fine
enum string[string] a0 = null;
enum string[int] a1 = null;
Tuple!(float, "a", float, "b") t0;
auto t1 = t0.rename!a0;
t1.a = 3;
t1.b = 4;
auto t2 = t0.rename!a1;
t2.a = 3;
t2.b = 4;
auto t3 = t0.rename;
t3.a = 3;
t3.b = 4;
}
/**
* Takes a slice by-reference of this `Tuple`.
*
* Params:
* from = A `size_t` designating the starting position of the slice.
* to = A `size_t` designating the ending position (exclusive) of the slice.
*
* Returns:
* A new `Tuple` that is a slice from `[from, to$(RPAREN)` of the original.
* It has the same types and values as the range `[from, to$(RPAREN)` in
* the original.
*/
@property
ref inout(Tuple!(sliceSpecs!(from, to))) slice(size_t from, size_t to)() inout @trusted
if (from <= to && to <= Types.length)
{
static assert(
(typeof(this).alignof % typeof(return).alignof == 0) &&
(expand[from].offsetof % typeof(return).alignof == 0),
"Slicing by reference is impossible because of an alignment mistmatch. (See Phobos issue #15645.)");
return *cast(typeof(return)*) &(field[from]);
}
///
static if (Specs.length == 0) @safe unittest
{
Tuple!(int, string, float, double) a;
a[1] = "abc";
a[2] = 4.5;
auto s = a.slice!(1, 3);
static assert(is(typeof(s) == Tuple!(string, float)));
assert(s[0] == "abc" && s[1] == 4.5);
// Phobos issue #15645
Tuple!(int, short, bool, double) b;
static assert(!__traits(compiles, b.slice!(2, 4)));
}
/**
Creates a hash of this `Tuple`.
Returns:
A `size_t` representing the hash of this `Tuple`.
*/
size_t toHash() const nothrow @safe
{
size_t h = 0;
static foreach (i, T; Types)
{{
static if (__traits(compiles, h = .hashOf(field[i])))
const k = .hashOf(field[i]);
else
// Workaround for when .hashOf is not both @safe and nothrow.
// BUG: Improperly casts away `shared`!
const k = typeid(T).getHash((() @trusted => cast(const void*) &field[i])());
static if (i == 0)
h = k;
else
// As in boost::hash_combine
// https://www.boost.org/doc/libs/1_55_0/doc/html/hash/reference.html#boost.hash_combine
h ^= k + 0x9e3779b9 + (h << 6) + (h >>> 2);
}}
return h;
}
/**
* Converts to string.
*
* Returns:
* The string representation of this `Tuple`.
*/
string toString()() const
{
import std.array : appender;
auto app = appender!string();
this.toString((const(char)[] chunk) => app ~= chunk);
return app.data;
}
import std.format : FormatSpec;
/**
* Formats `Tuple` with either `%s`, `%(inner%)` or `%(inner%|sep%)`.
*
* $(TABLE2 Formats supported by Tuple,
* $(THEAD Format, Description)
* $(TROW $(P `%s`), $(P Format like `Tuple!(types)(elements formatted with %s each)`.))
* $(TROW $(P `%(inner%)`), $(P The format `inner` is applied the expanded `Tuple`$(COMMA) so
* it may contain as many formats as the `Tuple` has fields.))
* $(TROW $(P `%(inner%|sep%)`), $(P The format `inner` is one format$(COMMA) that is applied
* on all fields of the `Tuple`. The inner format must be compatible to all
* of them.)))
*
* Params:
* sink = A `char` accepting delegate
* fmt = A $(REF FormatSpec, std,format)
*/
void toString(DG)(scope DG sink) const
{
auto f = FormatSpec!char();
toString(sink, f);
}
/// ditto
void toString(DG, Char)(scope DG sink, const ref FormatSpec!Char fmt) const
{
import std.format : formatElement, formattedWrite, FormatException;
if (fmt.nested)
{
if (fmt.sep)
{
foreach (i, Type; Types)
{
static if (i > 0)
{
sink(fmt.sep);
}
// TODO: Change this once formattedWrite() works for shared objects.
static if (is(Type == class) && is(Type == shared))
{
sink(Type.stringof);
}
else
{
formattedWrite(sink, fmt.nested, this.field[i]);
}
}
}
else
{
formattedWrite(sink, fmt.nested, staticMap!(sharedToString, this.expand));
}
}
else if (fmt.spec == 's')
{
enum header = Unqual!(typeof(this)).stringof ~ "(",
footer = ")",
separator = ", ";
sink(header);
foreach (i, Type; Types)
{
static if (i > 0)
{
sink(separator);
}
// TODO: Change this once formatElement() works for shared objects.
static if (is(Type == class) && is(Type == shared))
{
sink(Type.stringof);
}
else
{
FormatSpec!Char f;
formatElement(sink, field[i], f);
}
}
sink(footer);
}
else
{
throw new FormatException(
"Expected '%s' or '%(...%)' or '%(...%|...%)' format specifier for type '" ~
Unqual!(typeof(this)).stringof ~ "', not '%" ~ fmt.spec ~ "'.");
}
}
///
static if (Types.length == 0)
@safe unittest
{
import std.format : format;
Tuple!(int, double)[3] tupList = [ tuple(1, 1.0), tuple(2, 4.0), tuple(3, 9.0) ];
// Default format
assert(format("%s", tuple("a", 1)) == `Tuple!(string, int)("a", 1)`);
// One Format for each individual component
assert(format("%(%#x v %.4f w %#x%)", tuple(1, 1.0, 10)) == `0x1 v 1.0000 w 0xa`);
assert(format( "%#x v %.4f w %#x" , tuple(1, 1.0, 10).expand) == `0x1 v 1.0000 w 0xa`);
// One Format for all components
assert(format("%(>%s<%| & %)", tuple("abc", 1, 2.3, [4, 5])) == `>abc< & >1< & >2.3< & >[4, 5]<`);
// Array of Tuples
assert(format("%(%(f(%d) = %.1f%); %)", tupList) == `f(1) = 1.0; f(2) = 4.0; f(3) = 9.0`);
}
///
static if (Types.length == 0)
@safe unittest
{
import std.exception : assertThrown;
import std.format : format, FormatException;
// Error: %( %) missing.
assertThrown!FormatException(
format("%d, %f", tuple(1, 2.0)) == `1, 2.0`
);
// Error: %( %| %) missing.
assertThrown!FormatException(
format("%d", tuple(1, 2)) == `1, 2`
);
// Error: %d inadequate for double
assertThrown!FormatException(
format("%(%d%|, %)", tuple(1, 2.0)) == `1, 2.0`
);
}
}
}
///
@safe unittest
{
Tuple!(int, int) point;
// assign coordinates
point[0] = 5;
point[1] = 6;
// read coordinates
auto x = point[0];
auto y = point[1];
}
/**
`Tuple` members can be named. It is legal to mix named and unnamed
members. The method above is still applicable to all fields.
*/
@safe unittest
{
alias Entry = Tuple!(int, "index", string, "value");
Entry e;
e.index = 4;
e.value = "Hello";
assert(e[1] == "Hello");
assert(e[0] == 4);
}
/**
A `Tuple` with named fields is a distinct type from a `Tuple` with unnamed
fields, i.e. each naming imparts a separate type for the `Tuple`. Two
`Tuple`s differing in naming only are still distinct, even though they
might have the same structure.
*/
@safe unittest
{
Tuple!(int, "x", int, "y") point1;
Tuple!(int, int) point2;
assert(!is(typeof(point1) == typeof(point2)));
}
/// Use tuples as ranges
@safe unittest
{
import std.algorithm.iteration : sum;
import std.range : only;
auto t = tuple(1, 2);
assert(t.expand.only.sum == 3);
}
@safe unittest
{
// Bugzilla 4582
static assert(!__traits(compiles, Tuple!(string, "id", int, "id")));
static assert(!__traits(compiles, Tuple!(string, "str", int, "i", string, "str", float)));
}
/// Concatenate tuples
@safe unittest
{
import std.meta : AliasSeq;
auto t = tuple(1, "2") ~ tuple(ushort(42), true);
static assert(is(t.Types == AliasSeq!(int, string, ushort, bool)));
assert(t[1] == "2");
assert(t[2] == 42);
assert(t[3] == true);
}
// https://issues.dlang.org/show_bug.cgi?id=14637
// tuple concat
@safe unittest
{
auto t = tuple!"foo"(1.0) ~ tuple!"bar"("3");
static assert(is(t.Types == AliasSeq!(double, string)));
static assert(t.fieldNames == tuple("foo", "bar"));
assert(t.foo == 1.0);
assert(t.bar == "3");
}
// https://issues.dlang.org/show_bug.cgi?id=18824
// tuple concat
@safe unittest
{
alias Type = Tuple!(int, string);
Type[] arr;
auto t = tuple(2, "s");
// Test opBinaryRight
arr = arr ~ t;
// Test opBinary
arr = t ~ arr;
static assert(is(typeof(arr) == Type[]));
immutable Type[] b;
auto c = b ~ t;
static assert(is(typeof(c) == immutable(Type)[]));
}
// tuple concat
@safe unittest
{
auto t = tuple!"foo"(1.0) ~ "3";
static assert(is(t.Types == AliasSeq!(double, string)));
assert(t.foo == 1.0);
assert(t[1]== "3");
}
// tuple concat
@safe unittest
{
auto t = "2" ~ tuple!"foo"(1.0);
static assert(is(t.Types == AliasSeq!(string, double)));
assert(t.foo == 1.0);
assert(t[0]== "2");
}
// tuple concat
@safe unittest
{
auto t = "2" ~ tuple!"foo"(1.0) ~ tuple(42, 3.0f) ~ real(1) ~ "a";
static assert(is(t.Types == AliasSeq!(string, double, int, float, real, string)));
assert(t.foo == 1.0);
assert(t[0] == "2");
assert(t[1] == 1.0);
assert(t[2] == 42);
assert(t[3] == 3.0f);
assert(t[4] == 1.0);
assert(t[5] == "a");
}
// ensure that concatenation of tuples with non-distinct fields is forbidden
@safe unittest
{
static assert(!__traits(compiles,
tuple!("a")(0) ~ tuple!("a")("1")));
static assert(!__traits(compiles,
tuple!("a", "b")(0, 1) ~ tuple!("b", "a")("3", 1)));
static assert(!__traits(compiles,
tuple!("a")(0) ~ tuple!("b", "a")("3", 1)));
static assert(!__traits(compiles,
tuple!("a1", "a")(1.0, 0) ~ tuple!("a2", "a")("3", 0)));
}
// Ensure that Tuple comparison with non-const opEquals works
@safe unittest
{
static struct Bad
{
int a;
bool opEquals(Bad b)
{
return a == b.a;
}
}
auto t = Tuple!(int, Bad, string)(1, Bad(1), "asdf");
//Error: mutable method Bad.opEquals is not callable using a const object
assert(t == AliasSeq!(1, Bad(1), "asdf"));
}
/**
Creates a copy of a $(LREF Tuple) with its fields in _reverse order.
Params:
t = The `Tuple` to copy.
Returns:
A new `Tuple`.
*/
auto reverse(T)(T t)
if (isTuple!T)
{
import std.meta : Reverse;
// @@@BUG@@@ Cannot be an internal function due to forward reference issues.
// @@@BUG@@@ 9929 Need 'this' when calling template with expanded tuple
// return tuple(Reverse!(t.expand));
ReverseTupleType!T result;
auto tup = t.expand;
result.expand = Reverse!tup;
return result;
}
///
@safe unittest
{
auto tup = tuple(1, "2");
assert(tup.reverse == tuple("2", 1));
}
/* Get a Tuple type with the reverse specification of Tuple T. */
private template ReverseTupleType(T)
if (isTuple!T)
{
static if (is(T : Tuple!A, A...))
alias ReverseTupleType = Tuple!(ReverseTupleSpecs!A);
}
/* Reverse the Specs of a Tuple. */
private template ReverseTupleSpecs(T...)
{
static if (T.length > 1)
{
static if (is(typeof(T[$-1]) : string))
{
alias ReverseTupleSpecs = AliasSeq!(T[$-2], T[$-1], ReverseTupleSpecs!(T[0 .. $-2]));
}
else
{
alias ReverseTupleSpecs = AliasSeq!(T[$-1], ReverseTupleSpecs!(T[0 .. $-1]));
}
}
else
{
alias ReverseTupleSpecs = T;
}
}
// ensure that internal Tuple unittests are compiled
@safe unittest
{
Tuple!() t;
}
@safe unittest
{
import std.conv;
{
Tuple!(int, "a", int, "b") nosh;
static assert(nosh.length == 2);
nosh.a = 5;
nosh.b = 6;
assert(nosh.a == 5);
assert(nosh.b == 6);
}
{
Tuple!(short, double) b;
static assert(b.length == 2);
b[1] = 5;
auto a = Tuple!(int, real)(b);
assert(a[0] == 0 && a[1] == 5);
a = Tuple!(int, real)(1, 2);
assert(a[0] == 1 && a[1] == 2);
auto c = Tuple!(int, "a", double, "b")(a);
assert(c[0] == 1 && c[1] == 2);
}
{
Tuple!(int, real) nosh;
nosh[0] = 5;
nosh[1] = 0;
assert(nosh[0] == 5 && nosh[1] == 0);
assert(nosh.to!string == "Tuple!(int, real)(5, 0)", nosh.to!string);
Tuple!(int, int) yessh;
nosh = yessh;
}
{
class A {}
Tuple!(int, shared A) nosh;
nosh[0] = 5;
assert(nosh[0] == 5 && nosh[1] is null);
assert(nosh.to!string == "Tuple!(int, shared(A))(5, shared(A))");
}
{
Tuple!(int, string) t;
t[0] = 10;
t[1] = "str";
assert(t[0] == 10 && t[1] == "str");
assert(t.to!string == `Tuple!(int, string)(10, "str")`, t.to!string);
}
{
Tuple!(int, "a", double, "b") x;
static assert(x.a.offsetof == x[0].offsetof);
static assert(x.b.offsetof == x[1].offsetof);
x.b = 4.5;
x.a = 5;
assert(x[0] == 5 && x[1] == 4.5);
assert(x.a == 5 && x.b == 4.5);
}
// indexing
{
Tuple!(int, real) t;
static assert(is(typeof(t[0]) == int));
static assert(is(typeof(t[1]) == real));
int* p0 = &t[0];
real* p1 = &t[1];
t[0] = 10;
t[1] = -200.0L;
assert(*p0 == t[0]);
assert(*p1 == t[1]);
}
// slicing
{
Tuple!(int, "x", real, "y", double, "z", string) t;
t[0] = 10;
t[1] = 11;
t[2] = 12;
t[3] = "abc";
auto a = t.slice!(0, 3);
assert(a.length == 3);
assert(a.x == t.x);
assert(a.y == t.y);
assert(a.z == t.z);
auto b = t.slice!(2, 4);
assert(b.length == 2);
assert(b.z == t.z);
assert(b[1] == t[3]);
}
// nesting
{
Tuple!(Tuple!(int, real), Tuple!(string, "s")) t;
static assert(is(typeof(t[0]) == Tuple!(int, real)));
static assert(is(typeof(t[1]) == Tuple!(string, "s")));
static assert(is(typeof(t[0][0]) == int));
static assert(is(typeof(t[0][1]) == real));
static assert(is(typeof(t[1].s) == string));
t[0] = tuple(10, 20.0L);
t[1].s = "abc";
assert(t[0][0] == 10);
assert(t[0][1] == 20.0L);
assert(t[1].s == "abc");
}
// non-POD
{
static struct S
{
int count;
this(this) { ++count; }
~this() { --count; }
void opAssign(S rhs) { count = rhs.count; }
}
Tuple!(S, S) ss;
Tuple!(S, S) ssCopy = ss;
assert(ssCopy[0].count == 1);
assert(ssCopy[1].count == 1);
ssCopy[1] = ssCopy[0];
assert(ssCopy[1].count == 2);
}
// bug 2800
{
static struct R
{
Tuple!(int, int) _front;
@property ref Tuple!(int, int) front() return { return _front; }
@property bool empty() { return _front[0] >= 10; }
void popFront() { ++_front[0]; }
}
foreach (a; R())
{
static assert(is(typeof(a) == Tuple!(int, int)));
assert(0 <= a[0] && a[0] < 10);
assert(a[1] == 0);
}
}
// Construction with compatible elements
{
auto t1 = Tuple!(int, double)(1, 1);
// 8702
auto t8702a = tuple(tuple(1));
auto t8702b = Tuple!(Tuple!(int))(Tuple!(int)(1));
}
// Construction with compatible tuple
{
Tuple!(int, int) x;
x[0] = 10;
x[1] = 20;
Tuple!(int, "a", double, "b") y = x;
assert(y.a == 10);
assert(y.b == 20);
// incompatible
static assert(!__traits(compiles, Tuple!(int, int)(y)));
}
// 6275
{
const int x = 1;
auto t1 = tuple(x);
alias T = Tuple!(const(int));
auto t2 = T(1);
}
// 9431
{
alias T = Tuple!(int[1][]);
auto t = T([[10]]);
}
// 7666
{
auto tup = tuple(1, "2");
assert(tup.reverse == tuple("2", 1));
}
{
Tuple!(int, "x", string, "y") tup = tuple(1, "2");
auto rev = tup.reverse;
assert(rev == tuple("2", 1));
assert(rev.x == 1 && rev.y == "2");
}
{
Tuple!(wchar, dchar, int, "x", string, "y", char, byte, float) tup;
tup = tuple('a', 'b', 3, "4", 'c', cast(byte) 0x0D, 0.00);
auto rev = tup.reverse;
assert(rev == tuple(0.00, cast(byte) 0x0D, 'c', "4", 3, 'b', 'a'));
assert(rev.x == 3 && rev.y == "4");
}
}
@safe unittest
{
// opEquals
{
struct Equ1 { bool opEquals(Equ1) { return true; } }
auto tm1 = tuple(Equ1.init);
const tc1 = tuple(Equ1.init);
static assert( is(typeof(tm1 == tm1)));
static assert(!is(typeof(tm1 == tc1)));
static assert(!is(typeof(tc1 == tm1)));
static assert(!is(typeof(tc1 == tc1)));
struct Equ2 { bool opEquals(const Equ2) const { return true; } }
auto tm2 = tuple(Equ2.init);
const tc2 = tuple(Equ2.init);
static assert( is(typeof(tm2 == tm2)));
static assert( is(typeof(tm2 == tc2)));
static assert( is(typeof(tc2 == tm2)));
static assert( is(typeof(tc2 == tc2)));
struct Equ3 { bool opEquals(T)(T) { return true; } }
auto tm3 = tuple(Equ3.init); // bugzilla 8686
const tc3 = tuple(Equ3.init);
static assert( is(typeof(tm3 == tm3)));
static assert( is(typeof(tm3 == tc3)));
static assert(!is(typeof(tc3 == tm3)));
static assert(!is(typeof(tc3 == tc3)));
struct Equ4 { bool opEquals(T)(T) const { return true; } }
auto tm4 = tuple(Equ4.init);
const tc4 = tuple(Equ4.init);
static assert( is(typeof(tm4 == tm4)));
static assert( is(typeof(tm4 == tc4)));
static assert( is(typeof(tc4 == tm4)));
static assert( is(typeof(tc4 == tc4)));
}
// opCmp
{
struct Cmp1 { int opCmp(Cmp1) { return 0; } }
auto tm1 = tuple(Cmp1.init);
const tc1 = tuple(Cmp1.init);
static assert( is(typeof(tm1 < tm1)));
static assert(!is(typeof(tm1 < tc1)));
static assert(!is(typeof(tc1 < tm1)));
static assert(!is(typeof(tc1 < tc1)));
struct Cmp2 { int opCmp(const Cmp2) const { return 0; } }
auto tm2 = tuple(Cmp2.init);
const tc2 = tuple(Cmp2.init);
static assert( is(typeof(tm2 < tm2)));
static assert( is(typeof(tm2 < tc2)));
static assert( is(typeof(tc2 < tm2)));
static assert( is(typeof(tc2 < tc2)));
struct Cmp3 { int opCmp(T)(T) { return 0; } }
auto tm3 = tuple(Cmp3.init);
const tc3 = tuple(Cmp3.init);
static assert( is(typeof(tm3 < tm3)));
static assert( is(typeof(tm3 < tc3)));
static assert(!is(typeof(tc3 < tm3)));
static assert(!is(typeof(tc3 < tc3)));
struct Cmp4 { int opCmp(T)(T) const { return 0; } }
auto tm4 = tuple(Cmp4.init);
const tc4 = tuple(Cmp4.init);
static assert( is(typeof(tm4 < tm4)));
static assert( is(typeof(tm4 < tc4)));
static assert( is(typeof(tc4 < tm4)));
static assert( is(typeof(tc4 < tc4)));
}
// Bugzilla 14890
static void test14890(inout int[] dummy)
{
alias V = Tuple!(int, int);
V mv;
const V cv;
immutable V iv;
inout V wv; // OK <- NG
inout const V wcv; // OK <- NG
static foreach (v1; AliasSeq!(mv, cv, iv, wv, wcv))
static foreach (v2; AliasSeq!(mv, cv, iv, wv, wcv))
{
assert(!(v1 < v2));
}
}
{
int[2] ints = [ 1, 2 ];
Tuple!(int, int) t = ints;
assert(t[0] == 1 && t[1] == 2);
Tuple!(long, uint) t2 = ints;
assert(t2[0] == 1 && t2[1] == 2);
}
}
@safe unittest
{
auto t1 = Tuple!(int, "x", string, "y")(1, "a");
assert(t1.x == 1);
assert(t1.y == "a");
void foo(Tuple!(int, string) t2) {}
foo(t1);
Tuple!(int, int)[] arr;
arr ~= tuple(10, 20); // OK
arr ~= Tuple!(int, "x", int, "y")(10, 20); // NG -> OK
static assert(is(typeof(Tuple!(int, "x", string, "y").tupleof) ==
typeof(Tuple!(int, string ).tupleof)));
}
@safe unittest
{
// Bugzilla 10686
immutable Tuple!(int) t1;
auto r1 = t1[0]; // OK
immutable Tuple!(int, "x") t2;
auto r2 = t2[0]; // error
}
@safe unittest
{
import std.exception : assertCTFEable;
// Bugzilla 10218
assertCTFEable!(
{
auto t = tuple(1);
t = tuple(2); // assignment
});
}
@safe unittest
{
class Foo{}
Tuple!(immutable(Foo)[]) a;
}
@safe unittest
{
//Test non-assignable
static struct S
{
int* p;
}
alias IS = immutable S;
static assert(!isAssignable!IS);
auto s = IS.init;
alias TIS = Tuple!IS;
TIS a = tuple(s);
TIS b = a;
alias TISIS = Tuple!(IS, IS);
TISIS d = tuple(s, s);
IS[2] ss;
TISIS e = TISIS(ss);
}
// Bugzilla #9819
@safe unittest
{
alias T = Tuple!(int, "x", double, "foo");
static assert(T.fieldNames[0] == "x");
static assert(T.fieldNames[1] == "foo");
alias Fields = Tuple!(int, "id", string, float);
static assert(Fields.fieldNames == AliasSeq!("id", "", ""));
}
// Bugzilla 13837
@safe unittest
{
// New behaviour, named arguments.
static assert(is(
typeof(tuple!("x")(1)) == Tuple!(int, "x")));
static assert(is(
typeof(tuple!("x")(1.0)) == Tuple!(double, "x")));
static assert(is(
typeof(tuple!("x")("foo")) == Tuple!(string, "x")));
static assert(is(
typeof(tuple!("x", "y")(1, 2.0)) == Tuple!(int, "x", double, "y")));
auto a = tuple!("a", "b", "c")("1", 2, 3.0f);
static assert(is(typeof(a.a) == string));
static assert(is(typeof(a.b) == int));
static assert(is(typeof(a.c) == float));
// Old behaviour, but with explicit type parameters.
static assert(is(
typeof(tuple!(int, double)(1, 2.0)) == Tuple!(int, double)));
static assert(is(
typeof(tuple!(const int)(1)) == Tuple!(const int)));
static assert(is(
typeof(tuple()) == Tuple!()));
// Nonsensical behaviour
static assert(!__traits(compiles, tuple!(1)(2)));
static assert(!__traits(compiles, tuple!("x")(1, 2)));
static assert(!__traits(compiles, tuple!("x", "y")(1)));
static assert(!__traits(compiles, tuple!("x")()));
static assert(!__traits(compiles, tuple!("x", int)(2)));
}
@safe unittest
{
class C {}
Tuple!(Rebindable!(const C)) a;
Tuple!(const C) b;
a = b;
}
@nogc @safe unittest
{
alias T = Tuple!(string, "s");
T x;
x = T.init;
}
@safe unittest
{
import std.format : format, FormatException;
import std.exception : assertThrown;
//enum tupStr = tuple(1, 1.0).toString; // toString is *impure*.
//static assert(tupStr == `Tuple!(int, double)(1, 1)`);
}
// Issue 17803, parte uno
@safe unittest
{
auto a = tuple(3, "foo");
assert(__traits(compiles, { a = (a = a); }));
}
// Ditto
@safe unittest
{
Tuple!(int[]) a, b, c;
a = tuple([0, 1, 2]);
c = b = a;
assert(a[0].length == b[0].length && b[0].length == c[0].length);
assert(a[0].ptr == b[0].ptr && b[0].ptr == c[0].ptr);
}
/**
Constructs a $(LREF Tuple) object instantiated and initialized according to
the given arguments.
Params:
Names = An optional list of strings naming each successive field of the `Tuple`
or a list of types that the elements are being casted to.
For a list of names,
each name matches up with the corresponding field given by `Args`.
A name does not have to be provided for every field, but as
the names must proceed in order, it is not possible to skip
one field and name the next after it.
For a list of types,
there must be exactly as many types as parameters.
*/
template tuple(Names...)
{
/**
Params:
args = Values to initialize the `Tuple` with. The `Tuple`'s type will
be inferred from the types of the values given.
Returns:
A new `Tuple` with its type inferred from the arguments given.
*/
auto tuple(Args...)(Args args)
{
static if (Names.length == 0)
{
// No specified names, just infer types from Args...
return Tuple!Args(args);
}
else static if (!is(typeof(Names[0]) : string))
{
// Names[0] isn't a string, must be explicit types.
return Tuple!Names(args);
}
else
{
// Names[0] is a string, so must be specifying names.
static assert(Names.length == Args.length,
"Insufficient number of names given.");
// Interleave(a, b).and(c, d) == (a, c, b, d)
// This is to get the interleaving of types and names for Tuple
// e.g. Tuple!(int, "x", string, "y")
template Interleave(A...)
{
template and(B...) if (B.length == 1)
{
alias and = AliasSeq!(A[0], B[0]);
}
template and(B...) if (B.length != 1)
{
alias and = AliasSeq!(A[0], B[0],
Interleave!(A[1..$]).and!(B[1..$]));
}
}
return Tuple!(Interleave!(Args).and!(Names))(args);
}
}
}
///
@safe unittest
{
auto value = tuple(5, 6.7, "hello");
assert(value[0] == 5);
assert(value[1] == 6.7);
assert(value[2] == "hello");
// Field names can be provided.
auto entry = tuple!("index", "value")(4, "Hello");
assert(entry.index == 4);
assert(entry.value == "Hello");
}
/**
Returns `true` if and only if `T` is an instance of `std.typecons.Tuple`.
Params:
T = The type to check.
Returns:
true if `T` is a `Tuple` type, false otherwise.
*/
enum isTuple(T) = __traits(compiles,
{
void f(Specs...)(Tuple!Specs tup) {}
f(T.init);
} );
///
@safe unittest
{
static assert(isTuple!(Tuple!()));
static assert(isTuple!(Tuple!(int)));
static assert(isTuple!(Tuple!(int, real, string)));
static assert(isTuple!(Tuple!(int, "x", real, "y")));
static assert(isTuple!(Tuple!(int, Tuple!(real), string)));
}
@safe unittest
{
static assert(isTuple!(const Tuple!(int)));
static assert(isTuple!(immutable Tuple!(int)));
static assert(!isTuple!(int));
static assert(!isTuple!(const int));
struct S {}
static assert(!isTuple!(S));
}
// used by both Rebindable and UnqualRef
private mixin template RebindableCommon(T, U, alias This)
if (is(T == class) || is(T == interface) || isAssociativeArray!T)
{
private union
{
T original;
U stripped;
}
void opAssign(T another) pure nothrow @nogc
{
// If `T` defines `opCast` we must infer the safety
static if (hasMember!(T, "opCast"))
{
// This will allow the compiler to infer the safety of `T.opCast!U`
// without generating any runtime cost
if (false) { stripped = cast(U) another; }
}
() @trusted { stripped = cast(U) another; }();
}
void opAssign(typeof(this) another) @trusted pure nothrow @nogc
{
stripped = another.stripped;
}
static if (is(T == const U) && is(T == const shared U))
{
// safely assign immutable to const / const shared
void opAssign(This!(immutable U) another) @trusted pure nothrow @nogc
{
stripped = another.stripped;
}
}
this(T initializer) pure nothrow @nogc
{
// Infer safety from opAssign
opAssign(initializer);
}
@property inout(T) get() @trusted pure nothrow @nogc inout
{
return original;
}
bool opEquals()(auto ref const(typeof(this)) rhs) const
{
// Must forward explicitly because 'stripped' is part of a union.
// The necessary 'toHash' is forwarded to the class via alias this.
return stripped == rhs.stripped;
}
bool opEquals(const(U) rhs) const
{
return stripped == rhs;
}
alias get this;
}
/**
`Rebindable!(T)` is a simple, efficient wrapper that behaves just
like an object of type `T`, except that you can reassign it to
refer to another object. For completeness, `Rebindable!(T)` aliases
itself away to `T` if `T` is a non-const object type.
You may want to use `Rebindable` when you want to have mutable
storage referring to `const` objects, for example an array of
references that must be sorted in place. `Rebindable` does not
break the soundness of D's type system and does not incur any of the
risks usually associated with `cast`.
Params:
T = An object, interface, array slice type, or associative array type.
*/
template Rebindable(T)
if (is(T == class) || is(T == interface) || isDynamicArray!T || isAssociativeArray!T)
{
static if (is(T == const U, U) || is(T == immutable U, U))
{
static if (isDynamicArray!T)
{
import std.range.primitives : ElementEncodingType;
alias Rebindable = const(ElementEncodingType!T)[];
}
else
{
struct Rebindable
{
mixin RebindableCommon!(T, U, Rebindable);
}
}
}
else
{
alias Rebindable = T;
}
}
///Regular `const` object references cannot be reassigned.
@safe unittest
{
class Widget { int x; int y() @safe const { return x; } }
const a = new Widget;
// Fine
a.y();
// error! can't modify const a
// a.x = 5;
// error! can't modify const a
// a = new Widget;
}
/**
However, `Rebindable!(Widget)` does allow reassignment,
while otherwise behaving exactly like a $(D const Widget).
*/
@safe unittest
{
class Widget { int x; int y() const @safe { return x; } }
auto a = Rebindable!(const Widget)(new Widget);
// Fine
a.y();
// error! can't modify const a
// a.x = 5;
// Fine
a = new Widget;
}
@safe unittest // issue 16054
{
Rebindable!(immutable Object) r;
static assert(__traits(compiles, r.get()));
static assert(!__traits(compiles, &r.get()));
}
@safe unittest
{
class CustomToHash
{
override size_t toHash() const nothrow @trusted { return 42; }
}
Rebindable!(immutable(CustomToHash)) a = new immutable CustomToHash();
assert(a.toHash() == 42, "Rebindable!A should offer toHash()"
~ " by forwarding to A.toHash().");
}
@system unittest // issue 18615: Rebindable!A should use A.opEquals
{
class CustomOpEq
{
int x;
override bool opEquals(Object rhsObj)
{
if (auto rhs = cast(const(CustomOpEq)) rhsObj)
return this.x == rhs.x;
else
return false;
}
}
CustomOpEq a = new CustomOpEq();
CustomOpEq b = new CustomOpEq();
assert(a !is b);
assert(a == b, "a.x == b.x should be true (0 == 0).");
Rebindable!(const(CustomOpEq)) ra = a;
Rebindable!(const(CustomOpEq)) rb = b;
assert(ra !is rb);
assert(ra == rb, "Rebindable should use CustomOpEq's opEquals, not 'is'.");
assert(ra == b, "Rebindable!(someQualifier(A)) should be comparable"
~ " against const(A) via A.opEquals.");
assert(a == rb, "Rebindable!(someQualifier(A)) should be comparable"
~ " against const(A) via A.opEquals.");
b.x = 1;
assert(a != b);
assert(ra != b, "Rebindable!(someQualifier(A)) should be comparable"
~ " against const(A) via A.opEquals.");
assert(a != rb, "Rebindable!(someQualifier(A)) should be comparable"
~ " against const(A) via A.opEquals.");
Rebindable!(const(Object)) o1 = new Object();
Rebindable!(const(Object)) o2 = new Object();
assert(o1 !is o2);
assert(o1 == o1, "When the class doesn't provide its own opEquals,"
~ " Rebindable treats 'a == b' as 'a is b' like Object.opEquals.");
assert(o1 != o2, "When the class doesn't provide its own opEquals,"
~ " Rebindable treats 'a == b' as 'a is b' like Object.opEquals.");
assert(o1 != new Object(), "Rebindable!(const(Object)) should be"
~ " comparable against Object itself and use Object.opEquals.");
}
@safe unittest // issue 18755
{
static class Foo
{
auto opCast(T)() @system immutable pure nothrow
{
*(cast(uint*) 0xdeadbeef) = 0xcafebabe;
return T.init;
}
}
static assert(!__traits(compiles, () @safe {
auto r = Rebindable!(immutable Foo)(new Foo);
}));
static assert(__traits(compiles, () @system {
auto r = Rebindable!(immutable Foo)(new Foo);
}));
}
/**
Convenience function for creating a `Rebindable` using automatic type
inference.
Params:
obj = A reference to an object, interface, associative array, or an array slice
to initialize the `Rebindable` with.
Returns:
A newly constructed `Rebindable` initialized with the given reference.
*/
Rebindable!T rebindable(T)(T obj)
if (is(T == class) || is(T == interface) || isDynamicArray!T || isAssociativeArray!T)
{
typeof(return) ret;
ret = obj;
return ret;
}
///
@system unittest
{
class C
{
int payload;
this(int p) { payload = p; }
}
const c = new C(1);
auto c2 = c.rebindable;
assert(c2.payload == 1);
// passing Rebindable to rebindable
c2 = c2.rebindable;
c2 = new C(2);
assert(c2.payload == 2);
const c3 = c2.get;
assert(c3.payload == 2);
}
/**
This function simply returns the `Rebindable` object passed in. It's useful
in generic programming cases when a given object may be either a regular
`class` or a `Rebindable`.
Params:
obj = An instance of Rebindable!T.
Returns:
`obj` without any modification.
*/
Rebindable!T rebindable(T)(Rebindable!T obj)
{
return obj;
}
// TODO: remove me once the rebindable overloads have been joined
///
@system unittest
{
class C
{
int payload;
this(int p) { payload = p; }
}
const c = new C(1);
auto c2 = c.rebindable;
assert(c2.payload == 1);
// passing Rebindable to rebindable
c2 = c2.rebindable;
assert(c2.payload == 1);
}
@system unittest
{
interface CI { int foo() const; }
class C : CI {
int foo() const { return 42; }
@property int bar() const { return 23; }
}
Rebindable!(C) obj0;
static assert(is(typeof(obj0) == C));
Rebindable!(const(C)) obj1;
static assert(is(typeof(obj1.get) == const(C)), typeof(obj1.get).stringof);
static assert(is(typeof(obj1.stripped) == C));
obj1 = new C;
assert(obj1.get !is null);
obj1 = new const(C);
assert(obj1.get !is null);
Rebindable!(immutable(C)) obj2;
static assert(is(typeof(obj2.get) == immutable(C)));
static assert(is(typeof(obj2.stripped) == C));
obj2 = new immutable(C);
assert(obj1.get !is null);
// test opDot
assert(obj2.foo() == 42);
assert(obj2.bar == 23);
interface I { final int foo() const { return 42; } }
Rebindable!(I) obj3;
static assert(is(typeof(obj3) == I));
Rebindable!(const I) obj4;
static assert(is(typeof(obj4.get) == const I));
static assert(is(typeof(obj4.stripped) == I));
static assert(is(typeof(obj4.foo()) == int));
obj4 = new class I {};
Rebindable!(immutable C) obj5i;
Rebindable!(const C) obj5c;
obj5c = obj5c;
obj5c = obj5i;
obj5i = obj5i;
static assert(!__traits(compiles, obj5i = obj5c));
// Test the convenience functions.
auto obj5convenience = rebindable(obj5i);
assert(obj5convenience is obj5i);
auto obj6 = rebindable(new immutable(C));
static assert(is(typeof(obj6) == Rebindable!(immutable C)));
assert(obj6.foo() == 42);
auto obj7 = rebindable(new C);
CI interface1 = obj7;
auto interfaceRebind1 = rebindable(interface1);
assert(interfaceRebind1.foo() == 42);
const interface2 = interface1;
auto interfaceRebind2 = rebindable(interface2);
assert(interfaceRebind2.foo() == 42);
auto arr = [1,2,3,4,5];
const arrConst = arr;
assert(rebindable(arr) == arr);
assert(rebindable(arrConst) == arr);
// Issue 7654
immutable(char[]) s7654;
Rebindable!(typeof(s7654)) r7654 = s7654;
static foreach (T; AliasSeq!(char, wchar, char, int))
{
static assert(is(Rebindable!(immutable(T[])) == immutable(T)[]));
static assert(is(Rebindable!(const(T[])) == const(T)[]));
static assert(is(Rebindable!(T[]) == T[]));
}
// Issue 12046
static assert(!__traits(compiles, Rebindable!(int[1])));
static assert(!__traits(compiles, Rebindable!(const int[1])));
// Pull request 3341
Rebindable!(immutable int[int]) pr3341 = [123:345];
assert(pr3341[123] == 345);
immutable int[int] pr3341_aa = [321:543];
pr3341 = pr3341_aa;
assert(pr3341[321] == 543);
assert(rebindable(pr3341_aa)[321] == 543);
}
/**
Similar to `Rebindable!(T)` but strips all qualifiers from the reference as
opposed to just constness / immutability. Primary intended use case is with
shared (having thread-local reference to shared class data)
Params:
T = A class or interface type.
*/
template UnqualRef(T)
if (is(T == class) || is(T == interface))
{
static if (is(T == const U, U)
|| is(T == immutable U, U)
|| is(T == shared U, U)
|| is(T == const shared U, U))
{
struct UnqualRef
{
mixin RebindableCommon!(T, U, UnqualRef);
}
}
else
{
alias UnqualRef = T;
}
}
///
@system unittest
{
class Data {}
static shared(Data) a;
static UnqualRef!(shared Data) b;
import core.thread;
auto thread = new core.thread.Thread({
a = new shared Data();
b = new shared Data();
});
thread.start();
thread.join();
assert(a !is null);
assert(b is null);
}
@safe unittest
{
class C { }
alias T = UnqualRef!(const shared C);
static assert(is(typeof(T.stripped) == C));
}
/**
Order the provided members to minimize size while preserving alignment.
Alignment is not always optimal for 80-bit reals, nor for structs declared
as align(1).
Params:
E = A list of the types to be aligned, representing fields
of an aggregate such as a `struct` or `class`.
names = The names of the fields that are to be aligned.
Returns:
A string to be mixed in to an aggregate, such as a `struct` or `class`.
*/
string alignForSize(E...)(const char[][] names...)
{
// Sort all of the members by .alignof.
// BUG: Alignment is not always optimal for align(1) structs
// or 80-bit reals or 64-bit primitives on x86.
// TRICK: Use the fact that .alignof is always a power of 2,
// and maximum 16 on extant systems. Thus, we can perform
// a very limited radix sort.
// Contains the members with .alignof = 64,32,16,8,4,2,1
assert(E.length == names.length,
"alignForSize: There should be as many member names as the types");
string[7] declaration = ["", "", "", "", "", "", ""];
foreach (i, T; E)
{
auto a = T.alignof;
auto k = a >= 64? 0 : a >= 32? 1 : a >= 16? 2 : a >= 8? 3 : a >= 4? 4 : a >= 2? 5 : 6;
declaration[k] ~= T.stringof ~ " " ~ names[i] ~ ";\n";
}
auto s = "";
foreach (decl; declaration)
s ~= decl;
return s;
}
///
@safe unittest
{
struct Banner {
mixin(alignForSize!(byte[6], double)(["name", "height"]));
}
}
@safe unittest
{
enum x = alignForSize!(int[], char[3], short, double[5])("x", "y","z", "w");
struct Foo { int x; }
enum y = alignForSize!(ubyte, Foo, double)("x", "y", "z");
enum passNormalX = x == "double[5] w;\nint[] x;\nshort z;\nchar[3] y;\n";
enum passNormalY = y == "double z;\nFoo y;\nubyte x;\n";
enum passAbnormalX = x == "int[] x;\ndouble[5] w;\nshort z;\nchar[3] y;\n";
enum passAbnormalY = y == "Foo y;\ndouble z;\nubyte x;\n";
// ^ blame http://d.puremagic.com/issues/show_bug.cgi?id=231
static assert(passNormalX || passAbnormalX && double.alignof <= (int[]).alignof);
static assert(passNormalY || passAbnormalY && double.alignof <= int.alignof);
}
// Issue 12914
@safe unittest
{
immutable string[] fieldNames = ["x", "y"];
struct S
{
mixin(alignForSize!(byte, int)(fieldNames));
}
}
/**
Defines a value paired with a distinctive "null" state that denotes
the absence of a value. If default constructed, a $(D
Nullable!T) object starts in the null state. Assigning it renders it
non-null. Calling `nullify` can nullify it again.
Practically `Nullable!T` stores a `T` and a `bool`.
*/
struct Nullable(T)
{
private union DontCallDestructorT
{
T payload;
}
private DontCallDestructorT _value = DontCallDestructorT.init;
private bool _isNull = true;
/**
Constructor initializing `this` with `value`.
Params:
value = The value to initialize this `Nullable` with.
*/
this(inout T value) inout
{
_value.payload = value;
_isNull = false;
}
static if (is(T == struct) && hasElaborateDestructor!T)
{
~this()
{
if (!_isNull)
{
destroy(_value.payload);
}
}
}
/**
If they are both null, then they are equal. If one is null and the other
is not, then they are not equal. If they are both non-null, then they are
equal if their values are equal.
*/
bool opEquals()(auto ref const(typeof(this)) rhs) const
{
if (_isNull)
return rhs._isNull;
if (rhs._isNull)
return false;
return _value.payload == rhs._value.payload;
}
/// Ditto
bool opEquals(U)(auto ref const(U) rhs) const
if (is(typeof(this.get == rhs)))
{
return _isNull ? false : rhs == _value.payload;
}
///
@safe unittest
{
Nullable!int empty;
Nullable!int a = 42;
Nullable!int b = 42;
Nullable!int c = 27;
assert(empty == empty);
assert(empty == Nullable!int.init);
assert(empty != a);
assert(empty != b);
assert(empty != c);
assert(a == b);
assert(a != c);
assert(empty != 42);
assert(a == 42);
assert(c != 42);
}
@safe unittest
{
// Test constness
immutable Nullable!int a = 42;
Nullable!int b = 42;
immutable Nullable!int c = 29;
Nullable!int d = 29;
immutable e = 42;
int f = 29;
assert(a == a);
assert(a == b);
assert(a != c);
assert(a != d);
assert(a == e);
assert(a != f);
// Test rvalue
assert(a == const Nullable!int(42));
assert(a != Nullable!int(29));
}
// Issue 17482
@system unittest
{
import std.variant : Variant;
Nullable!Variant a = Variant(12);
assert(a == 12);
Nullable!Variant e;
assert(e != 12);
}
size_t toHash() const @safe nothrow
{
static if (__traits(compiles, .hashOf(_value.payload)))
return _isNull ? 0 : .hashOf(_value.payload);
else
// Workaround for when .hashOf is not both @safe and nothrow.
return _isNull ? 0 : typeid(T).getHash(&_value.payload);
}
/**
* Gives the string `"Nullable.null"` if `isNull` is `true`. Otherwise, the
* result is equivalent to calling $(REF formattedWrite, std,format) on the
* underlying value.
*
* Params:
* writer = A `char` accepting
* $(REF_ALTTEXT output range, isOutputRange, std, range, primitives)
* fmt = A $(REF FormatSpec, std,format) which is used to represent
* the value if this Nullable is not null
* Returns:
* A `string` if `writer` and `fmt` are not set; `void` otherwise.
*/
string toString()
{
import std.array : appender;
auto app = appender!string();
auto spec = singleSpec("%s");
toString(app, spec);
return app.data;
}
/// ditto
void toString(W)(ref W writer, const ref FormatSpec!char fmt)
if (isOutputRange!(W, char))
{
import std.range.primitives : put;
if (isNull)
put(writer, "Nullable.null");
else
formatValue(writer, _value.payload, fmt);
}
//@@@DEPRECATED_2.086@@@
deprecated("To be removed after 2.086. Please use the output range overload instead.")
void toString()(scope void delegate(const(char)[]) sink, const ref FormatSpec!char fmt)
{
if (isNull)
{
sink.formatValue("Nullable.null", fmt);
}
else
{
sink.formatValue(_value.payload, fmt);
}
}
// Issue 14940
//@@@DEPRECATED_2.086@@@
deprecated("To be removed after 2.086. Please use the output range overload instead.")
void toString()(scope void delegate(const(char)[]) @safe sink, const ref FormatSpec!char fmt)
{
if (isNull)
{
sink.formatValue("Nullable.null", fmt);
}
else
{
sink.formatValue(_value.payload, fmt);
}
}
/**
Check if `this` is in the null state.
Returns:
true $(B iff) `this` is in the null state, otherwise false.
*/
@property bool isNull() const @safe pure nothrow
{
return _isNull;
}
///
@safe unittest
{
Nullable!int ni;
assert(ni.isNull);
ni = 0;
assert(!ni.isNull);
}
// Issue 14940
@safe unittest
{
import std.array : appender;
import std.format : formattedWrite;
auto app = appender!string();
Nullable!int a = 1;
formattedWrite(app, "%s", a);
assert(app.data == "1");
}
/**
Forces `this` to the null state.
*/
void nullify()()
{
static if (is(T == class) || is(T == interface))
_value.payload = null;
else
.destroy(_value.payload);
_isNull = true;
}
///
@safe unittest
{
Nullable!int ni = 0;
assert(!ni.isNull);
ni.nullify();
assert(ni.isNull);
}
/**
Assigns `value` to the internally-held state. If the assignment
succeeds, `this` becomes non-null.
Params:
value = A value of type `T` to assign to this `Nullable`.
*/
void opAssign()(T value)
{
import std.algorithm.mutation : moveEmplace, move;
// the lifetime of the value in copy shall be managed by
// this Nullable, so we must avoid calling its destructor.
auto copy = DontCallDestructorT(value);
if (_isNull)
{
// trusted since payload is known to be T.init here.
() @trusted { moveEmplace(copy.payload, _value.payload); }();
}
else
{
move(copy.payload, _value.payload);
}
_isNull = false;
}
/**
If this `Nullable` wraps a type that already has a null value
(such as a pointer), then assigning the null value to this
`Nullable` is no different than assigning any other value of
type `T`, and the resulting code will look very strange. It
is strongly recommended that this be avoided by instead using
the version of `Nullable` that takes an additional `nullValue`
template argument.
*/
@safe unittest
{
//Passes
Nullable!(int*) npi;
assert(npi.isNull);
//Passes?!
npi = null;
assert(!npi.isNull);
}
/**
Gets the value if not null. If `this` is in the null state, and the optional
parameter `fallback` was provided, it will be returned. Without `fallback`,
calling `get` with a null state is invalid.
This function is also called for the implicit conversion to `T`.
Params:
fallback = the value to return in case the `Nullable` is null.
Returns:
The value held internally by this `Nullable`.
*/
@property ref inout(T) get() inout @safe pure nothrow
{
enum message = "Called `get' on null Nullable!" ~ T.stringof ~ ".";
assert(!isNull, message);
return _value.payload;
}
/// ditto
@property get(U)(inout(U) fallback) inout @safe pure nothrow
{
return isNull ? fallback : _value.payload;
}
///
@system unittest
{
import core.exception : AssertError;
import std.exception : assertThrown, assertNotThrown;
Nullable!int ni;
int i = 42;
//`get` is implicitly called. Will throw
//an AssertError in non-release mode
assertThrown!AssertError(i = ni);
assert(i == 42);
ni = 5;
assertNotThrown!AssertError(i = ni);
assert(i == 5);
}
///
@safe pure nothrow unittest
{
int i = 42;
Nullable!int ni2;
int x = ni2.get(i);
assert(x == i);
ni2 = 7;
x = ni2.get(i);
assert(x == 7);
}
/**
Implicitly converts to `T`.
`this` must not be in the null state.
*/
alias get this;
}
/// ditto
auto nullable(T)(T t)
{
return Nullable!T(t);
}
///
@safe unittest
{
struct CustomerRecord
{
string name;
string address;
int customerNum;
}
Nullable!CustomerRecord getByName(string name)
{
//A bunch of hairy stuff
return Nullable!CustomerRecord.init;
}
auto queryResult = getByName("Doe, John");
if (!queryResult.isNull)
{
//Process Mr. Doe's customer record
auto address = queryResult.address;
auto customerNum = queryResult.customerNum;
//Do some things with this customer's info
}
else
{
//Add the customer to the database
}
}
///
@system unittest
{
import std.exception : assertThrown;
auto a = 42.nullable;
assert(!a.isNull);
assert(a.get == 42);
a.nullify();
assert(a.isNull);
assertThrown!Throwable(a.get);
}
@system unittest
{
import std.exception : assertThrown;
Nullable!int a;
assert(a.isNull);
assertThrown!Throwable(a.get);
a = 5;
assert(!a.isNull);
assert(a == 5);
assert(a != 3);
assert(a.get != 3);
a.nullify();
assert(a.isNull);
a = 3;
assert(a == 3);
a *= 6;
assert(a == 18);
a = a;
assert(a == 18);
a.nullify();
assertThrown!Throwable(a += 2);
}
@safe unittest
{
auto k = Nullable!int(74);
assert(k == 74);
k.nullify();
assert(k.isNull);
}
@safe unittest
{
static int f(scope const Nullable!int x) {
return x.isNull ? 42 : x.get;
}
Nullable!int a;
assert(f(a) == 42);
a = 8;
assert(f(a) == 8);
a.nullify();
assert(f(a) == 42);
}
@system unittest
{
import std.exception : assertThrown;
static struct S { int x; }
Nullable!S s;
assert(s.isNull);
s = S(6);
assert(s == S(6));
assert(s != S(0));
assert(s.get != S(0));
s.x = 9190;
assert(s.x == 9190);
s.nullify();
assertThrown!Throwable(s.x = 9441);
}
@safe unittest
{
// Ensure Nullable can be used in pure/nothrow/@safe environment.
function() @safe pure nothrow
{
Nullable!int n;
assert(n.isNull);
n = 4;
assert(!n.isNull);
assert(n == 4);
n.nullify();
assert(n.isNull);
}();
}
@system unittest
{
// Ensure Nullable can be used when the value is not pure/nothrow/@safe
static struct S
{
int x;
this(this) @system {}
}
Nullable!S s;
assert(s.isNull);
s = S(5);
assert(!s.isNull);
assert(s.x == 5);
s.nullify();
assert(s.isNull);
}
@safe unittest
{
// Bugzilla 9404
alias N = Nullable!int;
void foo(N a)
{
N b;
b = a; // `N b = a;` works fine
}
N n;
foo(n);
}
@safe unittest
{
//Check nullable immutable is constructable
{
auto a1 = Nullable!(immutable int)();
auto a2 = Nullable!(immutable int)(1);
auto i = a2.get;
}
//Check immutable nullable is constructable
{
auto a1 = immutable (Nullable!int)();
auto a2 = immutable (Nullable!int)(1);
auto i = a2.get;
}
}
@safe unittest
{
alias NInt = Nullable!int;
//Construct tests
{
//from other Nullable null
NInt a1;
NInt b1 = a1;
assert(b1.isNull);
//from other Nullable non-null
NInt a2 = NInt(1);
NInt b2 = a2;
assert(b2 == 1);
//Construct from similar nullable
auto a3 = immutable(NInt)();
NInt b3 = a3;
assert(b3.isNull);
}
//Assign tests
{
//from other Nullable null
NInt a1;
NInt b1;
b1 = a1;
assert(b1.isNull);
//from other Nullable non-null
NInt a2 = NInt(1);
NInt b2;
b2 = a2;
assert(b2 == 1);
//Construct from similar nullable
auto a3 = immutable(NInt)();
NInt b3 = a3;
b3 = a3;
assert(b3.isNull);
}
}
@safe unittest
{
//Check nullable is nicelly embedable in a struct
static struct S1
{
Nullable!int ni;
}
static struct S2 //inspired from 9404
{
Nullable!int ni;
this(S2 other)
{
ni = other.ni;
}
void opAssign(S2 other)
{
ni = other.ni;
}
}
static foreach (S; AliasSeq!(S1, S2))
{{
S a;
S b = a;
S c;
c = a;
}}
}
@system unittest
{
// Bugzilla 10268
import std.json;
JSONValue value = null;
auto na = Nullable!JSONValue(value);
struct S1 { int val; }
struct S2 { int* val; }
struct S3 { immutable int* val; }
{
auto sm = S1(1);
immutable si = immutable S1(1);
auto x1 = Nullable!S1(sm);
auto x2 = immutable Nullable!S1(sm);
auto x3 = Nullable!S1(si);
auto x4 = immutable Nullable!S1(si);
assert(x1.val == 1);
assert(x2.val == 1);
assert(x3.val == 1);
assert(x4.val == 1);
}
auto nm = 10;
immutable ni = 10;
{
auto sm = S2(&nm);
immutable si = immutable S2(&ni);
auto x1 = Nullable!S2(sm);
static assert(!__traits(compiles, { auto x2 = immutable Nullable!S2(sm); }));
static assert(!__traits(compiles, { auto x3 = Nullable!S2(si); }));
auto x4 = immutable Nullable!S2(si);
assert(*x1.val == 10);
assert(*x4.val == 10);
}
{
auto sm = S3(&ni);
immutable si = immutable S3(&ni);
auto x1 = Nullable!S3(sm);
auto x2 = immutable Nullable!S3(sm);
auto x3 = Nullable!S3(si);
auto x4 = immutable Nullable!S3(si);
assert(*x1.val == 10);
assert(*x2.val == 10);
assert(*x3.val == 10);
assert(*x4.val == 10);
}
}
@safe unittest
{
// Bugzila 10357
import std.datetime;
Nullable!SysTime time = SysTime(0);
}
@system unittest
{
import std.conv : to;
import std.array;
// Bugzilla 10915
Appender!string buffer;
Nullable!int ni;
assert(ni.to!string() == "Nullable.null");
struct Test { string s; }
alias NullableTest = Nullable!Test;
NullableTest nt = Test("test");
// test output range version
assert(nt.to!string() == `Test("test")`);
// test appender version
assert(nt.toString() == `Test("test")`);
NullableTest ntn = Test("null");
assert(ntn.to!string() == `Test("null")`);
class TestToString
{
double d;
this (double d)
{
this.d = d;
}
override string toString()
{
return d.to!string();
}
}
Nullable!TestToString ntts = new TestToString(2.5);
assert(ntts.to!string() == "2.5");
}
// Bugzilla 14477
@safe unittest
{
static struct DisabledDefaultConstructor
{
@disable this();
this(int i) { }
}
Nullable!DisabledDefaultConstructor var;
var = DisabledDefaultConstructor(5);
var.nullify;
}
// Issue 17440
@system unittest
{
static interface I { }
static class C : I
{
int canary;
~this()
{
canary = 0x5050DEAD;
}
}
auto c = new C;
c.canary = 0xA71FE;
auto nc = nullable(c);
nc.nullify;
assert(c.canary == 0xA71FE);
I i = c;
auto ni = nullable(i);
ni.nullify;
assert(c.canary == 0xA71FE);
}
// Regression test for issue 18539
@safe unittest
{
import std.math : approxEqual;
auto foo = nullable(2.0);
auto bar = nullable(2.0);
assert(foo.approxEqual(bar));
}
// bugzilla issue 19037
@safe unittest
{
import std.datetime : SysTime;
struct Test
{
bool b;
nothrow invariant { assert(b == true); }
SysTime _st;
static bool destroyed;
@disable this();
this(bool b) { this.b = b; }
~this() @safe { destroyed = true; }
// mustn't call opAssign on Test.init in Nullable!Test, because the invariant
// will be called before opAssign on the Test.init that is in Nullable
// and Test.init violates its invariant.
void opAssign(Test rhs) @safe { assert(false); }
}
{
Nullable!Test nt;
nt = Test(true);
// destroy value
Test.destroyed = false;
nt.nullify;
assert(Test.destroyed);
Test.destroyed = false;
}
// don't run destructor on T.init in Nullable on scope exit!
assert(!Test.destroyed);
}
// check that the contained type's destructor is called on assignment
@system unittest
{
struct S
{
// can't be static, since we need a specific value's pointer
bool* destroyedRef;
~this()
{
if (this.destroyedRef)
{
*this.destroyedRef = true;
}
}
}
Nullable!S ns;
bool destroyed;
ns = S(&destroyed);
// reset from rvalue destruction in Nullable's opAssign
destroyed = false;
// overwrite Nullable
ns = S(null);
// the original S should be destroyed.
assert(destroyed == true);
}
// check that the contained type's destructor is still called when required
@system unittest
{
bool destructorCalled = false;
struct S
{
bool* destroyed;
~this() { *this.destroyed = true; }
}
{
Nullable!S ns;
}
assert(!destructorCalled);
{
Nullable!S ns = Nullable!S(S(&destructorCalled));
destructorCalled = false; // reset after S was destroyed in the NS constructor
}
assert(destructorCalled);
}
// check that toHash on Nullable is forwarded to the contained type
@system unittest
{
struct S
{
size_t toHash() const @safe pure nothrow { return 5; }
}
Nullable!S s1 = S();
Nullable!S s2 = Nullable!S();
assert(typeid(Nullable!S).getHash(&s1) == 5);
assert(typeid(Nullable!S).getHash(&s2) == 0);
}
/**
Just like `Nullable!T`, except that the null state is defined as a
particular value. For example, $(D Nullable!(uint, uint.max)) is an
`uint` that sets aside the value `uint.max` to denote a null
state. $(D Nullable!(T, nullValue)) is more storage-efficient than $(D
Nullable!T) because it does not need to store an extra `bool`.
Params:
T = The wrapped type for which Nullable provides a null value.
nullValue = The null value which denotes the null state of this
`Nullable`. Must be of type `T`.
*/
struct Nullable(T, T nullValue)
{
private T _value = nullValue;
/**
Constructor initializing `this` with `value`.
Params:
value = The value to initialize this `Nullable` with.
*/
this(T value)
{
_value = value;
}
template toString()
{
import std.format : FormatSpec, formatValue;
// Needs to be a template because of DMD @@BUG@@ 13737.
void toString()(scope void delegate(const(char)[]) sink, const ref FormatSpec!char fmt)
{
if (isNull)
{
sink.formatValue("Nullable.null", fmt);
}
else
{
sink.formatValue(_value, fmt);
}
}
}
/**
Check if `this` is in the null state.
Returns:
true $(B iff) `this` is in the null state, otherwise false.
*/
@property bool isNull() const
{
//Need to use 'is' if T is a nullable type and
//nullValue is null, or it's a compiler error
static if (is(CommonType!(T, typeof(null)) == T) && nullValue is null)
{
return _value is nullValue;
}
//Need to use 'is' if T is a float type
//because NaN != NaN
else static if (isFloatingPoint!T)
{
return _value is nullValue;
}
else
{
return _value == nullValue;
}
}
///
@safe unittest
{
Nullable!(int, -1) ni;
//Initialized to "null" state
assert(ni.isNull);
ni = 0;
assert(!ni.isNull);
}
// https://issues.dlang.org/show_bug.cgi?id=11135
// disable test until https://issues.dlang.org/show_bug.cgi?id=15316 gets fixed
version (none) @system unittest
{
static foreach (T; AliasSeq!(float, double, real))
{{
Nullable!(T, T.init) nf;
//Initialized to "null" state
assert(nf.isNull);
assert(nf is typeof(nf).init);
nf = 0;
assert(!nf.isNull);
nf.nullify();
assert(nf.isNull);
}}
}
/**
Forces `this` to the null state.
*/
void nullify()()
{
_value = nullValue;
}
///
@safe unittest
{
Nullable!(int, -1) ni = 0;
assert(!ni.isNull);
ni = -1;
assert(ni.isNull);
}
/**
Assigns `value` to the internally-held state. If the assignment
succeeds, `this` becomes non-null. No null checks are made. Note
that the assignment may leave `this` in the null state.
Params:
value = A value of type `T` to assign to this `Nullable`.
If it is `nullvalue`, then the internal state of
this `Nullable` will be set to null.
*/
void opAssign()(T value)
{
import std.algorithm.mutation : swap;
swap(value, _value);
}
/**
If this `Nullable` wraps a type that already has a null value
(such as a pointer), and that null value is not given for
`nullValue`, then assigning the null value to this `Nullable`
is no different than assigning any other value of type `T`,
and the resulting code will look very strange. It is strongly
recommended that this be avoided by using `T`'s "built in"
null value for `nullValue`.
*/
@system unittest
{
//Passes
enum nullVal = cast(int*) 0xCAFEBABE;
Nullable!(int*, nullVal) npi;
assert(npi.isNull);
//Passes?!
npi = null;
assert(!npi.isNull);
}
/**
Gets the value. `this` must not be in the null state.
This function is also called for the implicit conversion to `T`.
Preconditions: `isNull` must be `false`.
Returns:
The value held internally by this `Nullable`.
*/
@property ref inout(T) get() inout
{
//@@@6169@@@: We avoid any call that might evaluate nullValue's %s,
//Because it might messup get's purity and safety inference.
enum message = "Called `get' on null Nullable!(" ~ T.stringof ~ ",nullValue).";
assert(!isNull, message);
return _value;
}
///
@system unittest
{
import std.exception : assertThrown, assertNotThrown;
Nullable!(int, -1) ni;
//`get` is implicitly called. Will throw
//an error in non-release mode
assertThrown!Throwable(ni == 0);
ni = 0;
assertNotThrown!Throwable(ni == 0);
}
/**
Implicitly converts to `T`.
`this` must not be in the null state.
*/
alias get this;
}
/// ditto
auto nullable(alias nullValue, T)(T t)
if (is (typeof(nullValue) == T))
{
return Nullable!(T, nullValue)(t);
}
///
@safe unittest
{
Nullable!(size_t, size_t.max) indexOf(string[] haystack, string needle)
{
//Find the needle, returning -1 if not found
return Nullable!(size_t, size_t.max).init;
}
void sendLunchInvite(string name)
{
}
//It's safer than C...
auto coworkers = ["Jane", "Jim", "Marry", "Fred"];
auto pos = indexOf(coworkers, "Bob");
if (!pos.isNull)
{
//Send Bob an invitation to lunch
sendLunchInvite(coworkers[pos]);
}
else
{
//Bob not found; report the error
}
//And there's no overhead
static assert(Nullable!(size_t, size_t.max).sizeof == size_t.sizeof);
}
///
@system unittest
{
import std.exception : assertThrown;
Nullable!(int, int.min) a;
assert(a.isNull);
assertThrown!Throwable(a.get);
a = 5;
assert(!a.isNull);
assert(a == 5);
static assert(a.sizeof == int.sizeof);
}
///
@safe unittest
{
auto a = nullable!(int.min)(8);
assert(a == 8);
a.nullify();
assert(a.isNull);
}
@safe unittest
{
static int f(scope const Nullable!(int, int.min) x) {
return x.isNull ? 42 : x.get;
}
Nullable!(int, int.min) a;
assert(f(a) == 42);
a = 8;
assert(f(a) == 8);
a.nullify();
assert(f(a) == 42);
}
@safe unittest
{
// Ensure Nullable can be used in pure/nothrow/@safe environment.
function() @safe pure nothrow
{
Nullable!(int, int.min) n;
assert(n.isNull);
n = 4;
assert(!n.isNull);
assert(n == 4);
n.nullify();
assert(n.isNull);
}();
}
@system unittest
{
// Ensure Nullable can be used when the value is not pure/nothrow/@system
static struct S
{
int x;
bool opEquals(const S s) const @system { return s.x == x; }
}
Nullable!(S, S(711)) s;
assert(s.isNull);
s = S(5);
assert(!s.isNull);
assert(s.x == 5);
s.nullify();
assert(s.isNull);
}
@safe unittest
{
//Check nullable is nicelly embedable in a struct
static struct S1
{
Nullable!(int, 0) ni;
}
static struct S2 //inspired from 9404
{
Nullable!(int, 0) ni;
this(S2 other)
{
ni = other.ni;
}
void opAssign(S2 other)
{
ni = other.ni;
}
}
static foreach (S; AliasSeq!(S1, S2))
{{
S a;
S b = a;
S c;
c = a;
}}
}
@system unittest
{
import std.conv : to;
// Bugzilla 10915
Nullable!(int, 1) ni = 1;
assert(ni.to!string() == "Nullable.null");
struct Test { string s; }
alias NullableTest = Nullable!(Test, Test("null"));
NullableTest nt = Test("test");
assert(nt.to!string() == `Test("test")`);
NullableTest ntn = Test("null");
assert(ntn.to!string() == "Nullable.null");
class TestToString
{
double d;
this(double d)
{
this.d = d;
}
override string toString()
{
return d.to!string();
}
}
alias NullableTestToString = Nullable!(TestToString, null);
NullableTestToString ntts = new TestToString(2.5);
assert(ntts.to!string() == "2.5");
}
// apply
/**
Unpacks the content of a `Nullable`, performs an operation and packs it again. Does nothing if isNull.
When called on a `Nullable`, `apply` will unpack the value contained in the `Nullable`,
pass it to the function you provide and wrap the result in another `Nullable` (if necessary).
If the `Nullable` is null, `apply` will return null itself.
Params:
t = a `Nullable`
fun = a function operating on the content of the nullable
Returns:
`fun(t.get).nullable` if `!t.isNull`, else `Nullable.init`.
See also:
$(HTTPS en.wikipedia.org/wiki/Monad_(functional_programming)#The_Maybe_monad, The `Maybe` monad)
*/
template apply(alias fun)
{
import std.functional : unaryFun;
auto apply(T)(auto ref T t)
if (isInstanceOf!(Nullable, T) && is(typeof(unaryFun!fun(T.init.get))))
{
alias FunType = typeof(unaryFun!fun(T.init.get));
enum MustWrapReturn = !isInstanceOf!(Nullable, FunType);
static if (MustWrapReturn)
{
alias ReturnType = Nullable!FunType;
}
else
{
alias ReturnType = FunType;
}
if (!t.isNull)
{
static if (MustWrapReturn)
{
return fun(t.get).nullable;
}
else
{
return fun(t.get);
}
}
else
{
return ReturnType.init;
}
}
}
///
nothrow pure @nogc @safe unittest
{
alias toFloat = i => cast(float) i;
Nullable!int sample;
// apply(null) results in a null `Nullable` of the function's return type.
Nullable!float f = sample.apply!toFloat;
assert(sample.isNull && f.isNull);
sample = 3;
// apply(non-null) calls the function and wraps the result in a `Nullable`.
f = sample.apply!toFloat;
assert(!sample.isNull && !f.isNull);
assert(f.get == 3.0f);
}
///
nothrow pure @nogc @safe unittest
{
alias greaterThree = i => (i > 3) ? i.nullable : Nullable!(typeof(i)).init;
Nullable!int sample;
// when the function already returns a `Nullable`, that `Nullable` is not wrapped.
auto result = sample.apply!greaterThree;
assert(sample.isNull && result.isNull);
// The function may decide to return a null `Nullable`.
sample = 3;
result = sample.apply!greaterThree;
assert(!sample.isNull && result.isNull);
// Or it may return a value already wrapped in a `Nullable`.
sample = 4;
result = sample.apply!greaterThree;
assert(!sample.isNull && !result.isNull);
assert(result.get == 4);
}
/**
Just like `Nullable!T`, except that the object refers to a value
sitting elsewhere in memory. This makes assignments overwrite the
initially assigned value. Internally `NullableRef!T` only stores a
pointer to `T` (i.e., $(D Nullable!T.sizeof == (T*).sizeof)).
*/
struct NullableRef(T)
{
private T* _value;
/**
Constructor binding `this` to `value`.
Params:
value = The value to bind to.
*/
this(T* value) @safe pure nothrow
{
_value = value;
}
template toString()
{
import std.format : FormatSpec, formatValue;
// Needs to be a template because of DMD @@BUG@@ 13737.
void toString()(scope void delegate(const(char)[]) sink, const ref FormatSpec!char fmt)
{
if (isNull)
{
sink.formatValue("Nullable.null", fmt);
}
else
{
sink.formatValue(*_value, fmt);
}
}
}
/**
Binds the internal state to `value`.
Params:
value = A pointer to a value of type `T` to bind this `NullableRef` to.
*/
void bind(T* value) @safe pure nothrow
{
_value = value;
}
///
@safe unittest
{
NullableRef!int nr = new int(42);
assert(nr == 42);
int* n = new int(1);
nr.bind(n);
assert(nr == 1);
}
/**
Returns `true` if and only if `this` is in the null state.
Returns:
true if `this` is in the null state, otherwise false.
*/
@property bool isNull() const @safe pure nothrow
{
return _value is null;
}
///
@safe unittest
{
NullableRef!int nr;
assert(nr.isNull);
int* n = new int(42);
nr.bind(n);
assert(!nr.isNull && nr == 42);
}
/**
Forces `this` to the null state.
*/
void nullify() @safe pure nothrow
{
_value = null;
}
///
@safe unittest
{
NullableRef!int nr = new int(42);
assert(!nr.isNull);
nr.nullify();
assert(nr.isNull);
}
/**
Assigns `value` to the internally-held state.
Params:
value = A value of type `T` to assign to this `NullableRef`.
If the internal state of this `NullableRef` has not
been initialized, an error will be thrown in
non-release mode.
*/
void opAssign()(T value)
if (isAssignable!T) //@@@9416@@@
{
enum message = "Called `opAssign' on null NullableRef!" ~ T.stringof ~ ".";
assert(!isNull, message);
*_value = value;
}
///
@system unittest
{
import std.exception : assertThrown, assertNotThrown;
NullableRef!int nr;
assert(nr.isNull);
assertThrown!Throwable(nr = 42);
nr.bind(new int(0));
assert(!nr.isNull);
assertNotThrown!Throwable(nr = 42);
assert(nr == 42);
}
/**
Gets the value. `this` must not be in the null state.
This function is also called for the implicit conversion to `T`.
*/
@property ref inout(T) get() inout @safe pure nothrow
{
enum message = "Called `get' on null NullableRef!" ~ T.stringof ~ ".";
assert(!isNull, message);
return *_value;
}
///
@system unittest
{
import std.exception : assertThrown, assertNotThrown;
NullableRef!int nr;
//`get` is implicitly called. Will throw
//an error in non-release mode
assertThrown!Throwable(nr == 0);
nr.bind(new int(0));
assertNotThrown!Throwable(nr == 0);
}
/**
Implicitly converts to `T`.
`this` must not be in the null state.
*/
alias get this;
}
/// ditto
auto nullableRef(T)(T* t)
{
return NullableRef!T(t);
}
///
@system unittest
{
import std.exception : assertThrown;
int x = 5, y = 7;
auto a = nullableRef(&x);
assert(!a.isNull);
assert(a == 5);
assert(x == 5);
a = 42;
assert(x == 42);
assert(!a.isNull);
assert(a == 42);
a.nullify();
assert(x == 42);
assert(a.isNull);
assertThrown!Throwable(a.get);
assertThrown!Throwable(a = 71);
a.bind(&y);
assert(a == 7);
y = 135;
assert(a == 135);
}
@system unittest
{
static int f(scope const NullableRef!int x) {
return x.isNull ? 42 : x.get;
}
int x = 5;
auto a = nullableRef(&x);
assert(f(a) == 5);
a.nullify();
assert(f(a) == 42);
}
@safe unittest
{
// Ensure NullableRef can be used in pure/nothrow/@safe environment.
function() @safe pure nothrow
{
auto storage = new int;
*storage = 19902;
NullableRef!int n;
assert(n.isNull);
n.bind(storage);
assert(!n.isNull);
assert(n == 19902);
n = 2294;
assert(n == 2294);
assert(*storage == 2294);
n.nullify();
assert(n.isNull);
}();
}
@system unittest
{
// Ensure NullableRef can be used when the value is not pure/nothrow/@safe
static struct S
{
int x;
this(this) @system {}
bool opEquals(const S s) const @system { return s.x == x; }
}
auto storage = S(5);
NullableRef!S s;
assert(s.isNull);
s.bind(&storage);
assert(!s.isNull);
assert(s.x == 5);
s.nullify();
assert(s.isNull);
}
@safe unittest
{
//Check nullable is nicelly embedable in a struct
static struct S1
{
NullableRef!int ni;
}
static struct S2 //inspired from 9404
{
NullableRef!int ni;
this(S2 other)
{
ni = other.ni;
}
void opAssign(S2 other)
{
ni = other.ni;
}
}
static foreach (S; AliasSeq!(S1, S2))
{{
S a;
S b = a;
S c;
c = a;
}}
}
@system unittest
{
import std.conv : to;
// Bugzilla 10915
NullableRef!int nri;
assert(nri.to!string() == "Nullable.null");
struct Test
{
string s;
}
NullableRef!Test nt = new Test("test");
assert(nt.to!string() == `Test("test")`);
class TestToString
{
double d;
this(double d)
{
this.d = d;
}
override string toString()
{
return d.to!string();
}
}
TestToString tts = new TestToString(2.5);
NullableRef!TestToString ntts = &tts;
assert(ntts.to!string() == "2.5");
}
/**
`BlackHole!Base` is a subclass of `Base` which automatically implements
all abstract member functions in `Base` as do-nothing functions. Each
auto-implemented function just returns the default value of the return type
without doing anything.
The name came from
$(HTTP search.cpan.org/~sburke/Class-_BlackHole-0.04/lib/Class/_BlackHole.pm, Class::_BlackHole)
Perl module by Sean M. Burke.
Params:
Base = A non-final class for `BlackHole` to inherit from.
See_Also:
$(LREF AutoImplement), $(LREF generateEmptyFunction)
*/
alias BlackHole(Base) = AutoImplement!(Base, generateEmptyFunction, isAbstractFunction);
///
@system unittest
{
import std.math : isNaN;
static abstract class C
{
int m_value;
this(int v) { m_value = v; }
int value() @property { return m_value; }
abstract real realValue() @property;
abstract void doSomething();
}
auto c = new BlackHole!C(42);
assert(c.value == 42);
// Returns real.init which is NaN
assert(c.realValue.isNaN);
// Abstract functions are implemented as do-nothing
c.doSomething();
}
@system unittest
{
import std.math : isNaN;
// return default
{
interface I_1 { real test(); }
auto o = new BlackHole!I_1;
assert(o.test().isNaN()); // NaN
}
// doc example
{
static class C
{
int m_value;
this(int v) { m_value = v; }
int value() @property { return m_value; }
abstract real realValue() @property;
abstract void doSomething();
}
auto c = new BlackHole!C(42);
assert(c.value == 42);
assert(c.realValue.isNaN); // NaN
c.doSomething();
}
// Bugzilla 12058
interface Foo
{
inout(Object) foo() inout;
}
BlackHole!Foo o;
}
/**
`WhiteHole!Base` is a subclass of `Base` which automatically implements
all abstract member functions as functions that always fail. These functions
simply throw an `Error` and never return. `Whitehole` is useful for
trapping the use of class member functions that haven't been implemented.
The name came from
$(HTTP search.cpan.org/~mschwern/Class-_WhiteHole-0.04/lib/Class/_WhiteHole.pm, Class::_WhiteHole)
Perl module by Michael G Schwern.
Params:
Base = A non-final class for `WhiteHole` to inherit from.
See_Also:
$(LREF AutoImplement), $(LREF generateAssertTrap)
*/
alias WhiteHole(Base) = AutoImplement!(Base, generateAssertTrap, isAbstractFunction);
///
@system unittest
{
import std.exception : assertThrown;
static class C
{
abstract void notYetImplemented();
}
auto c = new WhiteHole!C;
assertThrown!NotImplementedError(c.notYetImplemented()); // throws an Error
}
// / ditto
class NotImplementedError : Error
{
this(string method)
{
super(method ~ " is not implemented");
}
}
@system unittest
{
import std.exception : assertThrown;
// nothrow
{
interface I_1
{
void foo();
void bar() nothrow;
}
auto o = new WhiteHole!I_1;
assertThrown!NotImplementedError(o.foo());
assertThrown!NotImplementedError(o.bar());
}
// doc example
{
static class C
{
abstract void notYetImplemented();
}
auto c = new WhiteHole!C;
try
{
c.notYetImplemented();
assert(0);
}
catch (Error e) {}
}
}
/**
`AutoImplement` automatically implements (by default) all abstract member
functions in the class or interface `Base` in specified way.
The second version of `AutoImplement` automatically implements
`Interface`, while deriving from `BaseClass`.
Params:
how = template which specifies _how functions will be implemented/overridden.
Two arguments are passed to `how`: the type `Base` and an alias
to an implemented function. Then `how` must return an implemented
function body as a string.
The generated function body can use these keywords:
$(UL
$(LI `a0`, `a1`, …: arguments passed to the function;)
$(LI `args`: a tuple of the arguments;)
$(LI `self`: an alias to the function itself;)
$(LI `parent`: an alias to the overridden function (if any).)
)
You may want to use templated property functions (instead of Implicit
Template Properties) to generate complex functions:
--------------------
// Prints log messages for each call to overridden functions.
string generateLogger(C, alias fun)() @property
{
import std.traits;
enum qname = C.stringof ~ "." ~ __traits(identifier, fun);
string stmt;
stmt ~= q{ struct Importer { import std.stdio; } };
stmt ~= `Importer.writeln("Log: ` ~ qname ~ `(", args, ")");`;
static if (!__traits(isAbstractFunction, fun))
{
static if (is(ReturnType!fun == void))
stmt ~= q{ parent(args); };
else
stmt ~= q{
auto r = parent(args);
Importer.writeln("--> ", r);
return r;
};
}
return stmt;
}
--------------------
what = template which determines _what functions should be
implemented/overridden.
An argument is passed to `what`: an alias to a non-final member
function in `Base`. Then `what` must return a boolean value.
Return `true` to indicate that the passed function should be
implemented/overridden.
--------------------
// Sees if fun returns something.
enum bool hasValue(alias fun) = !is(ReturnType!(fun) == void);
--------------------
Note:
Generated code is inserted in the scope of `std.typecons` module. Thus,
any useful functions outside `std.typecons` cannot be used in the generated
code. To workaround this problem, you may `import` necessary things in a
local struct, as done in the `generateLogger()` template in the above
example.
BUGS:
$(UL
$(LI Variadic arguments to constructors are not forwarded to super.)
$(LI Deep interface inheritance causes compile error with messages like
"Error: function std.typecons._AutoImplement!(Foo)._AutoImplement.bar
does not override any function". [$(BUGZILLA 2525), $(BUGZILLA 3525)] )
$(LI The `parent` keyword is actually a delegate to the super class'
corresponding member function. [$(BUGZILLA 2540)] )
$(LI Using alias template parameter in `how` and/or `what` may cause
strange compile error. Use template tuple parameter instead to workaround
this problem. [$(BUGZILLA 4217)] )
)
*/
class AutoImplement(Base, alias how, alias what = isAbstractFunction) : Base
if (!is(how == class))
{
private alias autoImplement_helper_ =
AutoImplement_Helper!("autoImplement_helper_", "Base", Base, typeof(this), how, what);
mixin(autoImplement_helper_.code);
}
/// ditto
class AutoImplement(
Interface, BaseClass, alias how,
alias what = isAbstractFunction) : BaseClass, Interface
if (is(Interface == interface) && is(BaseClass == class))
{
private alias autoImplement_helper_ = AutoImplement_Helper!(
"autoImplement_helper_", "Interface", Interface, typeof(this), how, what);
mixin(autoImplement_helper_.code);
}
///
@system unittest
{
interface PackageSupplier
{
int foo();
int bar();
}
static abstract class AbstractFallbackPackageSupplier : PackageSupplier
{
protected PackageSupplier default_, fallback;
this(PackageSupplier default_, PackageSupplier fallback)
{
this.default_ = default_;
this.fallback = fallback;
}
abstract int foo();
abstract int bar();
}
template fallback(T, alias func)
{
import std.format : format;
// for all implemented methods:
// - try default first
// - only on a failure run & return fallback
enum fallback = q{
scope (failure) return fallback.%1$s(args);
return default_.%1$s(args);
}.format(__traits(identifier, func));
}
// combines two classes and use the second one as fallback
alias FallbackPackageSupplier = AutoImplement!(AbstractFallbackPackageSupplier, fallback);
class FailingPackageSupplier : PackageSupplier
{
int foo(){ throw new Exception("failure"); }
int bar(){ return 2;}
}
class BackupPackageSupplier : PackageSupplier
{
int foo(){ return -1; }
int bar(){ return -1;}
}
auto registry = new FallbackPackageSupplier(new FailingPackageSupplier(), new BackupPackageSupplier());
assert(registry.foo() == -1);
assert(registry.bar() == 2);
}
/*
* Code-generating stuffs are encupsulated in this helper template so that
* namespace pollution, which can cause name confliction with Base's public
* members, should be minimized.
*/
private template AutoImplement_Helper(string myName, string baseName,
Base, Self, alias generateMethodBody, alias cherrypickMethod)
{
private static:
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// Internal stuffs
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// Returns function overload sets in the class C, filtered with pred.
template enumerateOverloads(C, alias pred)
{
template Impl(names...)
{
import std.meta : Filter;
static if (names.length > 0)
{
alias methods = Filter!(pred, MemberFunctionsTuple!(C, names[0]));
alias next = Impl!(names[1 .. $]);
static if (methods.length > 0)
alias Impl = AliasSeq!(OverloadSet!(names[0], methods), next);
else
alias Impl = next;
}
else
alias Impl = AliasSeq!();
}
alias enumerateOverloads = Impl!(__traits(allMembers, C));
}
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// Target functions
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// Add a non-final check to the cherrypickMethod.
enum bool canonicalPicker(fun.../+[BUG 4217]+/) =
!__traits(isFinalFunction, fun[0]) && cherrypickMethod!(fun);
/*
* A tuple of overload sets, each item of which consists of functions to be
* implemented by the generated code.
*/
alias targetOverloadSets = enumerateOverloads!(Base, canonicalPicker);
/*
* Super class of this AutoImplement instance
*/
alias Super = BaseTypeTuple!(Self)[0];
static assert(is(Super == class));
static assert(is(Base == interface) || is(Super == Base));
/*
* A tuple of the super class' constructors. Used for forwarding
* constructor calls.
*/
static if (__traits(hasMember, Super, "__ctor"))
alias ctorOverloadSet = OverloadSet!("__ctor", __traits(getOverloads, Super, "__ctor"));
else
alias ctorOverloadSet = OverloadSet!("__ctor"); // empty
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// Type information
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
/*
* The generated code will be mixed into AutoImplement, which will be
* instantiated in this module's scope. Thus, any user-defined types are
* out of scope and cannot be used directly (i.e. by their names).
*
* We will use FuncInfo instances for accessing return types and parameter
* types of the implemented functions. The instances will be populated to
* the AutoImplement's scope in a certain way; see the populate() below.
*/
// Returns the preferred identifier for the FuncInfo instance for the i-th
// overloaded function with the name.
template INTERNAL_FUNCINFO_ID(string name, size_t i)
{
import std.format : format;
enum string INTERNAL_FUNCINFO_ID = format("F_%s_%s", name, i);
}
/*
* Insert FuncInfo instances about all the target functions here. This
* enables the generated code to access type information via, for example,
* "autoImplement_helper_.F_foo_1".
*/
template populate(overloads...)
{
static if (overloads.length > 0)
{
mixin populate!(overloads[0].name, overloads[0].contents);
mixin populate!(overloads[1 .. $]);
}
}
template populate(string name, methods...)
{
static if (methods.length > 0)
{
mixin populate!(name, methods[0 .. $ - 1]);
//
alias target = methods[$ - 1];
enum ith = methods.length - 1;
mixin("alias " ~ INTERNAL_FUNCINFO_ID!(name, ith) ~ " = FuncInfo!target;");
}
}
public mixin populate!(targetOverloadSets);
public mixin populate!( ctorOverloadSet );
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// Code-generating policies
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
/* Common policy configurations for generating constructors and methods. */
template CommonGeneratingPolicy()
{
// base class identifier which generated code should use
enum string BASE_CLASS_ID = baseName;
// FuncInfo instance identifier which generated code should use
template FUNCINFO_ID(string name, size_t i)
{
enum string FUNCINFO_ID =
myName ~ "." ~ INTERNAL_FUNCINFO_ID!(name, i);
}
}
/* Policy configurations for generating constructors. */
template ConstructorGeneratingPolicy()
{
mixin CommonGeneratingPolicy;
/* Generates constructor body. Just forward to the base class' one. */
string generateFunctionBody(ctor.../+[BUG 4217]+/)() @property
{
enum varstyle = variadicFunctionStyle!(typeof(&ctor[0]));
static if (varstyle & (Variadic.c | Variadic.d))
{
// the argptr-forwarding problem
//pragma(msg, "Warning: AutoImplement!(", Base, ") ",
// "ignored variadic arguments to the constructor ",
// FunctionTypeOf!(typeof(&ctor[0])) );
}
return "super(args);";
}
}
/* Policy configurations for genearting target methods. */
template MethodGeneratingPolicy()
{
mixin CommonGeneratingPolicy;
/* Geneartes method body. */
string generateFunctionBody(func.../+[BUG 4217]+/)() @property
{
return generateMethodBody!(Base, func); // given
}
}
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// Generated code
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
alias ConstructorGenerator = MemberFunctionGenerator!(ConstructorGeneratingPolicy!());
alias MethodGenerator = MemberFunctionGenerator!(MethodGeneratingPolicy!());
public enum string code =
ConstructorGenerator.generateCode!( ctorOverloadSet ) ~ "\n" ~
MethodGenerator.generateCode!(targetOverloadSets);
debug (SHOW_GENERATED_CODE)
{
pragma(msg, "-------------------- < ", Base, " >");
pragma(msg, code);
pragma(msg, "--------------------");
}
}
//debug = SHOW_GENERATED_CODE;
@system unittest
{
import core.vararg;
// no function to implement
{
interface I_1 {}
auto o = new BlackHole!I_1;
}
// parameters
{
interface I_3 { void test(int, in int, out int, ref int, lazy int); }
auto o = new BlackHole!I_3;
}
// use of user-defined type
{
struct S {}
interface I_4 { S test(); }
auto o = new BlackHole!I_4;
}
// overloads
{
interface I_5
{
void test(string);
real test(real);
int test();
}
auto o = new BlackHole!I_5;
}
// constructor forwarding
{
static class C_6
{
this(int n) { assert(n == 42); }
this(string s) { assert(s == "Deeee"); }
this(...) {}
}
auto o1 = new BlackHole!C_6(42);
auto o2 = new BlackHole!C_6("Deeee");
auto o3 = new BlackHole!C_6(1, 2, 3, 4);
}
// attributes
{
interface I_7
{
ref int test_ref();
int test_pure() pure;
int test_nothrow() nothrow;
int test_property() @property;
int test_safe() @safe;
int test_trusted() @trusted;
int test_system() @system;
int test_pure_nothrow() pure nothrow;
}
auto o = new BlackHole!I_7;
}
// storage classes
{
interface I_8
{
void test_const() const;
void test_immutable() immutable;
void test_shared() shared;
void test_shared_const() shared const;
}
auto o = new BlackHole!I_8;
}
// use baseclass
{
static class C_9
{
private string foo_;
this(string s) {
foo_ = s;
}
protected string boilerplate() @property
{
return "Boilerplate stuff.";
}
public string foo() @property
{
return foo_;
}
}
interface I_10
{
string testMethod(size_t);
}
static string generateTestMethod(C, alias fun)() @property
{
return "return this.boilerplate[0 .. a0];";
}
auto o = new AutoImplement!(I_10, C_9, generateTestMethod)("Testing");
assert(o.testMethod(11) == "Boilerplate");
assert(o.foo == "Testing");
}
/+ // deep inheritance
{
// XXX [BUG 2525,3525]
// NOTE: [r494] func.c(504-571) FuncDeclaration::semantic()
interface I { void foo(); }
interface J : I {}
interface K : J {}
static abstract class C_9 : K {}
auto o = new BlackHole!C_9;
}+/
}
// Issue 17177 - AutoImplement fails on function overload sets with "cannot infer type from overloaded function symbol"
@system unittest
{
static class Issue17177
{
private string n_;
public {
Issue17177 overloaded(string n)
{
this.n_ = n;
return this;
}
string overloaded()
{
return this.n_;
}
}
}
static string how(C, alias fun)()
{
static if (!is(ReturnType!fun == void))
{
return q{
return parent(args);
};
}
else
{
return q{
parent(args);
};
}
}
alias Implementation = AutoImplement!(Issue17177, how, templateNot!isFinalFunction);
}
version (unittest)
{
// Issue 10647
// Add prefix "issue10647_" as a workaround for issue 1238
private string issue10647_generateDoNothing(C, alias fun)() @property
{
string stmt;
static if (is(ReturnType!fun == void))
stmt ~= "";
else
{
string returnType = ReturnType!fun.stringof;
stmt ~= "return "~returnType~".init;";
}
return stmt;
}
private template issue10647_isAlwaysTrue(alias fun)
{
enum issue10647_isAlwaysTrue = true;
}
// Do nothing template
private template issue10647_DoNothing(Base)
{
alias issue10647_DoNothing = AutoImplement!(Base, issue10647_generateDoNothing, issue10647_isAlwaysTrue);
}
// A class to be overridden
private class issue10647_Foo{
void bar(int a) { }
}
}
@system unittest
{
auto foo = new issue10647_DoNothing!issue10647_Foo();
foo.bar(13);
}
/*
Used by MemberFunctionGenerator.
*/
package template OverloadSet(string nam, T...)
{
enum string name = nam;
alias contents = T;
}
/*
Used by MemberFunctionGenerator.
*/
package template FuncInfo(alias func, /+[BUG 4217 ?]+/ T = typeof(&func))
{
alias RT = ReturnType!T;
alias PT = Parameters!T;
}
package template FuncInfo(Func)
{
alias RT = ReturnType!Func;
alias PT = Parameters!Func;
}
/*
General-purpose member function generator.
--------------------
template GeneratingPolicy()
{
// [optional] the name of the class where functions are derived
enum string BASE_CLASS_ID;
// [optional] define this if you have only function types
enum bool WITHOUT_SYMBOL;
// [optional] Returns preferred identifier for i-th parameter.
template PARAMETER_VARIABLE_ID(size_t i);
// Returns the identifier of the FuncInfo instance for the i-th overload
// of the specified name. The identifier must be accessible in the scope
// where generated code is mixed.
template FUNCINFO_ID(string name, size_t i);
// Returns implemented function body as a string. When WITHOUT_SYMBOL is
// defined, the latter is used.
template generateFunctionBody(alias func);
template generateFunctionBody(string name, FuncType);
}
--------------------
*/
package template MemberFunctionGenerator(alias Policy)
{
private static:
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// Internal stuffs
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
import std.format;
enum CONSTRUCTOR_NAME = "__ctor";
// true if functions are derived from a base class
enum WITH_BASE_CLASS = __traits(hasMember, Policy, "BASE_CLASS_ID");
// true if functions are specified as types, not symbols
enum WITHOUT_SYMBOL = __traits(hasMember, Policy, "WITHOUT_SYMBOL");
// preferred identifier for i-th parameter variable
static if (__traits(hasMember, Policy, "PARAMETER_VARIABLE_ID"))
{
alias PARAMETER_VARIABLE_ID = Policy.PARAMETER_VARIABLE_ID;
}
else
{
enum string PARAMETER_VARIABLE_ID(size_t i) = format("a%s", i);
// default: a0, a1, ...
}
// Returns a tuple consisting of 0,1,2,...,n-1. For static foreach.
template CountUp(size_t n)
{
static if (n > 0)
alias CountUp = AliasSeq!(CountUp!(n - 1), n - 1);
else
alias CountUp = AliasSeq!();
}
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// Code generator
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
/*
* Runs through all the target overload sets and generates D code which
* implements all the functions in the overload sets.
*/
public string generateCode(overloads...)() @property
{
string code = "";
// run through all the overload sets
foreach (i_; CountUp!(0 + overloads.length)) // workaround
{
enum i = 0 + i_; // workaround
alias oset = overloads[i];
code ~= generateCodeForOverloadSet!(oset);
static if (WITH_BASE_CLASS && oset.name != CONSTRUCTOR_NAME)
{
// The generated function declarations may hide existing ones
// in the base class (cf. HiddenFuncError), so we put an alias
// declaration here to reveal possible hidden functions.
code ~= format("alias %s = %s.%s;\n",
oset.name,
Policy.BASE_CLASS_ID, // [BUG 2540] super.
oset.name);
}
}
return code;
}
// handle each overload set
private string generateCodeForOverloadSet(alias oset)() @property
{
string code = "";
foreach (i_; CountUp!(0 + oset.contents.length)) // workaround
{
enum i = 0 + i_; // workaround
code ~= generateFunction!(
Policy.FUNCINFO_ID!(oset.name, i), oset.name,
oset.contents[i]) ~ "\n";
}
return code;
}
/*
* Returns D code which implements the function func. This function
* actually generates only the declarator part; the function body part is
* generated by the functionGenerator() policy.
*/
public string generateFunction(
string myFuncInfo, string name, func... )() @property
{
import std.format : format;
enum isCtor = (name == CONSTRUCTOR_NAME);
string code; // the result
auto paramsRes = generateParameters!(myFuncInfo, func)();
code ~= paramsRes.imports;
/*** Function Declarator ***/
{
alias Func = FunctionTypeOf!(func);
alias FA = FunctionAttribute;
enum atts = functionAttributes!(func);
enum realName = isCtor ? "this" : name;
// FIXME?? Make it so that these aren't CTFE funcs any more, since
// Format is deprecated, and format works at compile time?
/* Made them CTFE funcs just for the sake of Format!(...) */
// return type with optional "ref"
static string make_returnType()
{
string rtype = "";
if (!isCtor)
{
if (atts & FA.ref_) rtype ~= "ref ";
rtype ~= myFuncInfo ~ ".RT";
}
return rtype;
}
enum returnType = make_returnType();
// function attributes attached after declaration
static string make_postAtts()
{
string poatts = "";
if (atts & FA.pure_ ) poatts ~= " pure";
if (atts & FA.nothrow_) poatts ~= " nothrow";
if (atts & FA.property) poatts ~= " @property";
if (atts & FA.safe ) poatts ~= " @safe";
if (atts & FA.trusted ) poatts ~= " @trusted";
return poatts;
}
enum postAtts = make_postAtts();
// function storage class
static string make_storageClass()
{
string postc = "";
if (is(Func == shared)) postc ~= " shared";
if (is(Func == const)) postc ~= " const";
if (is(Func == inout)) postc ~= " inout";
if (is(Func == immutable)) postc ~= " immutable";
return postc;
}
enum storageClass = make_storageClass();
//
if (__traits(isVirtualMethod, func))
code ~= "override ";
code ~= format("extern(%s) %s %s(%s) %s %s\n",
functionLinkage!(func),
returnType,
realName,
paramsRes.params,
postAtts, storageClass );
}
/*** Function Body ***/
code ~= "{\n";
{
enum nparams = Parameters!(func).length;
/* Declare keywords: args, self and parent. */
string preamble;
preamble ~= "alias args = AliasSeq!(" ~ enumerateParameters!(nparams) ~ ");\n";
if (!isCtor)
{
preamble ~= "alias self = " ~ name ~ ";\n";
if (WITH_BASE_CLASS && !__traits(isAbstractFunction, func))
preamble ~= `alias parent = __traits(getMember, super, "` ~ name ~ `");`;
}
// Function body
static if (WITHOUT_SYMBOL)
enum fbody = Policy.generateFunctionBody!(name, func);
else
enum fbody = Policy.generateFunctionBody!(func);
code ~= preamble;
code ~= fbody;
}
code ~= "}";
return code;
}
/*
* Returns D code which declares function parameters,
* and optionally any imports (e.g. core.vararg)
* "ref int a0, real a1, ..."
*/
static struct GenParams { string imports, params; }
private GenParams generateParameters(string myFuncInfo, func...)()
{
alias STC = ParameterStorageClass;
alias stcs = ParameterStorageClassTuple!(func);
enum nparams = stcs.length;
string imports = ""; // any imports required
string params = ""; // parameters
foreach (i, stc; stcs)
{
if (i > 0) params ~= ", ";
// Parameter storage classes.
if (stc & STC.scope_) params ~= "scope ";
if (stc & STC.out_ ) params ~= "out ";
if (stc & STC.ref_ ) params ~= "ref ";
if (stc & STC.lazy_ ) params ~= "lazy ";
// Take parameter type from the FuncInfo.
params ~= format("%s.PT[%s]", myFuncInfo, i);
// Declare a parameter variable.
params ~= " " ~ PARAMETER_VARIABLE_ID!(i);
}
// Add some ellipsis part if needed.
auto style = variadicFunctionStyle!(func);
final switch (style)
{
case Variadic.no:
break;
case Variadic.c, Variadic.d:
imports ~= "import core.vararg;\n";
// (...) or (a, b, ...)
params ~= (nparams == 0) ? "..." : ", ...";
break;
case Variadic.typesafe:
params ~= " ...";
break;
}
return typeof(return)(imports, params);
}
// Returns D code which enumerates n parameter variables using comma as the
// separator. "a0, a1, a2, a3"
private string enumerateParameters(size_t n)() @property
{
string params = "";
foreach (i_; CountUp!(n))
{
enum i = 0 + i_; // workaround
if (i > 0) params ~= ", ";
params ~= PARAMETER_VARIABLE_ID!(i);
}
return params;
}
}
/**
Predefined how-policies for `AutoImplement`. These templates are also used by
`BlackHole` and `WhiteHole`, respectively.
*/
template generateEmptyFunction(C, func.../+[BUG 4217]+/)
{
static if (is(ReturnType!(func) == void))
enum string generateEmptyFunction = q{
};
else static if (functionAttributes!(func) & FunctionAttribute.ref_)
enum string generateEmptyFunction = q{
static typeof(return) dummy;
return dummy;
};
else
enum string generateEmptyFunction = q{
return typeof(return).init;
};
}
///
@system unittest
{
alias BlackHole(Base) = AutoImplement!(Base, generateEmptyFunction);
interface I
{
int foo();
string bar();
}
auto i = new BlackHole!I();
// generateEmptyFunction returns the default value of the return type without doing anything
assert(i.foo == 0);
assert(i.bar is null);
}
/// ditto
template generateAssertTrap(C, func...)
{
enum string generateAssertTrap =
`throw new NotImplementedError("` ~ C.stringof ~ "."
~ __traits(identifier, func) ~ `");`;
}
///
@system unittest
{
import std.exception : assertThrown;
alias WhiteHole(Base) = AutoImplement!(Base, generateAssertTrap);
interface I
{
int foo();
string bar();
}
auto i = new WhiteHole!I();
// generateAssertTrap throws an exception for every unimplemented function of the interface
assertThrown!NotImplementedError(i.foo);
assertThrown!NotImplementedError(i.bar);
}
private
{
pragma(mangle, "_d_toObject")
extern(C) pure nothrow Object typecons_d_toObject(void* p);
}
/*
* Avoids opCast operator overloading.
*/
private template dynamicCast(T)
if (is(T == class) || is(T == interface))
{
@trusted
T dynamicCast(S)(inout S source)
if (is(S == class) || is(S == interface))
{
static if (is(Unqual!S : Unqual!T))
{
import std.traits : QualifierOf;
alias Qual = QualifierOf!S; // SharedOf or MutableOf
alias TmpT = Qual!(Unqual!T);
inout(TmpT) tmp = source; // bypass opCast by implicit conversion
return *cast(T*)(&tmp); // + variable pointer cast + dereference
}
else
{
return cast(T) typecons_d_toObject(*cast(void**)(&source));
}
}
}
@system unittest
{
class C { @disable void opCast(T)(); }
auto c = new C;
static assert(!__traits(compiles, cast(Object) c));
auto o = dynamicCast!Object(c);
assert(c is o);
interface I { @disable void opCast(T)(); Object instance(); }
interface J { @disable void opCast(T)(); Object instance(); }
class D : I, J { Object instance() { return this; } }
I i = new D();
static assert(!__traits(compiles, cast(J) i));
J j = dynamicCast!J(i);
assert(i.instance() is j.instance());
}
/**
Supports structural based typesafe conversion.
If `Source` has structural conformance with the `interface` `Targets`,
wrap creates an internal wrapper class which inherits `Targets` and
wraps the `src` object, then returns it.
`unwrap` can be used to extract objects which have been wrapped by `wrap`.
*/
template wrap(Targets...)
if (Targets.length >= 1 && allSatisfy!(isMutable, Targets))
{
import std.meta : staticMap;
// strict upcast
auto wrap(Source)(inout Source src) @trusted pure nothrow
if (Targets.length == 1 && is(Source : Targets[0]))
{
alias T = Select!(is(Source == shared), shared Targets[0], Targets[0]);
return dynamicCast!(inout T)(src);
}
// structural upcast
template wrap(Source)
if (!allSatisfy!(Bind!(isImplicitlyConvertible, Source), Targets))
{
auto wrap(inout Source src)
{
static assert(hasRequireMethods!(),
"Source "~Source.stringof~
" does not have structural conformance to "~
Targets.stringof);
alias T = Select!(is(Source == shared), shared Impl, Impl);
return new inout T(src);
}
template FuncInfo(string s, F)
{
enum name = s;
alias type = F;
}
// issue 12064: Remove NVI members
template OnlyVirtual(members...)
{
enum notFinal(alias T) = !__traits(isFinalFunction, T);
alias OnlyVirtual = Filter!(notFinal, members);
}
// Concat all Targets function members into one tuple
template Concat(size_t i = 0)
{
static if (i >= Targets.length)
alias Concat = AliasSeq!();
else
{
alias Concat = AliasSeq!(OnlyVirtual!(GetOverloadedMethods!(Targets[i]), Concat!(i + 1)));
}
}
// Remove duplicated functions based on the identifier name and function type covariance
template Uniq(members...)
{
static if (members.length == 0)
alias Uniq = AliasSeq!();
else
{
alias func = members[0];
enum name = __traits(identifier, func);
alias type = FunctionTypeOf!func;
template check(size_t i, mem...)
{
static if (i >= mem.length)
enum ptrdiff_t check = -1;
else
{
enum ptrdiff_t check =
__traits(identifier, func) == __traits(identifier, mem[i]) &&
!is(DerivedFunctionType!(type, FunctionTypeOf!(mem[i])) == void)
? i : check!(i + 1, mem);
}
}
enum ptrdiff_t x = 1 + check!(0, members[1 .. $]);
static if (x >= 1)
{
alias typex = DerivedFunctionType!(type, FunctionTypeOf!(members[x]));
alias remain = Uniq!(members[1 .. x], members[x + 1 .. $]);
static if (remain.length >= 1 && remain[0].name == name &&
!is(DerivedFunctionType!(typex, remain[0].type) == void))
{
alias F = DerivedFunctionType!(typex, remain[0].type);
alias Uniq = AliasSeq!(FuncInfo!(name, F), remain[1 .. $]);
}
else
alias Uniq = AliasSeq!(FuncInfo!(name, typex), remain);
}
else
{
alias Uniq = AliasSeq!(FuncInfo!(name, type), Uniq!(members[1 .. $]));
}
}
}
alias TargetMembers = Uniq!(Concat!()); // list of FuncInfo
alias SourceMembers = GetOverloadedMethods!Source; // list of function symbols
// Check whether all of SourceMembers satisfy covariance target in TargetMembers
template hasRequireMethods(size_t i = 0)
{
static if (i >= TargetMembers.length)
enum hasRequireMethods = true;
else
{
enum hasRequireMethods =
findCovariantFunction!(TargetMembers[i], Source, SourceMembers) != -1 &&
hasRequireMethods!(i + 1);
}
}
// Internal wrapper class
final class Impl : Structural, Targets
{
private:
Source _wrap_source;
this( inout Source s) inout @safe pure nothrow { _wrap_source = s; }
this(shared inout Source s) shared inout @safe pure nothrow { _wrap_source = s; }
// BUG: making private should work with NVI.
protected final inout(Object) _wrap_getSource() inout @trusted
{
return dynamicCast!(inout Object)(_wrap_source);
}
import std.conv : to;
import std.functional : forward;
template generateFun(size_t i)
{
enum name = TargetMembers[i].name;
enum fa = functionAttributes!(TargetMembers[i].type);
static @property stc()
{
string r;
if (fa & FunctionAttribute.property) r ~= "@property ";
if (fa & FunctionAttribute.ref_) r ~= "ref ";
if (fa & FunctionAttribute.pure_) r ~= "pure ";
if (fa & FunctionAttribute.nothrow_) r ~= "nothrow ";
if (fa & FunctionAttribute.trusted) r ~= "@trusted ";
if (fa & FunctionAttribute.safe) r ~= "@safe ";
return r;
}
static @property mod()
{
alias type = AliasSeq!(TargetMembers[i].type)[0];
string r;
static if (is(type == immutable)) r ~= " immutable";
else
{
static if (is(type == shared)) r ~= " shared";
static if (is(type == const)) r ~= " const";
else static if (is(type == inout)) r ~= " inout";
//else --> mutable
}
return r;
}
enum n = to!string(i);
static if (fa & FunctionAttribute.property)
{
static if (Parameters!(TargetMembers[i].type).length == 0)
enum fbody = "_wrap_source."~name;
else
enum fbody = "_wrap_source."~name~" = forward!args";
}
else
{
enum fbody = "_wrap_source."~name~"(forward!args)";
}
enum generateFun =
"override "~stc~"ReturnType!(TargetMembers["~n~"].type) "
~ name~"(Parameters!(TargetMembers["~n~"].type) args) "~mod~
"{ return "~fbody~"; }";
}
public:
static foreach (i; 0 .. TargetMembers.length)
mixin(generateFun!i);
}
}
}
/// ditto
template wrap(Targets...)
if (Targets.length >= 1 && !allSatisfy!(isMutable, Targets))
{
import std.meta : staticMap;
alias wrap = .wrap!(staticMap!(Unqual, Targets));
}
/// ditto
template unwrap(Target)
if (isMutable!Target)
{
// strict downcast
auto unwrap(Source)(inout Source src) @trusted pure nothrow
if (is(Target : Source))
{
alias T = Select!(is(Source == shared), shared Target, Target);
return dynamicCast!(inout T)(src);
}
// structural downcast
auto unwrap(Source)(inout Source src) @trusted pure nothrow
if (!is(Target : Source))
{
alias T = Select!(is(Source == shared), shared Target, Target);
Object o = dynamicCast!(Object)(src); // remove qualifier
do
{
if (auto a = dynamicCast!(Structural)(o))
{
if (auto d = dynamicCast!(inout T)(o = a._wrap_getSource()))
return d;
}
else if (auto d = dynamicCast!(inout T)(o))
return d;
else
break;
} while (o);
return null;
}
}
/// ditto
template unwrap(Target)
if (!isMutable!Target)
{
alias unwrap = .unwrap!(Unqual!Target);
}
///
@system unittest
{
interface Quack
{
int quack();
@property int height();
}
interface Flyer
{
@property int height();
}
class Duck : Quack
{
int quack() { return 1; }
@property int height() { return 10; }
}
class Human
{
int quack() { return 2; }
@property int height() { return 20; }
}
Duck d1 = new Duck();
Human h1 = new Human();
interface Refleshable
{
int reflesh();
}
// does not have structural conformance
static assert(!__traits(compiles, d1.wrap!Refleshable));
static assert(!__traits(compiles, h1.wrap!Refleshable));
// strict upcast
Quack qd = d1.wrap!Quack;
assert(qd is d1);
assert(qd.quack() == 1); // calls Duck.quack
// strict downcast
Duck d2 = qd.unwrap!Duck;
assert(d2 is d1);
// structural upcast
Quack qh = h1.wrap!Quack;
assert(qh.quack() == 2); // calls Human.quack
// structural downcast
Human h2 = qh.unwrap!Human;
assert(h2 is h1);
// structural upcast (two steps)
Quack qx = h1.wrap!Quack; // Human -> Quack
Flyer fx = qx.wrap!Flyer; // Quack -> Flyer
assert(fx.height == 20); // calls Human.height
// structural downcast (two steps)
Quack qy = fx.unwrap!Quack; // Flyer -> Quack
Human hy = qy.unwrap!Human; // Quack -> Human
assert(hy is h1);
// structural downcast (one step)
Human hz = fx.unwrap!Human; // Flyer -> Human
assert(hz is h1);
}
///
@system unittest
{
import std.traits : FunctionAttribute, functionAttributes;
interface A { int run(); }
interface B { int stop(); @property int status(); }
class X
{
int run() { return 1; }
int stop() { return 2; }
@property int status() { return 3; }
}
auto x = new X();
auto ab = x.wrap!(A, B);
A a = ab;
B b = ab;
assert(a.run() == 1);
assert(b.stop() == 2);
assert(b.status == 3);
static assert(functionAttributes!(typeof(ab).status) & FunctionAttribute.property);
}
// Internal class to support dynamic cross-casting
private interface Structural
{
inout(Object) _wrap_getSource() inout @safe pure nothrow;
}
@system unittest
{
class A
{
int draw() { return 1; }
int draw(int v) { return v; }
int draw() const { return 2; }
int draw() shared { return 3; }
int draw() shared const { return 4; }
int draw() immutable { return 5; }
}
interface Drawable
{
int draw();
int draw() const;
int draw() shared;
int draw() shared const;
int draw() immutable;
}
interface Drawable2
{
int draw(int v);
}
auto ma = new A();
auto sa = new shared A();
auto ia = new immutable A();
{
Drawable md = ma.wrap!Drawable;
const Drawable cd = ma.wrap!Drawable;
shared Drawable sd = sa.wrap!Drawable;
shared const Drawable scd = sa.wrap!Drawable;
immutable Drawable id = ia.wrap!Drawable;
assert( md.draw() == 1);
assert( cd.draw() == 2);
assert( sd.draw() == 3);
assert(scd.draw() == 4);
assert( id.draw() == 5);
}
{
Drawable2 d = ma.wrap!Drawable2;
static assert(!__traits(compiles, d.draw()));
assert(d.draw(10) == 10);
}
}
@system unittest
{
// Bugzilla 10377
import std.range, std.algorithm;
interface MyInputRange(T)
{
@property T front();
void popFront();
@property bool empty();
}
//auto o = iota(0,10,1).inputRangeObject();
//pragma(msg, __traits(allMembers, typeof(o)));
auto r = iota(0,10,1).inputRangeObject().wrap!(MyInputRange!int)();
assert(equal(r, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
}
@system unittest
{
// Bugzilla 10536
interface Interface
{
int foo();
}
class Pluggable
{
int foo() { return 1; }
@disable void opCast(T, this X)(); // !
}
Interface i = new Pluggable().wrap!Interface;
assert(i.foo() == 1);
}
@system unittest
{
// Enhancement 10538
interface Interface
{
int foo();
int bar(int);
}
class Pluggable
{
int opDispatch(string name, A...)(A args) { return 100; }
}
Interface i = wrap!Interface(new Pluggable());
assert(i.foo() == 100);
assert(i.bar(10) == 100);
}
@system unittest // issue 12064
{
interface I
{
int foo();
final int nvi1(){return foo();}
}
interface J
{
int bar();
final int nvi2(){return bar();}
}
class Baz
{
int foo() { return 42;}
int bar() { return 12064;}
}
auto baz = new Baz();
auto foobar = baz.wrap!(I, J)();
assert(foobar.nvi1 == 42);
assert(foobar.nvi2 == 12064);
}
// Make a tuple of non-static function symbols
package template GetOverloadedMethods(T)
{
import std.meta : Filter;
alias allMembers = __traits(allMembers, T);
template follows(size_t i = 0)
{
static if (i >= allMembers.length)
{
alias follows = AliasSeq!();
}
else static if (!__traits(compiles, mixin("T."~allMembers[i])))
{
alias follows = follows!(i + 1);
}
else
{
enum name = allMembers[i];
template isMethod(alias f)
{
static if (is(typeof(&f) F == F*) && is(F == function))
enum isMethod = !__traits(isStaticFunction, f);
else
enum isMethod = false;
}
alias follows = AliasSeq!(
std.meta.Filter!(isMethod, __traits(getOverloads, T, name)),
follows!(i + 1));
}
}
alias GetOverloadedMethods = follows!();
}
// find a function from Fs that has same identifier and covariant type with f
private template findCovariantFunction(alias finfo, Source, Fs...)
{
template check(size_t i = 0)
{
static if (i >= Fs.length)
enum ptrdiff_t check = -1;
else
{
enum ptrdiff_t check =
(finfo.name == __traits(identifier, Fs[i])) &&
isCovariantWith!(FunctionTypeOf!(Fs[i]), finfo.type)
? i : check!(i + 1);
}
}
enum x = check!();
static if (x == -1 && is(typeof(Source.opDispatch)))
{
alias Params = Parameters!(finfo.type);
enum ptrdiff_t findCovariantFunction =
is(typeof(( Source).init.opDispatch!(finfo.name)(Params.init))) ||
is(typeof(( const Source).init.opDispatch!(finfo.name)(Params.init))) ||
is(typeof(( immutable Source).init.opDispatch!(finfo.name)(Params.init))) ||
is(typeof(( shared Source).init.opDispatch!(finfo.name)(Params.init))) ||
is(typeof((shared const Source).init.opDispatch!(finfo.name)(Params.init)))
? ptrdiff_t.max : -1;
}
else
enum ptrdiff_t findCovariantFunction = x;
}
private enum TypeModifier
{
mutable = 0, // type is mutable
const_ = 1, // type is const
immutable_ = 2, // type is immutable
shared_ = 4, // type is shared
inout_ = 8, // type is wild
}
private template TypeMod(T)
{
static if (is(T == immutable))
{
enum mod1 = TypeModifier.immutable_;
enum mod2 = 0;
}
else
{
enum mod1 = is(T == shared) ? TypeModifier.shared_ : 0;
static if (is(T == const))
enum mod2 = TypeModifier.const_;
else static if (is(T == inout))
enum mod2 = TypeModifier.inout_;
else
enum mod2 = TypeModifier.mutable;
}
enum TypeMod = cast(TypeModifier)(mod1 | mod2);
}
version (unittest)
{
private template UnittestFuncInfo(alias f)
{
enum name = __traits(identifier, f);
alias type = FunctionTypeOf!f;
}
}
@system unittest
{
class A
{
int draw() { return 1; }
@property int value() { return 2; }
final int run() { return 3; }
}
alias methods = GetOverloadedMethods!A;
alias int F1();
alias @property int F2();
alias string F3();
alias nothrow @trusted uint F4();
alias int F5(Object);
alias bool F6(Object);
static assert(methods.length == 3 + 4);
static assert(__traits(identifier, methods[0]) == "draw" && is(typeof(&methods[0]) == F1*));
static assert(__traits(identifier, methods[1]) == "value" && is(typeof(&methods[1]) == F2*));
static assert(__traits(identifier, methods[2]) == "run" && is(typeof(&methods[2]) == F1*));
int draw();
@property int value();
void opEquals();
int nomatch();
static assert(findCovariantFunction!(UnittestFuncInfo!draw, A, methods) == 0);
static assert(findCovariantFunction!(UnittestFuncInfo!value, A, methods) == 1);
static assert(findCovariantFunction!(UnittestFuncInfo!opEquals, A, methods) == -1);
static assert(findCovariantFunction!(UnittestFuncInfo!nomatch, A, methods) == -1);
// considering opDispatch
class B
{
void opDispatch(string name, A...)(A) {}
}
alias methodsB = GetOverloadedMethods!B;
static assert(findCovariantFunction!(UnittestFuncInfo!draw, B, methodsB) == ptrdiff_t.max);
static assert(findCovariantFunction!(UnittestFuncInfo!value, B, methodsB) == ptrdiff_t.max);
static assert(findCovariantFunction!(UnittestFuncInfo!opEquals, B, methodsB) == ptrdiff_t.max);
static assert(findCovariantFunction!(UnittestFuncInfo!nomatch, B, methodsB) == ptrdiff_t.max);
}
package template DerivedFunctionType(T...)
{
static if (!T.length)
{
alias DerivedFunctionType = void;
}
else static if (T.length == 1)
{
static if (is(T[0] == function))
{
alias DerivedFunctionType = T[0];
}
else
{
alias DerivedFunctionType = void;
}
}
else static if (is(T[0] P0 == function) && is(T[1] P1 == function))
{
alias FA = FunctionAttribute;
alias F0 = T[0], R0 = ReturnType!F0, PSTC0 = ParameterStorageClassTuple!F0;
alias F1 = T[1], R1 = ReturnType!F1, PSTC1 = ParameterStorageClassTuple!F1;
enum FA0 = functionAttributes!F0;
enum FA1 = functionAttributes!F1;
template CheckParams(size_t i = 0)
{
static if (i >= P0.length)
enum CheckParams = true;
else
{
enum CheckParams = (is(P0[i] == P1[i]) && PSTC0[i] == PSTC1[i]) &&
CheckParams!(i + 1);
}
}
static if (R0.sizeof == R1.sizeof && !is(CommonType!(R0, R1) == void) &&
P0.length == P1.length && CheckParams!() && TypeMod!F0 == TypeMod!F1 &&
variadicFunctionStyle!F0 == variadicFunctionStyle!F1 &&
functionLinkage!F0 == functionLinkage!F1 &&
((FA0 ^ FA1) & (FA.ref_ | FA.property)) == 0)
{
alias R = Select!(is(R0 : R1), R0, R1);
alias FX = FunctionTypeOf!(R function(P0));
// @system is default
alias FY = SetFunctionAttributes!(FX, functionLinkage!F0, (FA0 | FA1) & ~FA.system);
alias DerivedFunctionType = DerivedFunctionType!(FY, T[2 .. $]);
}
else
alias DerivedFunctionType = void;
}
else
alias DerivedFunctionType = void;
}
@safe unittest
{
// attribute covariance
alias int F1();
static assert(is(DerivedFunctionType!(F1, F1) == F1));
alias int F2() pure nothrow;
static assert(is(DerivedFunctionType!(F1, F2) == F2));
alias int F3() @safe;
alias int F23() @safe pure nothrow;
static assert(is(DerivedFunctionType!(F2, F3) == F23));
// return type covariance
alias long F4();
static assert(is(DerivedFunctionType!(F1, F4) == void));
class C {}
class D : C {}
alias C F5();
alias D F6();
static assert(is(DerivedFunctionType!(F5, F6) == F6));
alias typeof(null) F7();
alias int[] F8();
alias int* F9();
static assert(is(DerivedFunctionType!(F5, F7) == F7));
static assert(is(DerivedFunctionType!(F7, F8) == void));
static assert(is(DerivedFunctionType!(F7, F9) == F7));
// variadic type equality
alias int F10(int);
alias int F11(int...);
alias int F12(int, ...);
static assert(is(DerivedFunctionType!(F10, F11) == void));
static assert(is(DerivedFunctionType!(F10, F12) == void));
static assert(is(DerivedFunctionType!(F11, F12) == void));
// linkage equality
alias extern(C) int F13(int);
alias extern(D) int F14(int);
alias extern(Windows) int F15(int);
static assert(is(DerivedFunctionType!(F13, F14) == void));
static assert(is(DerivedFunctionType!(F13, F15) == void));
static assert(is(DerivedFunctionType!(F14, F15) == void));
// ref & @property equality
alias int F16(int);
alias ref int F17(int);
alias @property int F18(int);
static assert(is(DerivedFunctionType!(F16, F17) == void));
static assert(is(DerivedFunctionType!(F16, F18) == void));
static assert(is(DerivedFunctionType!(F17, F18) == void));
}
package template Bind(alias Template, args1...)
{
alias Bind(args2...) = Template!(args1, args2);
}
/**
Options regarding auto-initialization of a `RefCounted` object (see
the definition of `RefCounted` below).
*/
enum RefCountedAutoInitialize
{
/// Do not auto-initialize the object
no,
/// Auto-initialize the object
yes,
}
///
@system unittest
{
import core.exception : AssertError;
import std.exception : assertThrown;
struct Foo
{
int a = 42;
}
RefCounted!(Foo, RefCountedAutoInitialize.yes) rcAuto;
RefCounted!(Foo, RefCountedAutoInitialize.no) rcNoAuto;
assert(rcAuto.refCountedPayload.a == 42);
assertThrown!AssertError(rcNoAuto.refCountedPayload);
rcNoAuto.refCountedStore.ensureInitialized;
assert(rcNoAuto.refCountedPayload.a == 42);
}
/**
Defines a reference-counted object containing a `T` value as
payload.
An instance of `RefCounted` is a reference to a structure,
which is referred to as the $(I store), or $(I storage implementation
struct) in this documentation. The store contains a reference count
and the `T` payload. `RefCounted` uses `malloc` to allocate
the store. As instances of `RefCounted` are copied or go out of
scope, they will automatically increment or decrement the reference
count. When the reference count goes down to zero, `RefCounted`
will call `destroy` against the payload and call `free` to
deallocate the store. If the `T` payload contains any references
to GC-allocated memory, then `RefCounted` will add it to the GC memory
that is scanned for pointers, and remove it from GC scanning before
`free` is called on the store.
One important consequence of `destroy` is that it will call the
destructor of the `T` payload. GC-managed references are not
guaranteed to be valid during a destructor call, but other members of
`T`, such as file handles or pointers to `malloc` memory, will
still be valid during the destructor call. This allows the `T` to
deallocate or clean up any non-GC resources immediately after the
reference count has reached zero.
`RefCounted` is unsafe and should be used with care. No references
to the payload should be escaped outside the `RefCounted` object.
The `autoInit` option makes the object ensure the store is
automatically initialized. Leaving $(D autoInit ==
RefCountedAutoInitialize.yes) (the default option) is convenient but
has the cost of a test whenever the payload is accessed. If $(D
autoInit == RefCountedAutoInitialize.no), user code must call either
`refCountedStore.isInitialized` or `refCountedStore.ensureInitialized`
before attempting to access the payload. Not doing so results in null
pointer dereference.
*/
struct RefCounted(T, RefCountedAutoInitialize autoInit =
RefCountedAutoInitialize.yes)
if (!is(T == class) && !(is(T == interface)))
{
extern(C) private pure nothrow @nogc static // TODO remove pure when https://issues.dlang.org/show_bug.cgi?id=15862 has been fixed
{
pragma(mangle, "free") void pureFree( void *ptr );
pragma(mangle, "gc_addRange") void pureGcAddRange( in void* p, size_t sz, const TypeInfo ti = null );
pragma(mangle, "gc_removeRange") void pureGcRemoveRange( in void* p );
}
/// `RefCounted` storage implementation.
struct RefCountedStore
{
private struct Impl
{
T _payload;
size_t _count;
}
private Impl* _store;
private void initialize(A...)(auto ref A args)
{
import std.conv : emplace;
allocateStore();
emplace(&_store._payload, args);
_store._count = 1;
}
private void move(ref T source) nothrow pure
{
import std.algorithm.mutation : moveEmplace;
allocateStore();
moveEmplace(source, _store._payload);
_store._count = 1;
}
// 'nothrow': can only generate an Error
private void allocateStore() nothrow pure
{
static if (hasIndirections!T)
{
import std.internal.memory : enforceCalloc;
_store = cast(Impl*) enforceCalloc(1, Impl.sizeof);
pureGcAddRange(&_store._payload, T.sizeof);
}
else
{
import std.internal.memory : enforceMalloc;
_store = cast(Impl*) enforceMalloc(Impl.sizeof);
}
}
/**
Returns `true` if and only if the underlying store has been
allocated and initialized.
*/
@property nothrow @safe pure @nogc
bool isInitialized() const
{
return _store !is null;
}
/**
Returns underlying reference count if it is allocated and initialized
(a positive integer), and `0` otherwise.
*/
@property nothrow @safe pure @nogc
size_t refCount() const
{
return isInitialized ? _store._count : 0;
}
/**
Makes sure the payload was properly initialized. Such a
call is typically inserted before using the payload.
*/
void ensureInitialized()
{
if (!isInitialized) initialize();
}
}
RefCountedStore _refCounted;
/// Returns storage implementation struct.
@property nothrow @safe
ref inout(RefCountedStore) refCountedStore() inout
{
return _refCounted;
}
/**
Constructor that initializes the payload.
Postcondition: `refCountedStore.isInitialized`
*/
this(A...)(auto ref A args) if (A.length > 0)
{
_refCounted.initialize(args);
}
/// Ditto
this(T val)
{
_refCounted.move(val);
}
/**
Constructor that tracks the reference count appropriately. If $(D
!refCountedStore.isInitialized), does nothing.
*/
this(this) @safe pure nothrow @nogc
{
if (!_refCounted.isInitialized) return;
++_refCounted._store._count;
}
/**
Destructor that tracks the reference count appropriately. If $(D
!refCountedStore.isInitialized), does nothing. When the reference count goes
down to zero, calls `destroy` agaist the payload and calls `free`
to deallocate the corresponding resource.
*/
~this()
{
if (!_refCounted.isInitialized) return;
assert(_refCounted._store._count > 0);
if (--_refCounted._store._count)
return;
// Done, deallocate
.destroy(_refCounted._store._payload);
static if (hasIndirections!T)
{
pureGcRemoveRange(&_refCounted._store._payload);
}
pureFree(_refCounted._store);
_refCounted._store = null;
}
/**
Assignment operators
*/
void opAssign(typeof(this) rhs)
{
import std.algorithm.mutation : swap;
swap(_refCounted._store, rhs._refCounted._store);
}
/// Ditto
void opAssign(T rhs)
{
import std.algorithm.mutation : move;
static if (autoInit == RefCountedAutoInitialize.yes)
{
_refCounted.ensureInitialized();
}
else
{
assert(_refCounted.isInitialized);
}
move(rhs, _refCounted._store._payload);
}
//version to have a single properly ddoc'ed function (w/ correct sig)
version (StdDdoc)
{
/**
Returns a reference to the payload. If (autoInit ==
RefCountedAutoInitialize.yes), calls $(D
refCountedStore.ensureInitialized). Otherwise, just issues $(D
assert(refCountedStore.isInitialized)). Used with $(D alias
refCountedPayload this;), so callers can just use the `RefCounted`
object as a `T`.
$(BLUE The first overload exists only if $(D autoInit == RefCountedAutoInitialize.yes).)
So if $(D autoInit == RefCountedAutoInitialize.no)
or called for a constant or immutable object, then
`refCountedPayload` will also be qualified as safe and nothrow
(but will still assert if not initialized).
*/
@property @trusted
ref T refCountedPayload() return;
/// ditto
@property nothrow @safe pure @nogc
ref inout(T) refCountedPayload() inout return;
}
else
{
static if (autoInit == RefCountedAutoInitialize.yes)
{
//Can't use inout here because of potential mutation
@property
ref T refCountedPayload() return
{
_refCounted.ensureInitialized();
return _refCounted._store._payload;
}
}
@property nothrow @safe pure @nogc
ref inout(T) refCountedPayload() inout return
{
assert(_refCounted.isInitialized, "Attempted to access an uninitialized payload.");
return _refCounted._store._payload;
}
}
/**
Returns a reference to the payload. If (autoInit ==
RefCountedAutoInitialize.yes), calls $(D
refCountedStore.ensureInitialized). Otherwise, just issues $(D
assert(refCountedStore.isInitialized)).
*/
alias refCountedPayload this;
}
///
pure @system nothrow @nogc unittest
{
// A pair of an `int` and a `size_t` - the latter being the
// reference count - will be dynamically allocated
auto rc1 = RefCounted!int(5);
assert(rc1 == 5);
// No more allocation, add just one extra reference count
auto rc2 = rc1;
// Reference semantics
rc2 = 42;
assert(rc1 == 42);
// the pair will be freed when rc1 and rc2 go out of scope
}
pure @system unittest
{
RefCounted!int* p;
{
auto rc1 = RefCounted!int(5);
p = &rc1;
assert(rc1 == 5);
assert(rc1._refCounted._store._count == 1);
auto rc2 = rc1;
assert(rc1._refCounted._store._count == 2);
// Reference semantics
rc2 = 42;
assert(rc1 == 42);
rc2 = rc2;
assert(rc2._refCounted._store._count == 2);
rc1 = rc2;
assert(rc1._refCounted._store._count == 2);
}
assert(p._refCounted._store == null);
// RefCounted as a member
struct A
{
RefCounted!int x;
this(int y)
{
x._refCounted.initialize(y);
}
A copy()
{
auto another = this;
return another;
}
}
auto a = A(4);
auto b = a.copy();
assert(a.x._refCounted._store._count == 2, "BUG 4356 still unfixed");
}
pure @system nothrow @nogc unittest
{
import std.algorithm.mutation : swap;
RefCounted!int p1, p2;
swap(p1, p2);
}
// 6606
@safe pure nothrow @nogc unittest
{
union U {
size_t i;
void* p;
}
struct S {
U u;
}
alias SRC = RefCounted!S;
}
// 6436
@system pure unittest
{
struct S { this(ref int val) { assert(val == 3); ++val; } }
int val = 3;
auto s = RefCounted!S(val);
assert(val == 4);
}
// gc_addRange coverage
@system pure unittest
{
struct S { int* p; }
auto s = RefCounted!S(null);
}
@system pure nothrow @nogc unittest
{
RefCounted!int a;
a = 5; //This should not assert
assert(a == 5);
RefCounted!int b;
b = a; //This should not assert either
assert(b == 5);
RefCounted!(int*) c;
}
/**
* Initializes a `RefCounted` with `val`. The template parameter
* `T` of `RefCounted` is inferred from `val`.
* This function can be used to move non-copyable values to the heap.
* It also disables the `autoInit` option of `RefCounted`.
*
* Params:
* val = The value to be reference counted
* Returns:
* An initialized `RefCounted` containing `val`.
* See_Also:
* $(HTTP en.cppreference.com/w/cpp/memory/shared_ptr/make_shared, C++'s make_shared)
*/
RefCounted!(T, RefCountedAutoInitialize.no) refCounted(T)(T val)
{
typeof(return) res;
res._refCounted.move(val);
return res;
}
///
@system unittest
{
static struct File
{
string name;
@disable this(this); // not copyable
~this() { name = null; }
}
auto file = File("name");
assert(file.name == "name");
// file cannot be copied and has unique ownership
static assert(!__traits(compiles, {auto file2 = file;}));
// make the file refcounted to share ownership
import std.algorithm.mutation : move;
auto rcFile = refCounted(move(file));
assert(rcFile.name == "name");
assert(file.name == null);
auto rcFile2 = rcFile;
assert(rcFile.refCountedStore.refCount == 2);
// file gets properly closed when last reference is dropped
}
/**
Creates a proxy for the value `a` that will forward all operations
while disabling implicit conversions. The aliased item `a` must be
an $(B lvalue). This is useful for creating a new type from the
"base" type (though this is $(B not) a subtype-supertype
relationship; the new type is not related to the old type in any way,
by design).
The new type supports all operations that the underlying type does,
including all operators such as `+`, `--`, `<`, `[]`, etc.
Params:
a = The value to act as a proxy for all operations. It must
be an lvalue.
*/
mixin template Proxy(alias a)
{
private alias ValueType = typeof({ return a; }());
/* Determine if 'T.a' can referenced via a const(T).
* Use T* as the parameter because 'scope' inference needs a fully
* analyzed T, which doesn't work when accessibleFrom() is used in a
* 'static if' in the definition of Proxy or T.
*/
private enum bool accessibleFrom(T) =
is(typeof((T* self){ cast(void) mixin("(*self)."~__traits(identifier, a)); }));
static if (is(typeof(this) == class))
{
override bool opEquals(Object o)
{
if (auto b = cast(typeof(this))o)
{
return a == mixin("b."~__traits(identifier, a));
}
return false;
}
bool opEquals(T)(T b)
if (is(ValueType : T) || is(typeof(a.opEquals(b))) || is(typeof(b.opEquals(a))))
{
static if (is(typeof(a.opEquals(b))))
return a.opEquals(b);
else static if (is(typeof(b.opEquals(a))))
return b.opEquals(a);
else
return a == b;
}
override int opCmp(Object o)
{
if (auto b = cast(typeof(this))o)
{
return a < mixin("b."~__traits(identifier, a)) ? -1
: a > mixin("b."~__traits(identifier, a)) ? +1 : 0;
}
static if (is(ValueType == class))
return a.opCmp(o);
else
throw new Exception("Attempt to compare a "~typeid(this).toString~" and a "~typeid(o).toString);
}
int opCmp(T)(auto ref const T b)
if (is(ValueType : T) || is(typeof(a.opCmp(b))) || is(typeof(b.opCmp(a))))
{
static if (is(typeof(a.opCmp(b))))
return a.opCmp(b);
else static if (is(typeof(b.opCmp(a))))
return -b.opCmp(b);
else
return a < b ? -1 : a > b ? +1 : 0;
}
static if (accessibleFrom!(const typeof(this)))
{
override hash_t toHash() const nothrow @safe
{
static if (__traits(compiles, .hashOf(a)))
return .hashOf(a);
else
// Workaround for when .hashOf is not both @safe and nothrow.
{
static if (is(typeof(&a) == ValueType*))
alias v = a;
else
auto v = a; // if a is (property) function
// BUG: Improperly casts away `shared`!
return typeid(ValueType).getHash((() @trusted => cast(const void*) &v)());
}
}
}
}
else
{
auto ref opEquals(this X, B)(auto ref B b)
{
static if (is(immutable B == immutable typeof(this)))
{
return a == mixin("b."~__traits(identifier, a));
}
else
return a == b;
}
auto ref opCmp(this X, B)(auto ref B b)
if (!is(typeof(a.opCmp(b))) || !is(typeof(b.opCmp(a))))
{
static if (is(typeof(a.opCmp(b))))
return a.opCmp(b);
else static if (is(typeof(b.opCmp(a))))
return -b.opCmp(a);
else static if (isFloatingPoint!ValueType || isFloatingPoint!B)
return a < b ? -1 : a > b ? +1 : a == b ? 0 : float.nan;
else
return a < b ? -1 : (a > b);
}
static if (accessibleFrom!(const typeof(this)))
{
hash_t toHash() const nothrow @safe
{
static if (__traits(compiles, .hashOf(a)))
return .hashOf(a);
else
// Workaround for when .hashOf is not both @safe and nothrow.
{
static if (is(typeof(&a) == ValueType*))
alias v = a;
else
auto v = a; // if a is (property) function
// BUG: Improperly casts away `shared`!
return typeid(ValueType).getHash((() @trusted => cast(const void*) &v)());
}
}
}
}
auto ref opCall(this X, Args...)(auto ref Args args) { return a(args); }
auto ref opCast(T, this X)() { return cast(T) a; }
auto ref opIndex(this X, D...)(auto ref D i) { return a[i]; }
auto ref opSlice(this X )() { return a[]; }
auto ref opSlice(this X, B, E)(auto ref B b, auto ref E e) { return a[b .. e]; }
auto ref opUnary (string op, this X )() { return mixin(op~"a"); }
auto ref opIndexUnary(string op, this X, D...)(auto ref D i) { return mixin(op~"a[i]"); }
auto ref opSliceUnary(string op, this X )() { return mixin(op~"a[]"); }
auto ref opSliceUnary(string op, this X, B, E)(auto ref B b, auto ref E e) { return mixin(op~"a[b .. e]"); }
auto ref opBinary(string op, this X, B)(auto ref B b)
if (op == "in" && is(typeof(a in b)) || op != "in")
{
return mixin("a "~op~" b");
}
auto ref opBinaryRight(string op, this X, B)(auto ref B b) { return mixin("b "~op~" a"); }
static if (!is(typeof(this) == class))
{
import std.traits;
static if (isAssignable!ValueType)
{
auto ref opAssign(this X)(auto ref typeof(this) v)
{
a = mixin("v."~__traits(identifier, a));
return this;
}
}
else
{
@disable void opAssign(this X)(auto ref typeof(this) v);
}
}
auto ref opAssign (this X, V )(auto ref V v) if (!is(V == typeof(this))) { return a = v; }
auto ref opIndexAssign(this X, V, D...)(auto ref V v, auto ref D i) { return a[i] = v; }
auto ref opSliceAssign(this X, V )(auto ref V v) { return a[] = v; }
auto ref opSliceAssign(this X, V, B, E)(auto ref V v, auto ref B b, auto ref E e) { return a[b .. e] = v; }
auto ref opOpAssign (string op, this X, V )(auto ref V v)
{
return mixin("a " ~op~"= v");
}
auto ref opIndexOpAssign(string op, this X, V, D...)(auto ref V v, auto ref D i)
{
return mixin("a[i] " ~op~"= v");
}
auto ref opSliceOpAssign(string op, this X, V )(auto ref V v)
{
return mixin("a[] " ~op~"= v");
}
auto ref opSliceOpAssign(string op, this X, V, B, E)(auto ref V v, auto ref B b, auto ref E e)
{
return mixin("a[b .. e] "~op~"= v");
}
template opDispatch(string name)
{
static if (is(typeof(__traits(getMember, a, name)) == function))
{
// non template function
auto ref opDispatch(this X, Args...)(auto ref Args args) { return mixin("a."~name~"(args)"); }
}
else static if (is(typeof({ enum x = mixin("a."~name); })))
{
// built-in type field, manifest constant, and static non-mutable field
enum opDispatch = mixin("a."~name);
}
else static if (is(typeof(mixin("a."~name))) || __traits(getOverloads, a, name).length != 0)
{
// field or property function
@property auto ref opDispatch(this X)() { return mixin("a."~name); }
@property auto ref opDispatch(this X, V)(auto ref V v) { return mixin("a."~name~" = v"); }
}
else
{
// member template
template opDispatch(T...)
{
enum targs = T.length ? "!T" : "";
auto ref opDispatch(this X, Args...)(auto ref Args args){ return mixin("a."~name~targs~"(args)"); }
}
}
}
import std.traits : isArray;
static if (isArray!ValueType)
{
auto opDollar() const { return a.length; }
}
else static if (is(typeof(a.opDollar!0)))
{
auto ref opDollar(size_t pos)() { return a.opDollar!pos(); }
}
else static if (is(typeof(a.opDollar) == function))
{
auto ref opDollar() { return a.opDollar(); }
}
else static if (is(typeof(a.opDollar)))
{
alias opDollar = a.opDollar;
}
}
///
@safe unittest
{
struct MyInt
{
private int value;
mixin Proxy!value;
this(int n){ value = n; }
}
MyInt n = 10;
// Enable operations that original type has.
++n;
assert(n == 11);
assert(n * 2 == 22);
void func(int n) { }
// Disable implicit conversions to original type.
//int x = n;
//func(n);
}
///The proxied value must be an $(B lvalue).
@safe unittest
{
struct NewIntType
{
//Won't work; the literal '1'
//is an rvalue, not an lvalue
//mixin Proxy!1;
//Okay, n is an lvalue
int n;
mixin Proxy!n;
this(int n) { this.n = n; }
}
NewIntType nit = 0;
nit++;
assert(nit == 1);
struct NewObjectType
{
Object obj;
//Ok, obj is an lvalue
mixin Proxy!obj;
this (Object o) { obj = o; }
}
NewObjectType not = new Object();
assert(__traits(compiles, not.toHash()));
}
/**
There is one exception to the fact that the new type is not related to the
old type. $(DDSUBLINK spec/function,pseudo-member, Pseudo-member)
functions are usable with the new type; they will be forwarded on to the
proxied value.
*/
@safe unittest
{
import std.math;
float f = 1.0;
assert(!f.isInfinity);
struct NewFloat
{
float _;
mixin Proxy!_;
this(float f) { _ = f; }
}
NewFloat nf = 1.0f;
assert(!nf.isInfinity);
}
@safe unittest
{
static struct MyInt
{
private int value;
mixin Proxy!value;
this(int n) inout { value = n; }
enum str = "str";
static immutable arr = [1,2,3];
}
static foreach (T; AliasSeq!(MyInt, const MyInt, immutable MyInt))
{{
T m = 10;
static assert(!__traits(compiles, { int x = m; }));
static assert(!__traits(compiles, { void func(int n){} func(m); }));
assert(m == 10);
assert(m != 20);
assert(m < 20);
assert(+m == 10);
assert(-m == -10);
assert(cast(double) m == 10.0);
assert(m + 10 == 20);
assert(m - 5 == 5);
assert(m * 20 == 200);
assert(m / 2 == 5);
assert(10 + m == 20);
assert(15 - m == 5);
assert(20 * m == 200);
assert(50 / m == 5);
static if (is(T == MyInt)) // mutable
{
assert(++m == 11);
assert(m++ == 11); assert(m == 12);
assert(--m == 11);
assert(m-- == 11); assert(m == 10);
m = m;
m = 20; assert(m == 20);
}
static assert(T.max == int.max);
static assert(T.min == int.min);
static assert(T.init == int.init);
static assert(T.str == "str");
static assert(T.arr == [1,2,3]);
}}
}
@system unittest
{
static struct MyArray
{
private int[] value;
mixin Proxy!value;
this(int[] arr) { value = arr; }
this(immutable int[] arr) immutable { value = arr; }
}
static foreach (T; AliasSeq!(MyArray, const MyArray, immutable MyArray))
{{
static if (is(T == immutable) && !is(typeof({ T a = [1,2,3,4]; })))
T a = [1,2,3,4].idup; // workaround until qualified ctor is properly supported
else
T a = [1,2,3,4];
assert(a == [1,2,3,4]);
assert(a != [5,6,7,8]);
assert(+a[0] == 1);
version (LittleEndian)
assert(cast(ulong[]) a == [0x0000_0002_0000_0001, 0x0000_0004_0000_0003]);
else
assert(cast(ulong[]) a == [0x0000_0001_0000_0002, 0x0000_0003_0000_0004]);
assert(a ~ [10,11] == [1,2,3,4,10,11]);
assert(a[0] == 1);
assert(a[] == [1,2,3,4]);
assert(a[2 .. 4] == [3,4]);
static if (is(T == MyArray)) // mutable
{
a = a;
a = [5,6,7,8]; assert(a == [5,6,7,8]);
a[0] = 0; assert(a == [0,6,7,8]);
a[] = 1; assert(a == [1,1,1,1]);
a[0 .. 3] = 2; assert(a == [2,2,2,1]);
a[0] += 2; assert(a == [4,2,2,1]);
a[] *= 2; assert(a == [8,4,4,2]);
a[0 .. 2] /= 2; assert(a == [4,2,4,2]);
}
}}
}
@system unittest
{
class Foo
{
int field;
@property int val1() const { return field; }
@property void val1(int n) { field = n; }
@property ref int val2() { return field; }
int func(int x, int y) const { return x; }
void func1(ref int a) { a = 9; }
T ifti1(T)(T t) { return t; }
void ifti2(Args...)(Args args) { }
void ifti3(T, Args...)(Args args) { }
T opCast(T)(){ return T.init; }
T tempfunc(T)() { return T.init; }
}
class Hoge
{
Foo foo;
mixin Proxy!foo;
this(Foo f) { foo = f; }
}
auto h = new Hoge(new Foo());
int n;
static assert(!__traits(compiles, { Foo f = h; }));
// field
h.field = 1; // lhs of assign
n = h.field; // rhs of assign
assert(h.field == 1); // lhs of BinExp
assert(1 == h.field); // rhs of BinExp
assert(n == 1);
// getter/setter property function
h.val1 = 4;
n = h.val1;
assert(h.val1 == 4);
assert(4 == h.val1);
assert(n == 4);
// ref getter property function
h.val2 = 8;
n = h.val2;
assert(h.val2 == 8);
assert(8 == h.val2);
assert(n == 8);
// member function
assert(h.func(2,4) == 2);
h.func1(n);
assert(n == 9);
// IFTI
assert(h.ifti1(4) == 4);
h.ifti2(4);
h.ifti3!int(4, 3);
// bug5896 test
assert(h.opCast!int() == 0);
assert(cast(int) h == 0);
const ih = new const Hoge(new Foo());
static assert(!__traits(compiles, ih.opCast!int()));
static assert(!__traits(compiles, cast(int) ih));
// template member function
assert(h.tempfunc!int() == 0);
}
@system unittest // about Proxy inside a class
{
class MyClass
{
int payload;
mixin Proxy!payload;
this(int i){ payload = i; }
string opCall(string msg){ return msg; }
int pow(int i){ return payload ^^ i; }
}
class MyClass2
{
MyClass payload;
mixin Proxy!payload;
this(int i){ payload = new MyClass(i); }
}
class MyClass3
{
int payload;
mixin Proxy!payload;
this(int i){ payload = i; }
}
// opEquals
Object a = new MyClass(5);
Object b = new MyClass(5);
Object c = new MyClass2(5);
Object d = new MyClass3(5);
assert(a == b);
assert((cast(MyClass) a) == 5);
assert(5 == (cast(MyClass) b));
assert(5 == cast(MyClass2) c);
assert(a != d);
assert(c != a);
// oops! above line is unexpected, isn't it?
// the reason is below.
// MyClass2.opEquals knows MyClass but,
// MyClass.opEquals doesn't know MyClass2.
// so, c.opEquals(a) is true, but a.opEquals(c) is false.
// furthermore, opEquals(T) couldn't be invoked.
assert((cast(MyClass2) c) != (cast(MyClass) a));
// opCmp
Object e = new MyClass2(7);
assert(a < cast(MyClass2) e); // OK. and
assert(e > a); // OK, but...
// assert(a < e); // RUNTIME ERROR!
// assert((cast(MyClass) a) < e); // RUNTIME ERROR!
assert(3 < cast(MyClass) a);
assert((cast(MyClass2) e) < 11);
// opCall
assert((cast(MyClass2) e)("hello") == "hello");
// opCast
assert((cast(MyClass)(cast(MyClass2) c)) == a);
assert((cast(int)(cast(MyClass2) c)) == 5);
// opIndex
class MyClass4
{
string payload;
mixin Proxy!payload;
this(string s){ payload = s; }
}
class MyClass5
{
MyClass4 payload;
mixin Proxy!payload;
this(string s){ payload = new MyClass4(s); }
}
auto f = new MyClass4("hello");
assert(f[1] == 'e');
auto g = new MyClass5("hello");
assert(f[1] == 'e');
// opSlice
assert(f[2 .. 4] == "ll");
// opUnary
assert(-(cast(MyClass2) c) == -5);
// opBinary
assert((cast(MyClass) a) + (cast(MyClass2) c) == 10);
assert(5 + cast(MyClass) a == 10);
// opAssign
(cast(MyClass2) c) = 11;
assert((cast(MyClass2) c) == 11);
(cast(MyClass2) c) = new MyClass(13);
assert((cast(MyClass2) c) == 13);
// opOpAssign
assert((cast(MyClass2) c) += 4);
assert((cast(MyClass2) c) == 17);
// opDispatch
assert((cast(MyClass2) c).pow(2) == 289);
// opDollar
assert(f[2..$-1] == "ll");
// toHash
int[Object] hash;
hash[a] = 19;
hash[c] = 21;
assert(hash[b] == 19);
assert(hash[c] == 21);
}
@safe unittest
{
struct MyInt
{
int payload;
mixin Proxy!payload;
}
MyInt v;
v = v;
struct Foo
{
@disable void opAssign(typeof(this));
}
struct MyFoo
{
Foo payload;
mixin Proxy!payload;
}
MyFoo f;
static assert(!__traits(compiles, f = f));
struct MyFoo2
{
Foo payload;
mixin Proxy!payload;
// override default Proxy behavior
void opAssign(typeof(this) rhs){}
}
MyFoo2 f2;
f2 = f2;
}
@safe unittest
{
// bug8613
static struct Name
{
mixin Proxy!val;
private string val;
this(string s) { val = s; }
}
bool[Name] names;
names[Name("a")] = true;
bool* b = Name("a") in names;
}
// excludes struct S; it's 'mixin Proxy!foo' doesn't compile with -dip1000
version (DIP1000) {} else
@system unittest
{
// bug14213, using function for the payload
static struct S
{
int foo() { return 12; }
mixin Proxy!foo;
}
S s;
assert(s + 1 == 13);
assert(s * 2 == 24);
}
@system unittest
{
static class C
{
int foo() { return 12; }
mixin Proxy!foo;
}
C c = new C();
}
// Check all floating point comparisons for both Proxy and Typedef,
// also against int and a Typedef!int, to be as regression-proof
// as possible. bug 15561
@safe unittest
{
static struct MyFloatImpl
{
float value;
mixin Proxy!value;
}
static void allFail(T0, T1)(T0 a, T1 b)
{
assert(!(a == b));
assert(!(a<b));
assert(!(a <= b));
assert(!(a>b));
assert(!(a >= b));
}
static foreach (T1; AliasSeq!(MyFloatImpl, Typedef!float, Typedef!double,
float, real, Typedef!int, int))
{
static foreach (T2; AliasSeq!(MyFloatImpl, Typedef!float))
{{
T1 a;
T2 b;
static if (isFloatingPoint!T1 || isFloatingPoint!(TypedefType!T1))
allFail(a, b);
a = 3;
allFail(a, b);
b = 4;
assert(a != b);
assert(a<b);
assert(a <= b);
assert(!(a>b));
assert(!(a >= b));
a = 4;
assert(a == b);
assert(!(a<b));
assert(a <= b);
assert(!(a>b));
assert(a >= b);
}}
}
}
/**
$(B Typedef) allows the creation of a unique type which is
based on an existing type. Unlike the `alias` feature,
$(B Typedef) ensures the two types are not considered as equals.
Params:
init = Optional initial value for the new type.
cookie = Optional, used to create multiple unique types which are
based on the same origin type `T`
Note: If a library routine cannot handle the Typedef type,
you can use the `TypedefType` template to extract the
type which the Typedef wraps.
*/
struct Typedef(T, T init = T.init, string cookie=null)
{
private T Typedef_payload = init;
// issue 18415 : prevent default construction if original type does too.
static if ((is(T == struct) || is(T == union)) && !is(typeof({T t;})))
{
@disable this();
}
this(T init)
{
Typedef_payload = init;
}
this(Typedef tdef)
{
this(tdef.Typedef_payload);
}
// We need to add special overload for cast(Typedef!X) exp,
// thus we can't simply inherit Proxy!Typedef_payload
T2 opCast(T2 : Typedef!(T, Unused), this X, T, Unused...)()
{
return T2(cast(T) Typedef_payload);
}
auto ref opCast(T2, this X)()
{
return cast(T2) Typedef_payload;
}
mixin Proxy!Typedef_payload;
pure nothrow @nogc @safe @property
{
alias TD = typeof(this);
static if (isIntegral!T)
{
static TD min() {return TD(T.min);}
static TD max() {return TD(T.max);}
}
else static if (isFloatingPoint!T)
{
static TD infinity() {return TD(T.infinity);}
static TD nan() {return TD(T.nan);}
static TD dig() {return TD(T.dig);}
static TD epsilon() {return TD(T.epsilon);}
static TD mant_dig() {return TD(T.mant_dig);}
static TD max_10_exp() {return TD(T.max_10_exp);}
static TD max_exp() {return TD(T.max_exp);}
static TD min_10_exp() {return TD(T.min_10_exp);}
static TD min_exp() {return TD(T.min_exp);}
static TD max() {return TD(T.max);}
static TD min_normal() {return TD(T.min_normal);}
TD re() {return TD(Typedef_payload.re);}
TD im() {return TD(Typedef_payload.im);}
}
}
/**
* Convert wrapped value to a human readable string
*/
string toString(this T)()
{
import std.array : appender;
auto app = appender!string();
auto spec = singleSpec("%s");
toString(app, spec);
return app.data;
}
/// ditto
void toString(this T, W)(ref W writer, const ref FormatSpec!char fmt)
if (isOutputRange!(W, char))
{
formatValue(writer, Typedef_payload, fmt);
}
///
@safe unittest
{
import std.conv : to;
int i = 123;
auto td = Typedef!int(i);
assert(i.to!string == td.to!string);
}
}
///
@safe unittest
{
alias MyInt = Typedef!int;
MyInt foo = 10;
foo++;
assert(foo == 11);
}
/// custom initialization values
@safe unittest
{
alias MyIntInit = Typedef!(int, 42);
static assert(is(TypedefType!MyIntInit == int));
static assert(MyIntInit() == 42);
}
/// Typedef creates a new type
@safe unittest
{
alias MyInt = Typedef!int;
static void takeInt(int) {}
static void takeMyInt(MyInt) {}
int i;
takeInt(i); // ok
static assert(!__traits(compiles, takeMyInt(i)));
MyInt myInt;
static assert(!__traits(compiles, takeInt(myInt)));
takeMyInt(myInt); // ok
}
/// Use the optional `cookie` argument to create different types of the same base type
@safe unittest
{
alias TypeInt1 = Typedef!int;
alias TypeInt2 = Typedef!int;
// The two Typedefs are the same type.
static assert(is(TypeInt1 == TypeInt2));
alias MoneyEuros = Typedef!(float, float.init, "euros");
alias MoneyDollars = Typedef!(float, float.init, "dollars");
// The two Typedefs are _not_ the same type.
static assert(!is(MoneyEuros == MoneyDollars));
}
/**
Get the underlying type which a `Typedef` wraps.
If `T` is not a `Typedef` it will alias itself to `T`.
*/
template TypedefType(T)
{
static if (is(T : Typedef!Arg, Arg))
alias TypedefType = Arg;
else
alias TypedefType = T;
}
///
@safe unittest
{
import std.conv : to;
alias MyInt = Typedef!int;
static assert(is(TypedefType!MyInt == int));
/// Instantiating with a non-Typedef will return that type
static assert(is(TypedefType!int == int));
string num = "5";
// extract the needed type
MyInt myInt = MyInt( num.to!(TypedefType!MyInt) );
assert(myInt == 5);
// cast to the underlying type to get the value that's being wrapped
int x = cast(TypedefType!MyInt) myInt;
alias MyIntInit = Typedef!(int, 42);
static assert(is(TypedefType!MyIntInit == int));
static assert(MyIntInit() == 42);
}
@safe unittest
{
Typedef!int x = 10;
static assert(!__traits(compiles, { int y = x; }));
static assert(!__traits(compiles, { long z = x; }));
Typedef!int y = 10;
assert(x == y);
static assert(Typedef!int.init == int.init);
Typedef!(float, 1.0) z; // specifies the init
assert(z == 1.0);
static assert(typeof(z).init == 1.0);
alias Dollar = Typedef!(int, 0, "dollar");
alias Yen = Typedef!(int, 0, "yen");
static assert(!is(Dollar == Yen));
Typedef!(int[3]) sa;
static assert(sa.length == 3);
static assert(typeof(sa).length == 3);
Typedef!(int[3]) dollar1;
assert(dollar1[0..$] is dollar1[0 .. 3]);
Typedef!(int[]) dollar2;
dollar2.length = 3;
assert(dollar2[0..$] is dollar2[0 .. 3]);
static struct Dollar1
{
static struct DollarToken {}
enum opDollar = DollarToken.init;
auto opSlice(size_t, DollarToken) { return 1; }
auto opSlice(size_t, size_t) { return 2; }
}
Typedef!Dollar1 drange1;
assert(drange1[0..$] == 1);
assert(drange1[0 .. 1] == 2);
static struct Dollar2
{
size_t opDollar(size_t pos)() { return pos == 0 ? 1 : 100; }
size_t opIndex(size_t i, size_t j) { return i + j; }
}
Typedef!Dollar2 drange2;
assert(drange2[$, $] == 101);
static struct Dollar3
{
size_t opDollar() { return 123; }
size_t opIndex(size_t i) { return i; }
}
Typedef!Dollar3 drange3;
assert(drange3[$] == 123);
}
@safe @nogc pure nothrow unittest // Bugzilla 18415
{
struct NoDefCtorS{@disable this();}
union NoDefCtorU{@disable this();}
static assert(!is(typeof({Typedef!NoDefCtorS s;})));
static assert(!is(typeof({Typedef!NoDefCtorU u;})));
}
@safe @nogc pure nothrow unittest // Bugzilla 11703
{
alias I = Typedef!int;
static assert(is(typeof(I.min) == I));
static assert(is(typeof(I.max) == I));
alias F = Typedef!double;
static assert(is(typeof(F.infinity) == F));
static assert(is(typeof(F.epsilon) == F));
F f;
assert(!is(typeof(F.re).stringof == double));
assert(!is(typeof(F.im).stringof == double));
}
@safe unittest
{
// bug8655
import std.typecons;
import std.bitmanip;
static import core.stdc.config;
alias c_ulong = Typedef!(core.stdc.config.c_ulong);
static struct Foo
{
mixin(bitfields!(
c_ulong, "NameOffset", 31,
c_ulong, "NameIsString", 1
));
}
}
@safe unittest // Issue 12596
{
import std.typecons;
alias TD = Typedef!int;
TD x = TD(1);
TD y = TD(x);
assert(x == y);
}
@safe unittest // about toHash
{
import std.typecons;
{
alias TD = Typedef!int;
int[TD] td;
td[TD(1)] = 1;
assert(td[TD(1)] == 1);
}
{
alias TD = Typedef!(int[]);
int[TD] td;
td[TD([1,2,3,4])] = 2;
assert(td[TD([1,2,3,4])] == 2);
}
{
alias TD = Typedef!(int[][]);
int[TD] td;
td[TD([[1,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1]])] = 3;
assert(td[TD([[1,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1]])] == 3);
}
{
struct MyStruct{ int x; }
alias TD = Typedef!MyStruct;
int[TD] td;
td[TD(MyStruct(10))] = 4;
assert(TD(MyStruct(20)) !in td);
assert(td[TD(MyStruct(10))] == 4);
}
{
static struct MyStruct2
{
int x;
size_t toHash() const nothrow @safe { return x; }
bool opEquals(ref const MyStruct2 r) const { return r.x == x; }
}
alias TD = Typedef!MyStruct2;
int[TD] td;
td[TD(MyStruct2(50))] = 5;
assert(td[TD(MyStruct2(50))] == 5);
}
{
class MyClass{}
alias TD = Typedef!MyClass;
int[TD] td;
auto c = new MyClass;
td[TD(c)] = 6;
assert(TD(new MyClass) !in td);
assert(td[TD(c)] == 6);
}
}
@system unittest
{
alias String = Typedef!(char[]);
alias CString = Typedef!(const(char)[]);
CString cs = "fubar";
String s = cast(String) cs;
assert(cs == s);
char[] s2 = cast(char[]) cs;
const(char)[] cs2 = cast(const(char)[])s;
assert(s2 == cs2);
}
@system unittest // toString
{
import std.meta : AliasSeq;
import std.conv : to;
struct TestS {}
class TestC {}
static foreach (T; AliasSeq!(int, bool, float, double, real,
char, dchar, wchar,
TestS, TestC,
int*, int[], int[2], int[int]))
{{
T t;
Typedef!T td;
Typedef!(const T) ctd;
Typedef!(immutable T) itd;
assert(t.to!string() == td.to!string());
static if (!(is(T == TestS) || is(T == TestC)))
{
assert(t.to!string() == ctd.to!string());
assert(t.to!string() == itd.to!string());
}
}}
}
/**
Allocates a `class` object right inside the current scope,
therefore avoiding the overhead of `new`. This facility is unsafe;
it is the responsibility of the user to not escape a reference to the
object outside the scope.
The class destructor will be called when the result of `scoped()` is
itself destroyed.
Scoped class instances can be embedded in a parent `class` or `struct`,
just like a child struct instance. Scoped member variables must have
type `typeof(scoped!Class(args))`, and be initialized with a call to
scoped. See below for an example.
Note:
It's illegal to move a class instance even if you are sure there
are no pointers to it. As such, it is illegal to move a scoped object.
*/
template scoped(T)
if (is(T == class))
{
// _d_newclass now use default GC alignment (looks like (void*).sizeof * 2 for
// small objects). We will just use the maximum of filed alignments.
alias alignment = classInstanceAlignment!T;
alias aligned = _alignUp!alignment;
static struct Scoped
{
// Addition of `alignment` is required as `Scoped_store` can be misaligned in memory.
private void[aligned(__traits(classInstanceSize, T) + size_t.sizeof) + alignment] Scoped_store = void;
@property inout(T) Scoped_payload() inout
{
void* alignedStore = cast(void*) aligned(cast(size_t) Scoped_store.ptr);
// As `Scoped` can be unaligned moved in memory class instance should be moved accordingly.
immutable size_t d = alignedStore - Scoped_store.ptr;
size_t* currD = cast(size_t*) &Scoped_store[$ - size_t.sizeof];
if (d != *currD)
{
import core.stdc.string : memmove;
memmove(alignedStore, Scoped_store.ptr + *currD, __traits(classInstanceSize, T));
*currD = d;
}
return cast(inout(T)) alignedStore;
}
alias Scoped_payload this;
@disable this();
@disable this(this);
~this()
{
// `destroy` will also write .init but we have no functions in druntime
// for deterministic finalization and memory releasing for now.
.destroy(Scoped_payload);
}
}
/** Returns the _scoped object.
Params: args = Arguments to pass to `T`'s constructor.
*/
@system auto scoped(Args...)(auto ref Args args)
{
import std.conv : emplace;
Scoped result = void;
void* alignedStore = cast(void*) aligned(cast(size_t) result.Scoped_store.ptr);
immutable size_t d = alignedStore - result.Scoped_store.ptr;
*cast(size_t*) &result.Scoped_store[$ - size_t.sizeof] = d;
emplace!(Unqual!T)(result.Scoped_store[d .. $ - size_t.sizeof], args);
return result;
}
}
///
@system unittest
{
class A
{
int x;
this() {x = 0;}
this(int i){x = i;}
~this() {}
}
// Standard usage, constructing A on the stack
auto a1 = scoped!A();
a1.x = 42;
// Result of `scoped` call implicitly converts to a class reference
A aRef = a1;
assert(aRef.x == 42);
// Scoped destruction
{
auto a2 = scoped!A(1);
assert(a2.x == 1);
aRef = a2;
// a2 is destroyed here, calling A's destructor
}
// aRef is now an invalid reference
// Here the temporary scoped A is immediately destroyed.
// This means the reference is then invalid.
version (Bug)
{
// Wrong, should use `auto`
A invalid = scoped!A();
}
// Restrictions
version (Bug)
{
import std.algorithm.mutation : move;
auto invalid = a1.move; // illegal, scoped objects can't be moved
}
static assert(!is(typeof({
auto e1 = a1; // illegal, scoped objects can't be copied
assert([a1][0].x == 42); // ditto
})));
static assert(!is(typeof({
alias ScopedObject = typeof(a1);
auto e2 = ScopedObject(); // illegal, must be built via scoped!A
auto e3 = ScopedObject(1); // ditto
})));
// Use with alias
alias makeScopedA = scoped!A;
auto a3 = makeScopedA();
auto a4 = makeScopedA(1);
// Use as member variable
struct B
{
typeof(scoped!A()) a; // note the trailing parentheses
this(int i)
{
// construct member
a = scoped!A(i);
}
}
// Stack-allocate
auto b1 = B(5);
aRef = b1.a;
assert(aRef.x == 5);
destroy(b1); // calls A's destructor for b1.a
// aRef is now an invalid reference
// Heap-allocate
auto b2 = new B(6);
assert(b2.a.x == 6);
destroy(*b2); // calls A's destructor for b2.a
}
private size_t _alignUp(size_t alignment)(size_t n)
if (alignment > 0 && !((alignment - 1) & alignment))
{
enum badEnd = alignment - 1; // 0b11, 0b111, ...
return (n + badEnd) & ~badEnd;
}
@system unittest // Issue 6580 testcase
{
enum alignment = (void*).alignof;
static class C0 { }
static class C1 { byte b; }
static class C2 { byte[2] b; }
static class C3 { byte[3] b; }
static class C7 { byte[7] b; }
static assert(scoped!C0().sizeof % alignment == 0);
static assert(scoped!C1().sizeof % alignment == 0);
static assert(scoped!C2().sizeof % alignment == 0);
static assert(scoped!C3().sizeof % alignment == 0);
static assert(scoped!C7().sizeof % alignment == 0);
enum longAlignment = long.alignof;
static class C1long
{
long long_; byte byte_ = 4;
this() { }
this(long _long, ref int i) { long_ = _long; ++i; }
}
static class C2long { byte[2] byte_ = [5, 6]; long long_ = 7; }
static assert(scoped!C1long().sizeof % longAlignment == 0);
static assert(scoped!C2long().sizeof % longAlignment == 0);
void alignmentTest()
{
int var = 5;
auto c1long = scoped!C1long(3, var);
assert(var == 6);
auto c2long = scoped!C2long();
assert(cast(uint)&c1long.long_ % longAlignment == 0);
assert(cast(uint)&c2long.long_ % longAlignment == 0);
assert(c1long.long_ == 3 && c1long.byte_ == 4);
assert(c2long.byte_ == [5, 6] && c2long.long_ == 7);
}
alignmentTest();
version (DigitalMars)
{
void test(size_t size)
{
import core.stdc.stdlib;
alloca(size);
alignmentTest();
}
foreach (i; 0 .. 10)
test(i);
}
else
{
void test(size_t size)()
{
byte[size] arr;
alignmentTest();
}
static foreach (i; 0 .. 11)
test!i();
}
}
@system unittest // Original Issue 6580 testcase
{
class C { int i; byte b; }
auto sa = [scoped!C(), scoped!C()];
assert(cast(uint)&sa[0].i % int.alignof == 0);
assert(cast(uint)&sa[1].i % int.alignof == 0); // fails
}
@system unittest
{
class A { int x = 1; }
auto a1 = scoped!A();
assert(a1.x == 1);
auto a2 = scoped!A();
a1.x = 42;
a2.x = 53;
assert(a1.x == 42);
}
@system unittest
{
class A { int x = 1; this() { x = 2; } }
auto a1 = scoped!A();
assert(a1.x == 2);
auto a2 = scoped!A();
a1.x = 42;
a2.x = 53;
assert(a1.x == 42);
}
@system unittest
{
class A { int x = 1; this(int y) { x = y; } ~this() {} }
auto a1 = scoped!A(5);
assert(a1.x == 5);
auto a2 = scoped!A(42);
a1.x = 42;
a2.x = 53;
assert(a1.x == 42);
}
@system unittest
{
class A { static bool dead; ~this() { dead = true; } }
class B : A { static bool dead; ~this() { dead = true; } }
{
auto b = scoped!B();
}
assert(B.dead, "asdasd");
assert(A.dead, "asdasd");
}
@system unittest // Issue 8039 testcase
{
static int dels;
static struct S { ~this(){ ++dels; } }
static class A { S s; }
dels = 0; { scoped!A(); }
assert(dels == 1);
static class B { S[2] s; }
dels = 0; { scoped!B(); }
assert(dels == 2);
static struct S2 { S[3] s; }
static class C { S2[2] s; }
dels = 0; { scoped!C(); }
assert(dels == 6);
static class D: A { S2[2] s; }
dels = 0; { scoped!D(); }
assert(dels == 1+6);
}
@system unittest
{
// bug4500
class A
{
this() { a = this; }
this(int i) { a = this; }
A a;
bool check() { return this is a; }
}
auto a1 = scoped!A();
assert(a1.check());
auto a2 = scoped!A(1);
assert(a2.check());
a1.a = a1;
assert(a1.check());
}
@system unittest
{
static class A
{
static int sdtor;
this() { ++sdtor; assert(sdtor == 1); }
~this() { assert(sdtor == 1); --sdtor; }
}
interface Bob {}
static class ABob : A, Bob
{
this() { ++sdtor; assert(sdtor == 2); }
~this() { assert(sdtor == 2); --sdtor; }
}
A.sdtor = 0;
scope(exit) assert(A.sdtor == 0);
auto abob = scoped!ABob();
}
@safe unittest
{
static class A { this(int) {} }
static assert(!__traits(compiles, scoped!A()));
}
@system unittest
{
static class A { @property inout(int) foo() inout { return 1; } }
auto a1 = scoped!A();
assert(a1.foo == 1);
static assert(is(typeof(a1.foo) == int));
auto a2 = scoped!(const(A))();
assert(a2.foo == 1);
static assert(is(typeof(a2.foo) == const(int)));
auto a3 = scoped!(immutable(A))();
assert(a3.foo == 1);
static assert(is(typeof(a3.foo) == immutable(int)));
const c1 = scoped!A();
assert(c1.foo == 1);
static assert(is(typeof(c1.foo) == const(int)));
const c2 = scoped!(const(A))();
assert(c2.foo == 1);
static assert(is(typeof(c2.foo) == const(int)));
const c3 = scoped!(immutable(A))();
assert(c3.foo == 1);
static assert(is(typeof(c3.foo) == immutable(int)));
}
@system unittest
{
class C { this(ref int val) { assert(val == 3); ++val; } }
int val = 3;
auto s = scoped!C(val);
assert(val == 4);
}
@system unittest
{
class C
{
this(){}
this(int){}
this(int, int){}
}
alias makeScopedC = scoped!C;
auto a = makeScopedC();
auto b = makeScopedC(1);
auto c = makeScopedC(1, 1);
static assert(is(typeof(a) == typeof(b)));
static assert(is(typeof(b) == typeof(c)));
}
/**
Defines a simple, self-documenting yes/no flag. This makes it easy for
APIs to define functions accepting flags without resorting to $(D
bool), which is opaque in calls, and without needing to define an
enumerated type separately. Using `Flag!"Name"` instead of $(D
bool) makes the flag's meaning visible in calls. Each yes/no flag has
its own type, which makes confusions and mix-ups impossible.
Example:
Code calling `getLine` (usually far away from its definition) can't be
understood without looking at the documentation, even by users familiar with
the API:
----
string getLine(bool keepTerminator)
{
...
if (keepTerminator) ...
...
}
...
auto line = getLine(false);
----
Assuming the reverse meaning (i.e. "ignoreTerminator") and inserting the wrong
code compiles and runs with erroneous results.
After replacing the boolean parameter with an instantiation of `Flag`, code
calling `getLine` can be easily read and understood even by people not
fluent with the API:
----
string getLine(Flag!"keepTerminator" keepTerminator)
{
...
if (keepTerminator) ...
...
}
...
auto line = getLine(Yes.keepTerminator);
----
The structs `Yes` and `No` are provided as shorthand for
`Flag!"Name".yes` and `Flag!"Name".no` and are preferred for brevity and
readability. These convenience structs mean it is usually unnecessary and
counterproductive to create an alias of a `Flag` as a way of avoiding typing
out the full type while specifying the affirmative or negative options.
Passing categorical data by means of unstructured `bool`
parameters is classified under "simple-data coupling" by Steve
McConnell in the $(LUCKY Code Complete) book, along with three other
kinds of coupling. The author argues citing several studies that
coupling has a negative effect on code quality. `Flag` offers a
simple structuring method for passing yes/no flags to APIs.
*/
template Flag(string name) {
///
enum Flag : bool
{
/**
When creating a value of type `Flag!"Name"`, use $(D
Flag!"Name".no) for the negative option. When using a value
of type `Flag!"Name"`, compare it against $(D
Flag!"Name".no) or just `false` or `0`. */
no = false,
/** When creating a value of type `Flag!"Name"`, use $(D
Flag!"Name".yes) for the affirmative option. When using a
value of type `Flag!"Name"`, compare it against $(D
Flag!"Name".yes).
*/
yes = true
}
}
///
@safe unittest
{
Flag!"abc" flag;
assert(flag == Flag!"abc".no);
assert(flag == No.abc);
assert(!flag);
if (flag) assert(0);
}
///
@safe unittest
{
auto flag = Yes.abc;
assert(flag);
assert(flag == Yes.abc);
if (!flag) assert(0);
if (flag) {} else assert(0);
}
/**
Convenience names that allow using e.g. `Yes.encryption` instead of
`Flag!"encryption".yes` and `No.encryption` instead of $(D
Flag!"encryption".no).
*/
struct Yes
{
template opDispatch(string name)
{
enum opDispatch = Flag!name.yes;
}
}
//template yes(string name) { enum Flag!name yes = Flag!name.yes; }
/// Ditto
struct No
{
template opDispatch(string name)
{
enum opDispatch = Flag!name.no;
}
}
///
@safe unittest
{
Flag!"abc" flag;
assert(flag == Flag!"abc".no);
assert(flag == No.abc);
assert(!flag);
if (flag) assert(0);
}
///
@safe unittest
{
auto flag = Yes.abc;
assert(flag);
assert(flag == Yes.abc);
if (!flag) assert(0);
if (flag) {} else assert(0);
}
/**
Detect whether an enum is of integral type and has only "flag" values
(i.e. values with a bit count of exactly 1).
Additionally, a zero value is allowed for compatibility with enums including
a "None" value.
*/
template isBitFlagEnum(E)
{
static if (is(E Base == enum) && isIntegral!Base)
{
enum isBitFlagEnum = (E.min >= 0) &&
{
static foreach (immutable flag; EnumMembers!E)
{{
Base value = flag;
value &= value - 1;
if (value != 0) return false;
}}
return true;
}();
}
else
{
enum isBitFlagEnum = false;
}
}
///
@safe pure nothrow unittest
{
enum A
{
None,
A = 1 << 0,
B = 1 << 1,
C = 1 << 2,
D = 1 << 3,
}
static assert(isBitFlagEnum!A);
}
/// Test an enum with default (consecutive) values
@safe pure nothrow unittest
{
enum B
{
A,
B,
C,
D // D == 3
}
static assert(!isBitFlagEnum!B);
}
/// Test an enum with non-integral values
@safe pure nothrow unittest
{
enum C: double
{
A = 1 << 0,
B = 1 << 1
}
static assert(!isBitFlagEnum!C);
}
/**
A typesafe structure for storing combinations of enum values.
This template defines a simple struct to represent bitwise OR combinations of
enum values. It can be used if all the enum values are integral constants with
a bit count of at most 1, or if the `unsafe` parameter is explicitly set to
Yes.
This is much safer than using the enum itself to store
the OR combination, which can produce surprising effects like this:
----
enum E
{
A = 1 << 0,
B = 1 << 1
}
E e = E.A | E.B;
// will throw SwitchError
final switch (e)
{
case E.A:
return;
case E.B:
return;
}
----
*/
struct BitFlags(E, Flag!"unsafe" unsafe = No.unsafe)
if (unsafe || isBitFlagEnum!(E))
{
@safe @nogc pure nothrow:
private:
enum isBaseEnumType(T) = is(E == T);
alias Base = OriginalType!E;
Base mValue;
static struct Negation
{
@safe @nogc pure nothrow:
private:
Base mValue;
// Prevent non-copy construction outside the module.
@disable this();
this(Base value)
{
mValue = value;
}
}
public:
this(E flag)
{
this = flag;
}
this(T...)(T flags)
if (allSatisfy!(isBaseEnumType, T))
{
this = flags;
}
bool opCast(B: bool)() const
{
return mValue != 0;
}
Base opCast(B)() const
if (isImplicitlyConvertible!(Base, B))
{
return mValue;
}
Negation opUnary(string op)() const
if (op == "~")
{
return Negation(~mValue);
}
auto ref opAssign(T...)(T flags)
if (allSatisfy!(isBaseEnumType, T))
{
mValue = 0;
foreach (E flag; flags)
{
mValue |= flag;
}
return this;
}
auto ref opAssign(E flag)
{
mValue = flag;
return this;
}
auto ref opOpAssign(string op: "|")(BitFlags flags)
{
mValue |= flags.mValue;
return this;
}
auto ref opOpAssign(string op: "&")(BitFlags flags)
{
mValue &= flags.mValue;
return this;
}
auto ref opOpAssign(string op: "|")(E flag)
{
mValue |= flag;
return this;
}
auto ref opOpAssign(string op: "&")(E flag)
{
mValue &= flag;
return this;
}
auto ref opOpAssign(string op: "&")(Negation negatedFlags)
{
mValue &= negatedFlags.mValue;
return this;
}
auto opBinary(string op)(BitFlags flags) const
if (op == "|" || op == "&")
{
BitFlags result = this;
result.opOpAssign!op(flags);
return result;
}
auto opBinary(string op)(E flag) const
if (op == "|" || op == "&")
{
BitFlags result = this;
result.opOpAssign!op(flag);
return result;
}
auto opBinary(string op: "&")(Negation negatedFlags) const
{
BitFlags result = this;
result.opOpAssign!op(negatedFlags);
return result;
}
auto opBinaryRight(string op)(E flag) const
if (op == "|" || op == "&")
{
return opBinary!op(flag);
}
bool opDispatch(string name)() const
if (__traits(hasMember, E, name))
{
enum e = __traits(getMember, E, name);
return (mValue & e) == e;
}
void opDispatch(string name)(bool set)
if (__traits(hasMember, E, name))
{
enum e = __traits(getMember, E, name);
if (set)
mValue |= e;
else
mValue &= ~e;
}
}
/// Set values with the | operator and test with &
@safe @nogc pure nothrow unittest
{
enum Enum
{
A = 1 << 0,
}
// A default constructed BitFlags has no value set
immutable BitFlags!Enum flags_empty;
assert(!flags_empty.A);
// Value can be set with the | operator
immutable flags_A = flags_empty | Enum.A;
// and tested using property access
assert(flags_A.A);
// or the & operator
assert(flags_A & Enum.A);
// which commutes.
assert(Enum.A & flags_A);
}
/// A default constructed BitFlags has no value set
@safe @nogc pure nothrow unittest
{
enum Enum
{
None,
A = 1 << 0,
B = 1 << 1,
C = 1 << 2
}
immutable BitFlags!Enum flags_empty;
assert(!(flags_empty & (Enum.A | Enum.B | Enum.C)));
assert(!(flags_empty & Enum.A) && !(flags_empty & Enum.B) && !(flags_empty & Enum.C));
}
// BitFlags can be variadically initialized
@safe @nogc pure nothrow unittest
{
import std.traits : EnumMembers;
enum Enum
{
A = 1 << 0,
B = 1 << 1,
C = 1 << 2
}
// Values can also be set using property access
BitFlags!Enum flags;
flags.A = true;
assert(flags & Enum.A);
flags.A = false;
assert(!(flags & Enum.A));
// BitFlags can be variadically initialized
immutable BitFlags!Enum flags_AB = BitFlags!Enum(Enum.A, Enum.B);
assert(flags_AB.A && flags_AB.B && !flags_AB.C);
// You can use the EnumMembers template to set all flags
immutable BitFlags!Enum flags_all = EnumMembers!Enum;
assert(flags_all.A && flags_all.B && flags_all.C);
}
/// Binary operations: subtracting and intersecting flags
@safe @nogc pure nothrow unittest
{
enum Enum
{
A = 1 << 0,
B = 1 << 1,
C = 1 << 2,
}
immutable BitFlags!Enum flags_AB = BitFlags!Enum(Enum.A, Enum.B);
immutable BitFlags!Enum flags_BC = BitFlags!Enum(Enum.B, Enum.C);
// Use the ~ operator for subtracting flags
immutable BitFlags!Enum flags_B = flags_AB & ~BitFlags!Enum(Enum.A);
assert(!flags_B.A && flags_B.B && !flags_B.C);
// use & between BitFlags for intersection
assert(flags_B == (flags_BC & flags_AB));
}
/// All the binary operators work in their assignment version
@safe @nogc pure nothrow unittest
{
enum Enum
{
A = 1 << 0,
B = 1 << 1,
}
BitFlags!Enum flags_empty, temp, flags_AB;
flags_AB = Enum.A | Enum.B;
temp |= flags_AB;
assert(temp == (flags_empty | flags_AB));
temp = flags_empty;
temp |= Enum.B;
assert(temp == (flags_empty | Enum.B));
temp = flags_empty;
temp &= flags_AB;
assert(temp == (flags_empty & flags_AB));
temp = flags_empty;
temp &= Enum.A;
assert(temp == (flags_empty & Enum.A));
}
/// Conversion to bool and int
@safe @nogc pure nothrow unittest
{
enum Enum
{
A = 1 << 0,
B = 1 << 1,
}
BitFlags!Enum flags;
// BitFlags with no value set evaluate to false
assert(!flags);
// BitFlags with at least one value set evaluate to true
flags |= Enum.A;
assert(flags);
// This can be useful to check intersection between BitFlags
BitFlags!Enum flags_AB = Enum.A | Enum.B;
assert(flags & flags_AB);
assert(flags & Enum.A);
// You can of course get you raw value out of flags
auto value = cast(int) flags;
assert(value == Enum.A);
}
/// You need to specify the `unsafe` parameter for enums with custom values
@safe @nogc pure nothrow unittest
{
enum UnsafeEnum
{
A = 1,
B = 2,
C = 4,
BC = B|C
}
static assert(!__traits(compiles, { BitFlags!UnsafeEnum flags; }));
BitFlags!(UnsafeEnum, Yes.unsafe) flags;
// property access tests for exact match of unsafe enums
flags.B = true;
assert(!flags.BC); // only B
flags.C = true;
assert(flags.BC); // both B and C
flags.B = false;
assert(!flags.BC); // only C
// property access sets all bits of unsafe enum group
flags = flags.init;
flags.BC = true;
assert(!flags.A && flags.B && flags.C);
flags.A = true;
flags.BC = false;
assert(flags.A && !flags.B && !flags.C);
}
// ReplaceType
/**
Replaces all occurrences of `From` into `To`, in one or more types `T`. For
example, $(D ReplaceType!(int, uint, Tuple!(int, float)[string])) yields
$(D Tuple!(uint, float)[string]). The types in which replacement is performed
may be arbitrarily complex, including qualifiers, built-in type constructors
(pointers, arrays, associative arrays, functions, and delegates), and template
instantiations; replacement proceeds transitively through the type definition.
However, member types in `struct`s or `class`es are not replaced because there
are no ways to express the types resulting after replacement.
This is an advanced type manipulation necessary e.g. for replacing the
placeholder type `This` in $(REF Algebraic, std,variant).
Returns: `ReplaceType` aliases itself to the type(s) that result after
replacement.
*/
template ReplaceType(From, To, T...)
{
static if (T.length == 1)
{
static if (is(T[0] == From))
alias ReplaceType = To;
else static if (is(T[0] == const(U), U))
alias ReplaceType = const(ReplaceType!(From, To, U));
else static if (is(T[0] == immutable(U), U))
alias ReplaceType = immutable(ReplaceType!(From, To, U));
else static if (is(T[0] == shared(U), U))
alias ReplaceType = shared(ReplaceType!(From, To, U));
else static if (is(T[0] == U*, U))
{
static if (is(U == function))
alias ReplaceType = replaceTypeInFunctionType!(From, To, T[0]);
else
alias ReplaceType = ReplaceType!(From, To, U)*;
}
else static if (is(T[0] == delegate))
{
alias ReplaceType = replaceTypeInFunctionType!(From, To, T[0]);
}
else static if (is(T[0] == function))
{
static assert(0, "Function types not supported," ~
" use a function pointer type instead of " ~ T[0].stringof);
}
else static if (is(T[0] : U!V, alias U, V...))
{
template replaceTemplateArgs(T...)
{
static if (is(typeof(T[0]))) // template argument is value or symbol
enum replaceTemplateArgs = T[0];
else
alias replaceTemplateArgs = ReplaceType!(From, To, T[0]);
}
alias ReplaceType = U!(staticMap!(replaceTemplateArgs, V));
}
else static if (is(T[0] == struct))
// don't match with alias this struct below (Issue 15168)
alias ReplaceType = T[0];
else static if (is(T[0] == U[], U))
alias ReplaceType = ReplaceType!(From, To, U)[];
else static if (is(T[0] == U[n], U, size_t n))
alias ReplaceType = ReplaceType!(From, To, U)[n];
else static if (is(T[0] == U[V], U, V))
alias ReplaceType =
ReplaceType!(From, To, U)[ReplaceType!(From, To, V)];
else
alias ReplaceType = T[0];
}
else static if (T.length > 1)
{
alias ReplaceType = AliasSeq!(ReplaceType!(From, To, T[0]),
ReplaceType!(From, To, T[1 .. $]));
}
else
{
alias ReplaceType = AliasSeq!();
}
}
///
@safe unittest
{
static assert(
is(ReplaceType!(int, string, int[]) == string[]) &&
is(ReplaceType!(int, string, int[int]) == string[string]) &&
is(ReplaceType!(int, string, const(int)[]) == const(string)[]) &&
is(ReplaceType!(int, string, Tuple!(int[], float))
== Tuple!(string[], float))
);
}
private template replaceTypeInFunctionType(From, To, fun)
{
alias RX = ReplaceType!(From, To, ReturnType!fun);
alias PX = AliasSeq!(ReplaceType!(From, To, Parameters!fun));
// Wrapping with AliasSeq is neccesary because ReplaceType doesn't return
// tuple if Parameters!fun.length == 1
string gen()
{
enum linkage = functionLinkage!fun;
alias attributes = functionAttributes!fun;
enum variadicStyle = variadicFunctionStyle!fun;
alias storageClasses = ParameterStorageClassTuple!fun;
string result;
result ~= "extern(" ~ linkage ~ ") ";
static if (attributes & FunctionAttribute.ref_)
{
result ~= "ref ";
}
result ~= "RX";
static if (is(fun == delegate))
result ~= " delegate";
else
result ~= " function";
result ~= "(";
static foreach (i; 0 .. PX.length)
{
if (i)
result ~= ", ";
if (storageClasses[i] & ParameterStorageClass.scope_)
result ~= "scope ";
if (storageClasses[i] & ParameterStorageClass.out_)
result ~= "out ";
if (storageClasses[i] & ParameterStorageClass.ref_)
result ~= "ref ";
if (storageClasses[i] & ParameterStorageClass.lazy_)
result ~= "lazy ";
if (storageClasses[i] & ParameterStorageClass.return_)
result ~= "return ";
result ~= "PX[" ~ i.stringof ~ "]";
}
static if (variadicStyle == Variadic.typesafe)
result ~= " ...";
else static if (variadicStyle != Variadic.no)
result ~= ", ...";
result ~= ")";
static if (attributes & FunctionAttribute.pure_)
result ~= " pure";
static if (attributes & FunctionAttribute.nothrow_)
result ~= " nothrow";
static if (attributes & FunctionAttribute.property)
result ~= " @property";
static if (attributes & FunctionAttribute.trusted)
result ~= " @trusted";
static if (attributes & FunctionAttribute.safe)
result ~= " @safe";
static if (attributes & FunctionAttribute.nogc)
result ~= " @nogc";
static if (attributes & FunctionAttribute.system)
result ~= " @system";
static if (attributes & FunctionAttribute.const_)
result ~= " const";
static if (attributes & FunctionAttribute.immutable_)
result ~= " immutable";
static if (attributes & FunctionAttribute.inout_)
result ~= " inout";
static if (attributes & FunctionAttribute.shared_)
result ~= " shared";
static if (attributes & FunctionAttribute.return_)
result ~= " return";
return result;
}
//pragma(msg, "gen ==> ", gen());
mixin("alias replaceTypeInFunctionType = " ~ gen() ~ ";");
}
@safe unittest
{
template Test(Ts...)
{
static if (Ts.length)
{
//pragma(msg, "Testing: ReplaceType!("~Ts[0].stringof~", "
// ~Ts[1].stringof~", "~Ts[2].stringof~")");
static assert(is(ReplaceType!(Ts[0], Ts[1], Ts[2]) == Ts[3]),
"ReplaceType!("~Ts[0].stringof~", "~Ts[1].stringof~", "
~Ts[2].stringof~") == "
~ReplaceType!(Ts[0], Ts[1], Ts[2]).stringof);
alias Test = Test!(Ts[4 .. $]);
}
else alias Test = void;
}
//import core.stdc.stdio;
alias RefFun1 = ref int function(float, long);
alias RefFun2 = ref float function(float, long);
extern(C) int printf(const char*, ...) nothrow @nogc @system;
extern(C) float floatPrintf(const char*, ...) nothrow @nogc @system;
int func(float);
int x;
struct S1 { void foo() { x = 1; } }
struct S2 { void bar() { x = 2; } }
alias Pass = Test!(
int, float, typeof(&func), float delegate(float),
int, float, typeof(&printf), typeof(&floatPrintf),
int, float, int function(out long, ...),
float function(out long, ...),
int, float, int function(ref float, long),
float function(ref float, long),
int, float, int function(ref int, long),
float function(ref float, long),
int, float, int function(out int, long),
float function(out float, long),
int, float, int function(lazy int, long),
float function(lazy float, long),
int, float, int function(out long, ref const int),
float function(out long, ref const float),
int, int, int, int,
int, float, int, float,
int, float, const int, const float,
int, float, immutable int, immutable float,
int, float, shared int, shared float,
int, float, int*, float*,
int, float, const(int)*, const(float)*,
int, float, const(int*), const(float*),
const(int)*, float, const(int*), const(float),
int*, float, const(int)*, const(int)*,
int, float, int[], float[],
int, float, int[42], float[42],
int, float, const(int)[42], const(float)[42],
int, float, const(int[42]), const(float[42]),
int, float, int[int], float[float],
int, float, int[double], float[double],
int, float, double[int], double[float],
int, float, int function(float, long), float function(float, long),
int, float, int function(float), float function(float),
int, float, int function(float, int), float function(float, float),
int, float, int delegate(float, long), float delegate(float, long),
int, float, int delegate(float), float delegate(float),
int, float, int delegate(float, int), float delegate(float, float),
int, float, Unique!int, Unique!float,
int, float, Tuple!(float, int), Tuple!(float, float),
int, float, RefFun1, RefFun2,
S1, S2,
S1[1][][S1]* function(),
S2[1][][S2]* function(),
int, string,
int[3] function( int[] arr, int[2] ...) pure @trusted,
string[3] function(string[] arr, string[2] ...) pure @trusted,
);
// Bugzilla 15168
static struct T1 { string s; alias s this; }
static struct T2 { char[10] s; alias s this; }
static struct T3 { string[string] s; alias s this; }
alias Pass2 = Test!(
ubyte, ubyte, T1, T1,
ubyte, ubyte, T2, T2,
ubyte, ubyte, T3, T3,
);
}
@safe unittest // Bugzilla 17116
{
alias ConstDg = void delegate(float) const;
alias B = void delegate(int) const;
alias A = ReplaceType!(float, int, ConstDg);
static assert(is(B == A));
}
/**
Ternary type with three truth values:
$(UL
$(LI `Ternary.yes` for `true`)
$(LI `Ternary.no` for `false`)
$(LI `Ternary.unknown` as an unknown state)
)
Also known as trinary, trivalent, or trilean.
See_Also:
$(HTTP en.wikipedia.org/wiki/Three-valued_logic,
Three Valued Logic on Wikipedia)
*/
struct Ternary
{
@safe @nogc nothrow pure:
private ubyte value = 6;
private static Ternary make(ubyte b)
{
Ternary r = void;
r.value = b;
return r;
}
/**
The possible states of the `Ternary`
*/
enum no = make(0);
/// ditto
enum yes = make(2);
/// ditto
enum unknown = make(6);
/**
Construct and assign from a `bool`, receiving `no` for `false` and `yes`
for `true`.
*/
this(bool b) { value = b << 1; }
/// ditto
void opAssign(bool b) { value = b << 1; }
/**
Construct a ternary value from another ternary value
*/
this(const Ternary b) { value = b.value; }
/**
$(TABLE Truth table for logical operations,
$(TR $(TH `a`) $(TH `b`) $(TH `$(TILDE)a`) $(TH `a | b`) $(TH `a & b`) $(TH `a ^ b`))
$(TR $(TD `no`) $(TD `no`) $(TD `yes`) $(TD `no`) $(TD `no`) $(TD `no`))
$(TR $(TD `no`) $(TD `yes`) $(TD) $(TD `yes`) $(TD `no`) $(TD `yes`))
$(TR $(TD `no`) $(TD `unknown`) $(TD) $(TD `unknown`) $(TD `no`) $(TD `unknown`))
$(TR $(TD `yes`) $(TD `no`) $(TD `no`) $(TD `yes`) $(TD `no`) $(TD `yes`))
$(TR $(TD `yes`) $(TD `yes`) $(TD) $(TD `yes`) $(TD `yes`) $(TD `no`))
$(TR $(TD `yes`) $(TD `unknown`) $(TD) $(TD `yes`) $(TD `unknown`) $(TD `unknown`))
$(TR $(TD `unknown`) $(TD `no`) $(TD `unknown`) $(TD `unknown`) $(TD `no`) $(TD `unknown`))
$(TR $(TD `unknown`) $(TD `yes`) $(TD) $(TD `yes`) $(TD `unknown`) $(TD `unknown`))
$(TR $(TD `unknown`) $(TD `unknown`) $(TD) $(TD `unknown`) $(TD `unknown`) $(TD `unknown`))
)
*/
Ternary opUnary(string s)() if (s == "~")
{
return make((386 >> value) & 6);
}
/// ditto
Ternary opBinary(string s)(Ternary rhs) if (s == "|")
{
return make((25_512 >> (value + rhs.value)) & 6);
}
/// ditto
Ternary opBinary(string s)(Ternary rhs) if (s == "&")
{
return make((26_144 >> (value + rhs.value)) & 6);
}
/// ditto
Ternary opBinary(string s)(Ternary rhs) if (s == "^")
{
return make((26_504 >> (value + rhs.value)) & 6);
}
/// ditto
Ternary opBinary(string s)(bool rhs)
if (s == "|" || s == "&" || s == "^")
{
return this.opBinary!s(Ternary(rhs));
}
}
///
@safe @nogc nothrow pure
unittest
{
Ternary a;
assert(a == Ternary.unknown);
assert(~Ternary.yes == Ternary.no);
assert(~Ternary.no == Ternary.yes);
assert(~Ternary.unknown == Ternary.unknown);
}
@safe @nogc nothrow pure
unittest
{
alias f = Ternary.no, t = Ternary.yes, u = Ternary.unknown;
Ternary[27] truthTableAnd =
[
t, t, t,
t, u, u,
t, f, f,
u, t, u,
u, u, u,
u, f, f,
f, t, f,
f, u, f,
f, f, f,
];
Ternary[27] truthTableOr =
[
t, t, t,
t, u, t,
t, f, t,
u, t, t,
u, u, u,
u, f, u,
f, t, t,
f, u, u,
f, f, f,
];
Ternary[27] truthTableXor =
[
t, t, f,
t, u, u,
t, f, t,
u, t, u,
u, u, u,
u, f, u,
f, t, t,
f, u, u,
f, f, f,
];
for (auto i = 0; i != truthTableAnd.length; i += 3)
{
assert((truthTableAnd[i] & truthTableAnd[i + 1])
== truthTableAnd[i + 2]);
assert((truthTableOr[i] | truthTableOr[i + 1])
== truthTableOr[i + 2]);
assert((truthTableXor[i] ^ truthTableXor[i + 1])
== truthTableXor[i + 2]);
}
Ternary a;
assert(a == Ternary.unknown);
static assert(!is(typeof({ if (a) {} })));
assert(!is(typeof({ auto b = Ternary(3); })));
a = true;
assert(a == Ternary.yes);
a = false;
assert(a == Ternary.no);
a = Ternary.unknown;
assert(a == Ternary.unknown);
Ternary b;
b = a;
assert(b == a);
assert(~Ternary.yes == Ternary.no);
assert(~Ternary.no == Ternary.yes);
assert(~Ternary.unknown == Ternary.unknown);
}
@safe @nogc nothrow pure
unittest
{
Ternary a = Ternary(true);
assert(a == Ternary.yes);
assert((a & false) == Ternary.no);
assert((a | false) == Ternary.yes);
assert((a ^ true) == Ternary.no);
assert((a ^ false) == Ternary.yes);
}
| D |
import std.stdio, std.algorithm, std.conv, std.array, std.range, std.string, std.math, std.typecons;
void main()
{
auto nk = readln.split.to!(int[]);
auto N = nk[0];
auto K = nk[1];
long cnt;
for (long i; i <= N; ++i) {
if (i < K) continue;
cnt += N - i;
foreach (j; 1..i) if (i % j >= K) ++cnt;
}
writeln(cnt);
} | D |
/**
* Compiler implementation of the
* $(LINK2 http://www.dlang.org, D programming language).
*
* Copyright: Copyright (C) 1999-2020 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 http://www.digitalmars.com, Walter Bright)
* License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/statementsem.d, _statementsem.d)
* Documentation: https://dlang.org/phobos/dmd_statementsem.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/statementsem.d
*/
module dmd.statementsem;
import cidrus;
import dmd.aggregate;
import dmd.aliasthis;
import dmd.arrayop;
import dmd.arraytypes;
import dmd.blockexit;
import dmd.clone;
import dmd.cond;
import dmd.ctorflow;
import dmd.dcast;
import dmd.dclass;
import dmd.declaration;
import dmd.denum;
import dmd.dimport;
import dmd.dinterpret;
import dmd.dmodule;
import dmd.dscope;
import dmd.дсимвол;
import dmd.dsymbolsem;
import dmd.dtemplate;
import dmd.errors;
import dmd.escape;
import drc.ast.Expression;
import dmd.expressionsem;
import dmd.func;
import dmd.globals;
import dmd.gluelayer;
import drc.lexer.Id;
import drc.lexer.Identifier;
import dmd.init;
import dmd.intrange;
import dmd.mtype;
import dmd.nogc;
import dmd.opover;
import util.outbuffer;
import util.string;
import dmd.semantic2;
import dmd.sideeffect;
import dmd.инструкция;
import dmd.target;
import drc.lexer.Tokens;
import dmd.typesem;
import drc.ast.Visitor;
import dmd.cond: StaticForeach;
import dmd.attrib: ForwardingAttribDeclaration;
import cidrus : qsort, _compare_fp_t;
/*****************************************
* CTFE requires FuncDeclaration::labtab for the interpretation.
* So fixing the label имя inside in/out contracts is necessary
* for the uniqueness in labtab.
* Параметры:
* sc = context
* идент = инструкция label имя to be adjusted
* Возвращает:
* adjusted label имя
*/
private Идентификатор2 fixupLabelName(Scope* sc, Идентификатор2 идент)
{
бцел flags = (sc.flags & SCOPE.contract);
const ид = идент.вТкст();
if (flags && flags != SCOPE.invariant_ &&
!(ид.length >= 2 && ид[0] == '_' && ид[1] == '_')) // does not start with "__"
{
БуфВыв буф;
буф.пишиСтр(flags == SCOPE.require ? "__in_" : "__out_");
буф.пишиСтр(идент.вТкст());
идент = Идентификатор2.idPool(буф[]);
}
return идент;
}
/*******************************************
* Check to see if инструкция is the innermost labeled инструкция.
* Параметры:
* sc = context
* инструкция = Инструкция2 to check
* Возвращает:
* if `да`, then the `LabelStatement`, otherwise `null`
*/
private LabelStatement checkLabeledLoop(Scope* sc, Инструкция2 инструкция)
{
if (sc.slabel && sc.slabel.инструкция == инструкция)
{
return sc.slabel;
}
return null;
}
/***********************************************************
* Check an assignment is используется as a условие.
* Intended to be use before the `semantic` call on `e`.
* Параметры:
* e = условие Выражение which is not yet run semantic analysis.
* Возвращает:
* `e` or ErrorExp.
*/
private Выражение checkAssignmentAsCondition(Выражение e)
{
auto ec = lastComma(e);
if (ec.op == ТОК2.assign)
{
ec.выведиОшибку("assignment cannot be используется as a условие, perhaps `==` was meant?");
return new ErrorExp();
}
return e;
}
// Performs semantic analysis in Инструкция2 AST nodes
/*extern(C++)*/ Инструкция2 statementSemantic(Инструкция2 s, Scope* sc)
{
scope v = new StatementSemanticVisitor(sc);
s.прими(v);
return v.результат;
}
private final class StatementSemanticVisitor : Визитор2
{
alias Визитор2.посети посети;
Инструкция2 результат;
Scope* sc;
this(Scope* sc)
{
this.sc = sc;
}
private проц setError()
{
результат = new ErrorStatement();
}
override проц посети(Инструкция2 s)
{
результат = s;
}
override проц посети(ErrorStatement s)
{
результат = s;
}
override проц посети(PeelStatement s)
{
/* "peel" off this wrapper, and don't run semantic()
* on the результат.
*/
результат = s.s;
}
override проц посети(ExpStatement s)
{
/* https://dlang.org/spec/инструкция.html#Выражение-инструкция
*/
if (s.exp)
{
//printf("ExpStatement::semantic() %s\n", exp.вТкст0());
// Allow CommaExp in ExpStatement because return isn't используется
CommaExp.allow(s.exp);
s.exp = s.exp.ВыражениеSemantic(sc);
s.exp = resolveProperties(sc, s.exp);
s.exp = s.exp.addDtorHook(sc);
if (checkNonAssignmentArrayOp(s.exp))
s.exp = new ErrorExp();
if (auto f = isFuncAddress(s.exp))
{
if (f.checkForwardRef(s.exp.место))
s.exp = new ErrorExp();
}
if (discardValue(s.exp))
s.exp = new ErrorExp();
s.exp = s.exp.optimize(WANTvalue);
s.exp = checkGC(sc, s.exp);
if (s.exp.op == ТОК2.error)
return setError();
}
результат = s;
}
override проц посети(CompileStatement cs)
{
/* https://dlang.org/spec/инструкция.html#mixin-инструкция
*/
//printf("CompileStatement::semantic() %s\n", exp.вТкст0());
Инструкции* a = cs.flatten(sc);
if (!a)
return;
Инструкция2 s = new CompoundStatement(cs.место, a);
результат = s.statementSemantic(sc);
}
override проц посети(CompoundStatement cs)
{
//printf("CompoundStatement::semantic(this = %p, sc = %p)\n", cs, sc);
version (none)
{
foreach (i, s; cs.statements)
{
if (s)
printf("[%d]: %s", i, s.вТкст0());
}
}
for (т_мера i = 0; i < cs.statements.dim;)
{
Инструкция2 s = (*cs.statements)[i];
if (s)
{
Инструкции* flt = s.flatten(sc);
if (flt)
{
cs.statements.удали(i);
cs.statements.вставь(i, flt);
continue;
}
s = s.statementSemantic(sc);
(*cs.statements)[i] = s;
if (s)
{
Инструкция2 sentry;
Инструкция2 sexception;
Инструкция2 sfinally;
(*cs.statements)[i] = s.scopeCode(sc, &sentry, &sexception, &sfinally);
if (sentry)
{
sentry = sentry.statementSemantic(sc);
cs.statements.вставь(i, sentry);
i++;
}
if (sexception)
sexception = sexception.statementSemantic(sc);
if (sexception)
{
/* Возвращает: да if statements[] are empty statements
*/
static бул isEmpty( Инструкция2[] statements)
{
foreach (s; statements)
{
if(auto cs = s.isCompoundStatement())
{
if (!isEmpty((*cs.statements)[]))
return нет;
}
else
return нет;
}
return да;
}
if (!sfinally && isEmpty((*cs.statements)[i + 1 .. cs.statements.dim]))
{
}
else
{
/* Rewrite:
* s; s1; s2;
* As:
* s;
* try { s1; s2; }
* catch (Throwable __o)
* { sexception; throw __o; }
*/
auto a = new Инструкции();
a.суньСрез((*cs.statements)[i + 1 .. cs.statements.length]);
cs.statements.устДим(i + 1);
Инструкция2 _body = new CompoundStatement(Место.initial, a);
_body = new ScopeStatement(Место.initial, _body, Место.initial);
Идентификатор2 ид = Идентификатор2.генерируйИд("__o");
Инструкция2 handler = new PeelStatement(sexception);
if (sexception.blockExit(sc.func, нет) & BE.fallthru)
{
auto ts = new ThrowStatement(Место.initial, new IdentifierExp(Место.initial, ид));
ts.internalThrow = да;
handler = new CompoundStatement(Место.initial, handler, ts);
}
auto catches = new Уловители();
auto ctch = new Уловитель(Место.initial, getThrowable(), ид, handler);
ctch.internalCatch = да;
catches.сунь(ctch);
Инструкция2 st = new TryCatchStatement(Место.initial, _body, catches);
if (sfinally)
st = new TryFinallyStatement(Место.initial, st, sfinally);
st = st.statementSemantic(sc);
cs.statements.сунь(st);
break;
}
}
else if (sfinally)
{
if (0 && i + 1 == cs.statements.dim)
{
cs.statements.сунь(sfinally);
}
else
{
/* Rewrite:
* s; s1; s2;
* As:
* s; try { s1; s2; } finally { sfinally; }
*/
auto a = new Инструкции();
a.суньСрез((*cs.statements)[i + 1 .. cs.statements.length]);
cs.statements.устДим(i + 1);
auto _body = new CompoundStatement(Место.initial, a);
Инструкция2 stf = new TryFinallyStatement(Место.initial, _body, sfinally);
stf = stf.statementSemantic(sc);
cs.statements.сунь(stf);
break;
}
}
}
else
{
/* Remove NULL statements from the list.
*/
cs.statements.удали(i);
continue;
}
}
i++;
}
/* Flatten them in place
*/
проц flatten(Инструкции* statements)
{
for (т_мера i = 0; i < statements.length;)
{
Инструкция2 s = (*statements)[i];
if (s)
{
if (auto flt = s.flatten(sc))
{
statements.удали(i);
statements.вставь(i, flt);
continue;
}
}
++i;
}
}
/* https://issues.dlang.org/show_bug.cgi?ид=11653
* 'semantic' may return another CompoundStatement
* (eg. CaseRangeStatement), so flatten it here.
*/
flatten(cs.statements);
foreach (s; *cs.statements)
{
if (!s)
continue;
if (auto se = s.isErrorStatement())
{
результат = se;
return;
}
}
if (cs.statements.length == 1)
{
результат = (*cs.statements)[0];
return;
}
результат = cs;
}
override проц посети(UnrolledLoopStatement uls)
{
//printf("UnrolledLoopStatement::semantic(this = %p, sc = %p)\n", uls, sc);
Scope* scd = sc.сунь();
scd.sbreak = uls;
scd.scontinue = uls;
Инструкция2 serror = null;
foreach (i, ref s; *uls.statements)
{
if (s)
{
//printf("[%d]: %s\n", i, s.вТкст0());
s = s.statementSemantic(scd);
if (s && !serror)
serror = s.isErrorStatement();
}
}
scd.вынь();
результат = serror ? serror : uls;
}
override проц посети(ScopeStatement ss)
{
//printf("ScopeStatement::semantic(sc = %p)\n", sc);
if (ss.инструкция)
{
ScopeDsymbol sym = new ScopeDsymbol();
sym.родитель = sc.scopesym;
sym.endlinnum = ss.endloc.номстр;
sc = sc.сунь(sym);
Инструкции* a = ss.инструкция.flatten(sc);
if (a)
{
ss.инструкция = new CompoundStatement(ss.место, a);
}
ss.инструкция = ss.инструкция.statementSemantic(sc);
if (ss.инструкция)
{
if (ss.инструкция.isErrorStatement())
{
sc.вынь();
результат = ss.инструкция;
return;
}
Инструкция2 sentry;
Инструкция2 sexception;
Инструкция2 sfinally;
ss.инструкция = ss.инструкция.scopeCode(sc, &sentry, &sexception, &sfinally);
assert(!sentry);
assert(!sexception);
if (sfinally)
{
//printf("adding sfinally\n");
sfinally = sfinally.statementSemantic(sc);
ss.инструкция = new CompoundStatement(ss.место, ss.инструкция, sfinally);
}
}
sc.вынь();
}
результат = ss;
}
override проц посети(ForwardingStatement ss)
{
assert(ss.sym);
for (Scope* csc = sc; !ss.sym.forward; csc = csc.enclosing)
{
assert(csc);
ss.sym.forward = csc.scopesym;
}
sc = sc.сунь(ss.sym);
sc.sbreak = ss;
sc.scontinue = ss;
ss.инструкция = ss.инструкция.statementSemantic(sc);
sc = sc.вынь();
результат = ss.инструкция;
}
override проц посети(WhileStatement ws)
{
/* Rewrite as a for(;условие;) loop
* https://dlang.org/spec/инструкция.html#while-инструкция
*/
Инструкция2 s = new ForStatement(ws.место, null, ws.условие, null, ws._body, ws.endloc);
s = s.statementSemantic(sc);
результат = s;
}
override проц посети(DoStatement ds)
{
/* https://dlang.org/spec/инструкция.html#do-инструкция
*/
const inLoopSave = sc.inLoop;
sc.inLoop = да;
if (ds._body)
ds._body = ds._body.semanticScope(sc, ds, ds);
sc.inLoop = inLoopSave;
if (ds.условие.op == ТОК2.dotIdentifier)
(cast(DotIdExp)ds.условие).noderef = да;
// check in syntax уровень
ds.условие = checkAssignmentAsCondition(ds.условие);
ds.условие = ds.условие.ВыражениеSemantic(sc);
ds.условие = resolveProperties(sc, ds.условие);
if (checkNonAssignmentArrayOp(ds.условие))
ds.условие = new ErrorExp();
ds.условие = ds.условие.optimize(WANTvalue);
ds.условие = checkGC(sc, ds.условие);
ds.условие = ds.условие.toBoolean(sc);
if (ds.условие.op == ТОК2.error)
return setError();
if (ds._body && ds._body.isErrorStatement())
{
результат = ds._body;
return;
}
результат = ds;
}
override проц посети(ForStatement fs)
{
/* https://dlang.org/spec/инструкция.html#for-инструкция
*/
//printf("ForStatement::semantic %s\n", fs.вТкст0());
if (fs._иниц)
{
/* Rewrite:
* for (auto v1 = i1, v2 = i2; условие; increment) { ... }
* to:
* { auto v1 = i1, v2 = i2; for (; условие; increment) { ... } }
* then lowered to:
* auto v1 = i1;
* try {
* auto v2 = i2;
* try {
* for (; условие; increment) { ... }
* } finally { v2.~this(); }
* } finally { v1.~this(); }
*/
auto ainit = new Инструкции();
ainit.сунь(fs._иниц);
fs._иниц = null;
ainit.сунь(fs);
Инструкция2 s = new CompoundStatement(fs.место, ainit);
s = new ScopeStatement(fs.место, s, fs.endloc);
s = s.statementSemantic(sc);
if (!s.isErrorStatement())
{
if (LabelStatement ls = checkLabeledLoop(sc, fs))
ls.gotoTarget = fs;
fs.relatedLabeled = s;
}
результат = s;
return;
}
assert(fs._иниц is null);
auto sym = new ScopeDsymbol();
sym.родитель = sc.scopesym;
sym.endlinnum = fs.endloc.номстр;
sc = sc.сунь(sym);
sc.inLoop = да;
if (fs.условие)
{
if (fs.условие.op == ТОК2.dotIdentifier)
(cast(DotIdExp)fs.условие).noderef = да;
// check in syntax уровень
fs.условие = checkAssignmentAsCondition(fs.условие);
fs.условие = fs.условие.ВыражениеSemantic(sc);
fs.условие = resolveProperties(sc, fs.условие);
if (checkNonAssignmentArrayOp(fs.условие))
fs.условие = new ErrorExp();
fs.условие = fs.условие.optimize(WANTvalue);
fs.условие = checkGC(sc, fs.условие);
fs.условие = fs.условие.toBoolean(sc);
}
if (fs.increment)
{
CommaExp.allow(fs.increment);
fs.increment = fs.increment.ВыражениеSemantic(sc);
fs.increment = resolveProperties(sc, fs.increment);
if (checkNonAssignmentArrayOp(fs.increment))
fs.increment = new ErrorExp();
fs.increment = fs.increment.optimize(WANTvalue);
fs.increment = checkGC(sc, fs.increment);
}
sc.sbreak = fs;
sc.scontinue = fs;
if (fs._body)
fs._body = fs._body.semanticNoScope(sc);
sc.вынь();
if (fs.условие && fs.условие.op == ТОК2.error ||
fs.increment && fs.increment.op == ТОК2.error ||
fs._body && fs._body.isErrorStatement())
return setError();
результат = fs;
}
/*******************
* Determines the return тип of makeTupleForeach.
*/
private static template MakeTupleForeachRet(бул isDecl)
{
static if(isDecl)
{
alias Дсимволы* MakeTupleForeachRet;
}
else
{
alias проц MakeTupleForeachRet;
}
}
/*******************
* Тип check and unroll `foreach` over an Выражение кортеж as well
* as `static foreach` statements and `static foreach`
* declarations. For `static foreach` statements and `static
* foreach` declarations, the visitor interface is используется (and the
* результат is written into the `результат` field.) For `static
* foreach` declarations, the результатing Дсимволы* are returned
* directly.
*
* The unrolled body is wrapped into a
* - UnrolledLoopStatement, for `foreach` over an Выражение кортеж.
* - ForwardingStatement, for `static foreach` statements.
* - ForwardingAttribDeclaration, for `static foreach` declarations.
*
* `static foreach` variables are declared as `STC.local`, such
* that they are inserted into the local symbol tables of the
* forwarding constructs instead of forwarded. For `static
* foreach` with multiple foreach loop variables whose aggregate
* has been lowered into a sequence of tuples, this function
* expands the tuples into multiple `STC.local` `static foreach`
* variables.
*/
MakeTupleForeachRet!(isDecl) makeTupleForeach(бул isStatic, бул isDecl)(ForeachStatement fs, TupleForeachArgs!(isStatic, isDecl) args)
{
X returnEarly()
{
static if (isDecl)
{
return null;
}
else
{
результат = new ErrorStatement();
return;
}
}
static if(isDecl)
{
static assert(isStatic);
auto dbody = args[0];
}
static if(isStatic)
{
auto needExpansion = args[$-1];
assert(sc);
}
auto место = fs.место;
т_мера dim = fs.parameters.dim;
static if(isStatic) бул skipCheck = needExpansion;
else const skipCheck = нет;
if (!skipCheck && (dim < 1 || dim > 2))
{
fs.выведиОшибку("only one (значение) or two (ключ,значение) arguments for кортеж `foreach`");
setError();
return returnEarly();
}
Тип paramtype = (*fs.parameters)[dim - 1].тип;
if (paramtype)
{
paramtype = paramtype.typeSemantic(место, sc);
if (paramtype.ty == Terror)
{
setError();
return returnEarly();
}
}
Тип tab = fs.aggr.тип.toBasetype();
КортежТипов кортеж = cast(КортежТипов)tab;
static if(!isDecl)
{
auto statements = new Инструкции();
}
else
{
auto declarations = new Дсимволы();
}
//printf("aggr: op = %d, %s\n", fs.aggr.op, fs.aggr.вТкст0());
т_мера n;
TupleExp te = null;
if (fs.aggr.op == ТОК2.кортеж) // Выражение кортеж
{
te = cast(TupleExp)fs.aggr;
n = te.exps.dim;
}
else if (fs.aggr.op == ТОК2.тип) // тип кортеж
{
n = Параметр2.dim(кортеж.arguments);
}
else
assert(0);
foreach (j; new бцел[0 .. n])
{
т_мера k = (fs.op == ТОК2.foreach_) ? j : n - 1 - j;
Выражение e = null;
Тип t = null;
if (te)
e = (*te.exps)[k];
else
t = Параметр2.getNth(кортеж.arguments, k).тип;
Параметр2 p = (*fs.parameters)[0];
static if(!isDecl)
{
auto st = new Инструкции();
}
else
{
auto st = new Дсимволы();
}
static if(isStatic) бул skip = needExpansion;
else const skip = нет;
if (!skip && dim == 2)
{
// Declare ключ
if (p.классХранения & (STC.out_ | STC.ref_ | STC.lazy_))
{
fs.выведиОшибку("no storage class for ключ `%s`", p.идент.вТкст0());
setError();
return returnEarly();
}
static if(isStatic)
{
if(!p.тип)
{
p.тип = Тип.tт_мера;
}
}
p.тип = p.тип.typeSemantic(место, sc);
TY keyty = p.тип.ty;
if (keyty != Tint32 && keyty != Tuns32)
{
if (глоб2.парамы.isLP64)
{
if (keyty != Tint64 && keyty != Tuns64)
{
fs.выведиОшибку("`foreach`: ключ тип must be `цел` or `бцел`, `long` or `бдол`, not `%s`", p.тип.вТкст0());
setError();
return returnEarly();
}
}
else
{
fs.выведиОшибку("`foreach`: ключ тип must be `цел` or `бцел`, not `%s`", p.тип.вТкст0());
setError();
return returnEarly();
}
}
Инициализатор ie = new ExpInitializer(Место.initial, new IntegerExp(k));
auto var = new VarDeclaration(место, p.тип, p.идент, ie);
var.класс_хранения |= STC.manifest;
static if(isStatic) var.класс_хранения |= STC.local;
static if(!isDecl)
{
st.сунь(new ExpStatement(место, var));
}
else
{
st.сунь(var);
}
p = (*fs.parameters)[1]; // значение
}
/***********************
* Declares a unrolled `foreach` loop variable or a `static foreach` variable.
*
* Параметры:
* классХранения = The storage class of the variable.
* тип = The declared тип of the variable.
* идент = The имя of the variable.
* e = The инициализатор of the variable (i.e. the current element of the looped over aggregate).
* t = The тип of the инициализатор.
* Возвращает:
* `да` iff the declaration was successful.
*/
бул declareVariable(КлассХранения классХранения, Тип тип, Идентификатор2 идент, Выражение e, Тип t)
{
if (классХранения & (STC.out_ | STC.lazy_) ||
классХранения & STC.ref_ && !te)
{
fs.выведиОшибку("no storage class for значение `%s`", идент.вТкст0());
setError();
return нет;
}
Declaration var;
if (e)
{
Тип tb = e.тип.toBasetype();
ДСимвол ds = null;
if (!(классХранения & STC.manifest))
{
if ((isStatic || tb.ty == Tfunction || tb.ty == Tsarray || классХранения&STC.alias_) && e.op == ТОК2.variable)
ds = (cast(VarExp)e).var;
else if (e.op == ТОК2.template_)
ds = (cast(TemplateExp)e).td;
else if (e.op == ТОК2.scope_)
ds = (cast(ScopeExp)e).sds;
else if (e.op == ТОК2.function_)
{
auto fe = cast(FuncExp)e;
ds = fe.td ? cast(ДСимвол)fe.td : fe.fd;
}
else if (e.op == ТОК2.overloadSet)
ds = (cast(OverExp)e).vars;
}
else if (классХранения & STC.alias_)
{
fs.выведиОшибку("`foreach` loop variable cannot be both `enum` and `alias`");
setError();
return нет;
}
if (ds)
{
var = new AliasDeclaration(место, идент, ds);
if (классХранения & STC.ref_)
{
fs.выведиОшибку("symbol `%s` cannot be `ref`", ds.вТкст0());
setError();
return нет;
}
if (paramtype)
{
fs.выведиОшибку("cannot specify element тип for symbol `%s`", ds.вТкст0());
setError();
return нет;
}
}
else if (e.op == ТОК2.тип)
{
var = new AliasDeclaration(место, идент, e.тип);
if (paramtype)
{
fs.выведиОшибку("cannot specify element тип for тип `%s`", e.тип.вТкст0());
setError();
return нет;
}
}
else
{
e = resolveProperties(sc, e);
тип = e.тип;
if (paramtype)
тип = paramtype;
Инициализатор ie = new ExpInitializer(Место.initial, e);
auto v = new VarDeclaration(место, тип, идент, ie);
if (классХранения & STC.ref_)
v.класс_хранения |= STC.ref_ | STC.foreach_;
if (isStatic || классХранения&STC.manifest || e.isConst() ||
e.op == ТОК2.string_ ||
e.op == ТОК2.structLiteral ||
e.op == ТОК2.arrayLiteral)
{
if (v.класс_хранения & STC.ref_)
{
static if (!isStatic)
{
fs.выведиОшибку("constant значение `%s` cannot be `ref`", ie.вТкст0());
}
else
{
if (!needExpansion)
{
fs.выведиОшибку("constant значение `%s` cannot be `ref`", ie.вТкст0());
}
else
{
fs.выведиОшибку("constant значение `%s` cannot be `ref`", идент.вТкст0());
}
}
setError();
return нет;
}
else
v.класс_хранения |= STC.manifest;
}
var = v;
}
}
else
{
var = new AliasDeclaration(место, идент, t);
if (paramtype)
{
fs.выведиОшибку("cannot specify element тип for symbol `%s`", fs.вТкст0());
setError();
return нет;
}
}
static if (isStatic)
{
var.класс_хранения |= STC.local;
}
static if (!isDecl)
{
st.сунь(new ExpStatement(место, var));
}
else
{
st.сунь(var);
}
return да;
}
static if (!isStatic)
{
// Declare значение
if (!declareVariable(p.классХранения, p.тип, p.идент, e, t))
{
return returnEarly();
}
}
else
{
if (!needExpansion)
{
// Declare значение
if (!declareVariable(p.классХранения, p.тип, p.идент, e, t))
{
return returnEarly();
}
}
else
{ // expand tuples into multiple `static foreach` variables.
assert(e && !t);
auto идент = Идентификатор2.генерируйИд("__value");
declareVariable(0, e.тип, идент, e, null);
auto field = Идентификатор2.idPool(StaticForeach.tupleFieldName.ptr,StaticForeach.tupleFieldName.length);
Выражение access = new DotIdExp(место, e, field);
access = ВыражениеSemantic(access, sc);
if (!кортеж) return returnEarly();
//printf("%s\n",кортеж.вТкст0());
foreach (l; new бцел[0 .. dim])
{
auto cp = (*fs.parameters)[l];
Выражение init_ = new IndexExp(место, access, new IntegerExp(место, l, Тип.tт_мера));
init_ = init_.ВыражениеSemantic(sc);
assert(init_.тип);
declareVariable(p.классХранения, init_.тип, cp.идент, init_, null);
}
}
}
static if (!isDecl)
{
if (fs._body) // https://issues.dlang.org/show_bug.cgi?ид=17646
st.сунь(fs._body.syntaxCopy());
Инструкция2 res = new CompoundStatement(место, st);
}
else
{
st.приставь(ДСимвол.arraySyntaxCopy(dbody));
}
static if (!isStatic)
{
res = new ScopeStatement(место, res, fs.endloc);
}
else static if (!isDecl)
{
auto fwd = new ForwardingStatement(место, res);
res = fwd;
}
else
{
auto res = new ForwardingAttribDeclaration(st);
}
static if (!isDecl)
{
statements.сунь(res);
}
else
{
declarations.сунь(res);
}
}
static if (!isStatic)
{
Инструкция2 res = new UnrolledLoopStatement(место, statements);
if (LabelStatement ls = checkLabeledLoop(sc, fs))
ls.gotoTarget = res;
if (te && te.e0)
res = new CompoundStatement(место, new ExpStatement(te.e0.место, te.e0), res);
}
else static if (!isDecl)
{
Инструкция2 res = new CompoundStatement(место, statements);
}
else
{
auto res = declarations;
}
static if (!isDecl)
{
результат = res;
}
else
{
return res;
}
}
override проц посети(ForeachStatement fs)
{
/* https://dlang.org/spec/инструкция.html#foreach-инструкция
*/
//printf("ForeachStatement::semantic() %p\n", fs);
/******
* Issue error if any of the ForeachTypes were not supplied and could not be inferred.
* Возвращает:
* да if error issued
*/
static бул checkForArgTypes(ForeachStatement fs)
{
бул результат = нет;
foreach (p; *fs.parameters)
{
if (!p.тип)
{
fs.выведиОшибку("cannot infer тип for `foreach` variable `%s`, perhaps set it explicitly", p.идент.вТкст0());
p.тип = Тип.terror;
результат = да;
}
}
return результат;
}
const место = fs.место;
const dim = fs.parameters.dim;
TypeAArray taa = null;
Тип tn = null;
Тип tnv = null;
fs.func = sc.func;
if (fs.func.fes)
fs.func = fs.func.fes.func;
VarDeclaration vinit = null;
fs.aggr = fs.aggr.ВыражениеSemantic(sc);
fs.aggr = resolveProperties(sc, fs.aggr);
fs.aggr = fs.aggr.optimize(WANTvalue);
if (fs.aggr.op == ТОК2.error)
return setError();
Выражение oaggr = fs.aggr;
if (fs.aggr.тип && fs.aggr.тип.toBasetype().ty == Tstruct &&
(cast(TypeStruct)(fs.aggr.тип.toBasetype())).sym.dtor &&
fs.aggr.op != ТОК2.тип && !fs.aggr.isLvalue())
{
// https://issues.dlang.org/show_bug.cgi?ид=14653
// Extend the life of rvalue aggregate till the end of foreach.
vinit = copyToTemp(STC.rvalue, "__aggr", fs.aggr);
vinit.endlinnum = fs.endloc.номстр;
vinit.dsymbolSemantic(sc);
fs.aggr = new VarExp(fs.aggr.место, vinit);
}
ДСимвол sapply = null; // the inferred opApply() or front() function
if (!inferForeachAggregate(sc, fs.op == ТОК2.foreach_, fs.aggr, sapply))
{
ткст0 msg = "";
if (fs.aggr.тип && isAggregate(fs.aggr.тип))
{
msg = ", define `opApply()`, range primitives, or use `.tupleof`";
}
fs.выведиОшибку("invalid `foreach` aggregate `%s`%s", oaggr.вТкст0(), msg);
return setError();
}
ДСимвол sapplyOld = sapply; // 'sapply' will be NULL if and after 'inferApplyArgTypes' errors
/* Check for inference errors
*/
if (!inferApplyArgTypes(fs, sc, sapply))
{
/**
Try and extract the параметр count of the opApply callback function, e.g.:
цел opApply(цел delegate(цел, float)) => 2 args
*/
бул foundMismatch = нет;
т_мера foreachParamCount = 0;
if (sapplyOld)
{
if (FuncDeclaration fd = sapplyOld.isFuncDeclaration())
{
auto fparameters = fd.getParameterList();
if (fparameters.length == 1)
{
// first param should be the callback function
Параметр2 fparam = fparameters[0];
if ((fparam.тип.ty == Tpointer ||
fparam.тип.ty == Tdelegate) &&
fparam.тип.nextOf().ty == Tfunction)
{
TypeFunction tf = cast(TypeFunction)fparam.тип.nextOf();
foreachParamCount = tf.parameterList.length;
foundMismatch = да;
}
}
}
}
//printf("dim = %d, parameters.dim = %d\n", dim, parameters.dim);
if (foundMismatch && dim != foreachParamCount)
{
ткст0 plural = foreachParamCount > 1 ? "s" : "";
fs.выведиОшибку("cannot infer argument types, expected %d argument%s, not %d",
foreachParamCount, plural, dim);
}
else
fs.выведиОшибку("cannot uniquely infer `foreach` argument types");
return setError();
}
Тип tab = fs.aggr.тип.toBasetype();
if (tab.ty == Ttuple) // don't generate new scope for кортеж loops
{
makeTupleForeach!(нет,нет)(fs);
if (vinit)
результат = new CompoundStatement(место, new ExpStatement(место, vinit), результат);
результат = результат.statementSemantic(sc);
return;
}
auto sym = new ScopeDsymbol();
sym.родитель = sc.scopesym;
sym.endlinnum = fs.endloc.номстр;
auto sc2 = sc.сунь(sym);
sc2.inLoop = да;
foreach (Параметр2 p; *fs.parameters)
{
if (p.классХранения & STC.manifest)
{
fs.выведиОшибку("cannot declare `enum` loop variables for non-unrolled foreach");
}
if (p.классХранения & STC.alias_)
{
fs.выведиОшибку("cannot declare `alias` loop variables for non-unrolled foreach");
}
}
Инструкция2 s;
switch (tab.ty)
{
case Tarray:
case Tsarray:
{
if (checkForArgTypes(fs))
goto case Terror;
if (dim < 1 || dim > 2)
{
fs.выведиОшибку("only one or two arguments for массив `foreach`");
goto case Terror;
}
// Finish semantic on all foreach параметр types.
foreach (i; new бцел[0 .. dim])
{
Параметр2 p = (*fs.parameters)[i];
p.тип = p.тип.typeSemantic(место, sc2);
p.тип = p.тип.addStorageClass(p.классХранения);
}
tn = tab.nextOf().toBasetype();
if (dim == 2)
{
Тип tindex = (*fs.parameters)[0].тип;
if (!tindex.isintegral())
{
fs.выведиОшибку("foreach: ключ cannot be of non-integral тип `%s`", tindex.вТкст0());
goto case Terror;
}
/* What cases to deprecate implicit conversions for:
* 1. foreach aggregate is a dynamic массив
* 2. foreach body is lowered to _aApply (see special case below).
*/
Тип tv = (*fs.parameters)[1].тип.toBasetype();
if ((tab.ty == Tarray ||
(tn.ty != tv.ty &&
(tn.ty == Tchar || tn.ty == Twchar || tn.ty == Tdchar) &&
(tv.ty == Tchar || tv.ty == Twchar || tv.ty == Tdchar))) &&
!Тип.tт_мера.implicitConvTo(tindex))
{
fs.deprecation("foreach: loop index implicitly converted from `т_мера` to `%s`",
tindex.вТкст0());
}
}
/* Look for special case of parsing сим types out of сим тип
* массив.
*/
if (tn.ty == Tchar || tn.ty == Twchar || tn.ty == Tdchar)
{
цел i = (dim == 1) ? 0 : 1; // index of значение
Параметр2 p = (*fs.parameters)[i];
tnv = p.тип.toBasetype();
if (tnv.ty != tn.ty &&
(tnv.ty == Tchar || tnv.ty == Twchar || tnv.ty == Tdchar))
{
if (p.классХранения & STC.ref_)
{
fs.выведиОшибку("`foreach`: значение of UTF conversion cannot be `ref`");
goto case Terror;
}
if (dim == 2)
{
p = (*fs.parameters)[0];
if (p.классХранения & STC.ref_)
{
fs.выведиОшибку("`foreach`: ключ cannot be `ref`");
goto case Terror;
}
}
goto Lapply;
}
}
foreach (i; new бцел[0 .. dim])
{
// Declare parameters
Параметр2 p = (*fs.parameters)[i];
VarDeclaration var;
if (dim == 2 && i == 0)
{
var = new VarDeclaration(место, p.тип.mutableOf(), Идентификатор2.генерируйИд("__key"), null);
var.класс_хранения |= STC.temp | STC.foreach_;
if (var.класс_хранения & (STC.ref_ | STC.out_))
var.класс_хранения |= STC.nodtor;
fs.ключ = var;
if (p.классХранения & STC.ref_)
{
if (var.тип.constConv(p.тип) <= MATCH.nomatch)
{
fs.выведиОшибку("ключ тип mismatch, `%s` to `ref %s`",
var.тип.вТкст0(), p.тип.вТкст0());
goto case Terror;
}
}
if (tab.ty == Tsarray)
{
TypeSArray ta = cast(TypeSArray)tab;
IntRange dimrange = getIntRange(ta.dim);
if (!IntRange.fromType(var.тип).содержит(dimrange))
{
fs.выведиОшибку("index тип `%s` cannot cover index range 0..%llu",
p.тип.вТкст0(), ta.dim.toInteger());
goto case Terror;
}
fs.ключ.range = new IntRange(SignExtendedNumber(0), dimrange.imax);
}
}
else
{
var = new VarDeclaration(место, p.тип, p.идент, null);
var.класс_хранения |= STC.foreach_;
var.класс_хранения |= p.классХранения & (STC.in_ | STC.out_ | STC.ref_ | STC.TYPECTOR);
if (var.класс_хранения & (STC.ref_ | STC.out_))
var.класс_хранения |= STC.nodtor;
fs.значение = var;
if (var.класс_хранения & STC.ref_)
{
if (fs.aggr.checkModifiable(sc2, 1) == Modifiable.initialization)
var.класс_хранения |= STC.ctorinit;
Тип t = tab.nextOf();
if (t.constConv(p.тип) <= MATCH.nomatch)
{
fs.выведиОшибку("argument тип mismatch, `%s` to `ref %s`",
t.вТкст0(), p.тип.вТкст0());
goto case Terror;
}
}
}
}
/* Convert to a ForStatement
* foreach (ключ, значение; a) body =>
* for (T[] tmp = a[], т_мера ключ; ключ < tmp.length; ++ключ)
* { T значение = tmp[k]; body }
*
* foreach_reverse (ключ, значение; a) body =>
* for (T[] tmp = a[], т_мера ключ = tmp.length; ключ--; )
* { T значение = tmp[k]; body }
*/
auto ид = Идентификатор2.генерируйИд("__r");
auto ie = new ExpInitializer(место, new SliceExp(место, fs.aggr, null, null));
VarDeclaration tmp;
if (fs.aggr.op == ТОК2.arrayLiteral &&
!((*fs.parameters)[dim - 1].классХранения & STC.ref_))
{
auto ale = cast(ArrayLiteralExp)fs.aggr;
т_мера edim = ale.elements ? ale.elements.dim : 0;
auto telem = (*fs.parameters)[dim - 1].тип;
// https://issues.dlang.org/show_bug.cgi?ид=12936
// if telem has been specified explicitly,
// converting массив literal elements to telem might make it .
fs.aggr = fs.aggr.implicitCastTo(sc, telem.sarrayOf(edim));
if (fs.aggr.op == ТОК2.error)
goto case Terror;
// for (T[edim] tmp = a, ...)
tmp = new VarDeclaration(место, fs.aggr.тип, ид, ie);
}
else
tmp = new VarDeclaration(место, tab.nextOf().arrayOf(), ид, ie);
tmp.класс_хранения |= STC.temp;
Выражение tmp_length = new DotIdExp(место, new VarExp(место, tmp), Id.length);
if (!fs.ключ)
{
Идентификатор2 idkey = Идентификатор2.генерируйИд("__key");
fs.ключ = new VarDeclaration(место, Тип.tт_мера, idkey, null);
fs.ключ.класс_хранения |= STC.temp;
}
else if (fs.ключ.тип.ty != Тип.tт_мера.ty)
{
tmp_length = new CastExp(место, tmp_length, fs.ключ.тип);
}
if (fs.op == ТОК2.foreach_reverse_)
fs.ключ._иниц = new ExpInitializer(место, tmp_length);
else
fs.ключ._иниц = new ExpInitializer(место, new IntegerExp(место, 0, fs.ключ.тип));
auto cs = new Инструкции();
if (vinit)
cs.сунь(new ExpStatement(место, vinit));
cs.сунь(new ExpStatement(место, tmp));
cs.сунь(new ExpStatement(место, fs.ключ));
Инструкция2 forinit = new CompoundDeclarationStatement(место, cs);
Выражение cond;
if (fs.op == ТОК2.foreach_reverse_)
{
// ключ--
cond = new PostExp(ТОК2.minusMinus, место, new VarExp(место, fs.ключ));
}
else
{
// ключ < tmp.length
cond = new CmpExp(ТОК2.lessThan, место, new VarExp(место, fs.ключ), tmp_length);
}
Выражение increment = null;
if (fs.op == ТОК2.foreach_)
{
// ключ += 1
increment = new AddAssignExp(место, new VarExp(место, fs.ключ), new IntegerExp(место, 1, fs.ключ.тип));
}
// T значение = tmp[ключ];
IndexExp indexExp = new IndexExp(место, new VarExp(место, tmp), new VarExp(место, fs.ключ));
indexExp.indexIsInBounds = да; // disabling bounds checking in foreach statements.
fs.значение._иниц = new ExpInitializer(место, indexExp);
Инструкция2 ds = new ExpStatement(место, fs.значение);
if (dim == 2)
{
Параметр2 p = (*fs.parameters)[0];
if ((p.классХранения & STC.ref_) && p.тип.равен(fs.ключ.тип))
{
fs.ключ.range = null;
auto v = new AliasDeclaration(место, p.идент, fs.ключ);
fs._body = new CompoundStatement(место, new ExpStatement(место, v), fs._body);
}
else
{
auto ei = new ExpInitializer(место, new IdentifierExp(место, fs.ключ.идент));
auto v = new VarDeclaration(место, p.тип, p.идент, ei);
v.класс_хранения |= STC.foreach_ | (p.классХранения & STC.ref_);
fs._body = new CompoundStatement(место, new ExpStatement(место, v), fs._body);
if (fs.ключ.range && !p.тип.isMutable())
{
/* Limit the range of the ключ to the specified range
*/
v.range = new IntRange(fs.ключ.range.imin, fs.ключ.range.imax - SignExtendedNumber(1));
}
}
}
fs._body = new CompoundStatement(место, ds, fs._body);
s = new ForStatement(место, forinit, cond, increment, fs._body, fs.endloc);
if (auto ls = checkLabeledLoop(sc, fs)) // https://issues.dlang.org/show_bug.cgi?ид=15450
// don't use sc2
ls.gotoTarget = s;
s = s.statementSemantic(sc2);
break;
}
case Taarray:
if (fs.op == ТОК2.foreach_reverse_)
fs.warning("cannot use `foreach_reverse` with an associative массив");
if (checkForArgTypes(fs))
goto case Terror;
taa = cast(TypeAArray)tab;
if (dim < 1 || dim > 2)
{
fs.выведиОшибку("only one or two arguments for associative массив `foreach`");
goto case Terror;
}
goto Lapply;
case Tclass:
case Tstruct:
/* Prefer using opApply, if it exists
*/
if (sapply)
goto Lapply;
{
/* Look for range iteration, i.e. the properties
* .empty, .popFront, .popBack, .front and .back
* foreach (e; aggr) { ... }
* translates to:
* for (auto __r = aggr[]; !__r.empty; __r.popFront()) {
* auto e = __r.front;
* ...
* }
*/
auto ad = (tab.ty == Tclass) ?
cast(AggregateDeclaration)(cast(TypeClass)tab).sym :
cast(AggregateDeclaration)(cast(TypeStruct)tab).sym;
Идентификатор2 idfront;
Идентификатор2 idpopFront;
if (fs.op == ТОК2.foreach_)
{
idfront = Id.Ffront;
idpopFront = Id.FpopFront;
}
else
{
idfront = Id.Fback;
idpopFront = Id.FpopBack;
}
auto sfront = ad.search(Место.initial, idfront);
if (!sfront)
goto Lapply;
/* Generate a temporary __r and initialize it with the aggregate.
*/
VarDeclaration r;
Инструкция2 _иниц;
if (vinit && fs.aggr.op == ТОК2.variable && (cast(VarExp)fs.aggr).var == vinit)
{
r = vinit;
_иниц = new ExpStatement(место, vinit);
}
else
{
r = copyToTemp(0, "__r", fs.aggr);
r.dsymbolSemantic(sc);
_иниц = new ExpStatement(место, r);
if (vinit)
_иниц = new CompoundStatement(место, new ExpStatement(место, vinit), _иниц);
}
// !__r.empty
Выражение e = new VarExp(место, r);
e = new DotIdExp(место, e, Id.Fempty);
Выражение условие = new NotExp(место, e);
// __r.idpopFront()
e = new VarExp(место, r);
Выражение increment = new CallExp(место, new DotIdExp(место, e, idpopFront));
/* Declaration инструкция for e:
* auto e = __r.idfront;
*/
e = new VarExp(место, r);
Выражение einit = new DotIdExp(место, e, idfront);
Инструкция2 makeargs, forbody;
бул ignoreRef = нет; // If a range returns a non-ref front we ignore ref on foreach
Тип tfront;
if (auto fd = sfront.isFuncDeclaration())
{
if (!fd.functionSemantic())
goto Lrangeerr;
tfront = fd.тип;
}
else if (auto td = sfront.isTemplateDeclaration())
{
Выражения a;
if (auto f = resolveFuncCall(место, sc, td, null, tab, &a, FuncResolveFlag.quiet))
tfront = f.тип;
}
else if (auto d = sfront.toAlias().isDeclaration())
{
tfront = d.тип;
}
if (!tfront || tfront.ty == Terror)
goto Lrangeerr;
if (tfront.toBasetype().ty == Tfunction)
{
auto ftt = cast(TypeFunction)tfront.toBasetype();
tfront = tfront.toBasetype().nextOf();
if (!ftt.isref)
{
// .front() does not return a ref. We ignore ref on foreach arg.
// see https://issues.dlang.org/show_bug.cgi?ид=11934
if (tfront.needsDestruction()) ignoreRef = да;
}
}
if (tfront.ty == Tvoid)
{
fs.выведиОшибку("`%s.front` is `проц` and has no значение", oaggr.вТкст0());
goto case Terror;
}
if (dim == 1)
{
auto p = (*fs.parameters)[0];
auto ve = new VarDeclaration(место, p.тип, p.идент, new ExpInitializer(место, einit));
ve.класс_хранения |= STC.foreach_;
ve.класс_хранения |= p.классХранения & (STC.in_ | STC.out_ | STC.ref_ | STC.TYPECTOR);
if (ignoreRef)
ve.класс_хранения &= ~STC.ref_;
makeargs = new ExpStatement(место, ve);
}
else
{
auto vd = copyToTemp(STC.ref_, "__front", einit);
vd.dsymbolSemantic(sc);
makeargs = new ExpStatement(место, vd);
// Resolve inout qualifier of front тип
tfront = tfront.substWildTo(tab.mod);
Выражение ve = new VarExp(место, vd);
ve.тип = tfront;
auto exps = new Выражения();
exps.сунь(ve);
цел pos = 0;
while (exps.dim < dim)
{
pos = expandAliasThisTuples(exps, pos);
if (pos == -1)
break;
}
if (exps.dim != dim)
{
ткст0 plural = exps.dim > 1 ? "s" : "";
fs.выведиОшибку("cannot infer argument types, expected %d argument%s, not %d",
exps.dim, plural, dim);
goto case Terror;
}
foreach (i; new бцел[0 .. dim])
{
auto p = (*fs.parameters)[i];
auto exp = (*exps)[i];
version (none)
{
printf("[%d] p = %s %s, exp = %s %s\n", i,
p.тип ? p.тип.вТкст0() : "?", p.идент.вТкст0(),
exp.тип.вТкст0(), exp.вТкст0());
}
if (!p.тип)
p.тип = exp.тип;
auto sc = p.классХранения;
if (ignoreRef) sc &= ~STC.ref_;
p.тип = p.тип.addStorageClass(sc).typeSemantic(место, sc2);
if (!exp.implicitConvTo(p.тип))
goto Lrangeerr;
auto var = new VarDeclaration(место, p.тип, p.идент, new ExpInitializer(место, exp));
var.класс_хранения |= STC.ctfe | STC.ref_ | STC.foreach_;
makeargs = new CompoundStatement(место, makeargs, new ExpStatement(место, var));
}
}
forbody = new CompoundStatement(место, makeargs, fs._body);
s = new ForStatement(место, _иниц, условие, increment, forbody, fs.endloc);
if (auto ls = checkLabeledLoop(sc, fs))
ls.gotoTarget = s;
version (none)
{
printf("init: %s\n", _иниц.вТкст0());
printf("условие: %s\n", условие.вТкст0());
printf("increment: %s\n", increment.вТкст0());
printf("body: %s\n", forbody.вТкст0());
}
s = s.statementSemantic(sc2);
break;
Lrangeerr:
fs.выведиОшибку("cannot infer argument types");
goto case Terror;
}
case Tdelegate:
if (fs.op == ТОК2.foreach_reverse_)
fs.deprecation("cannot use `foreach_reverse` with a delegate");
Lapply:
{
if (checkForArgTypes(fs))
goto case Terror;
TypeFunction tfld = null;
if (sapply)
{
FuncDeclaration fdapply = sapply.isFuncDeclaration();
if (fdapply)
{
assert(fdapply.тип && fdapply.тип.ty == Tfunction);
tfld = cast(TypeFunction)fdapply.тип.typeSemantic(место, sc2);
goto Lget;
}
else if (tab.ty == Tdelegate)
{
tfld = cast(TypeFunction)tab.nextOf();
Lget:
//printf("tfld = %s\n", tfld.вТкст0());
if (tfld.parameterList.parameters.dim == 1)
{
Параметр2 p = tfld.parameterList[0];
if (p.тип && p.тип.ty == Tdelegate)
{
auto t = p.тип.typeSemantic(место, sc2);
assert(t.ty == Tdelegate);
tfld = cast(TypeFunction)t.nextOf();
}
//printf("tfld = %s\n", tfld.вТкст0());
}
}
}
FuncExp flde = foreachBodyToFunction(sc2, fs, tfld);
if (!flde)
goto case Terror;
// Resolve any forward referenced goto's
foreach (ScopeStatement ss; *fs.gotos)
{
GotoStatement gs = ss.инструкция.isGotoStatement();
if (!gs.label.инструкция)
{
// 'Promote' it to this scope, and replace with a return
fs.cases.сунь(gs);
ss.инструкция = new ReturnStatement(Место.initial, new IntegerExp(fs.cases.dim + 1));
}
}
Выражение e = null;
Выражение ec;
if (vinit)
{
e = new DeclarationExp(место, vinit);
e = e.ВыражениеSemantic(sc2);
if (e.op == ТОК2.error)
goto case Terror;
}
if (taa)
{
// Check types
Параметр2 p = (*fs.parameters)[0];
бул isRef = (p.классХранения & STC.ref_) != 0;
Тип ta = p.тип;
if (dim == 2)
{
Тип ti = (isRef ? taa.index.addMod(MODFlags.const_) : taa.index);
if (isRef ? !ti.constConv(ta) : !ti.implicitConvTo(ta))
{
fs.выведиОшибку("`foreach`: index must be тип `%s`, not `%s`",
ti.вТкст0(), ta.вТкст0());
goto case Terror;
}
p = (*fs.parameters)[1];
isRef = (p.классХранения & STC.ref_) != 0;
ta = p.тип;
}
Тип taav = taa.nextOf();
if (isRef ? !taav.constConv(ta) : !taav.implicitConvTo(ta))
{
fs.выведиОшибку("`foreach`: значение must be тип `%s`, not `%s`",
taav.вТкст0(), ta.вТкст0());
goto case Terror;
}
/* Call:
* extern(C) цел _aaApply(ук, in т_мера, цел delegate(ук))
* _aaApply(aggr, keysize, flde)
*
* extern(C) цел _aaApply2(ук, in т_мера, цел delegate(ук, ук))
* _aaApply2(aggr, keysize, flde)
*/
FuncDeclaration* fdapply = [null, null];
TypeDelegate* fldeTy = [null, null];
ббайт i = (dim == 2 ? 1 : 0);
if (!fdapply[i])
{
auto парамы = new Параметры();
парамы.сунь(new Параметр2(0, Тип.tvoid.pointerTo(), null, null, null));
парамы.сунь(new Параметр2(STC.in_, Тип.tт_мера, null, null, null));
auto dgparams = new Параметры();
dgparams.сунь(new Параметр2(0, Тип.tvoidptr, null, null, null));
if (dim == 2)
dgparams.сунь(new Параметр2(0, Тип.tvoidptr, null, null, null));
fldeTy[i] = new TypeDelegate(new TypeFunction(СписокПараметров(dgparams), Тип.tint32, LINK.d));
парамы.сунь(new Параметр2(0, fldeTy[i], null, null, null));
fdapply[i] = FuncDeclaration.genCfunc(парамы, Тип.tint32, i ? Id._aaApply2 : Id._aaApply);
}
auto exps = new Выражения();
exps.сунь(fs.aggr);
auto keysize = taa.index.size();
if (keysize == SIZE_INVALID)
goto case Terror;
assert(keysize < keysize.max - target.ptrsize);
keysize = (keysize + (target.ptrsize - 1)) & ~(target.ptrsize - 1);
// paint delegate argument to the тип runtime expects
Выражение fexp = flde;
if (!fldeTy[i].равен(flde.тип))
{
fexp = new CastExp(место, flde, flde.тип);
fexp.тип = fldeTy[i];
}
exps.сунь(new IntegerExp(Место.initial, keysize, Тип.tт_мера));
exps.сунь(fexp);
ec = new VarExp(Место.initial, fdapply[i], нет);
ec = new CallExp(место, ec, exps);
ec.тип = Тип.tint32; // don't run semantic() on ec
}
else if (tab.ty == Tarray || tab.ty == Tsarray)
{
/* Call:
* _aApply(aggr, flde)
*/
сим** fntab =
[
"cc", "cw", "cd",
"wc", "cc", "wd",
"dc", "dw", "dd"
];
const т_мера BUFFER_LEN = 7 + 1 + 2 + dim.sizeof * 3 + 1;
сим[BUFFER_LEN] fdname;
цел флаг;
switch (tn.ty)
{
case Tchar: флаг = 0; break;
case Twchar: флаг = 3; break;
case Tdchar: флаг = 6; break;
default:
assert(0);
}
switch (tnv.ty)
{
case Tchar: флаг += 0; break;
case Twchar: флаг += 1; break;
case Tdchar: флаг += 2; break;
default:
assert(0);
}
ткст0 r = (fs.op == ТОК2.foreach_reverse_) ? "R" : "";
цел j = sprintf(fdname.ptr, "_aApply%s%.*s%llu", r, 2, fntab[флаг], cast(бдол)dim);
assert(j < BUFFER_LEN);
FuncDeclaration fdapply;
TypeDelegate dgty;
auto парамы = new Параметры();
парамы.сунь(new Параметр2(STC.in_, tn.arrayOf(), null, null, null));
auto dgparams = new Параметры();
dgparams.сунь(new Параметр2(0, Тип.tvoidptr, null, null, null));
if (dim == 2)
dgparams.сунь(new Параметр2(0, Тип.tvoidptr, null, null, null));
dgty = new TypeDelegate(new TypeFunction(СписокПараметров(dgparams), Тип.tint32, LINK.d));
парамы.сунь(new Параметр2(0, dgty, null, null, null));
fdapply = FuncDeclaration.genCfunc(парамы, Тип.tint32, fdname.ptr);
if (tab.ty == Tsarray)
fs.aggr = fs.aggr.castTo(sc2, tn.arrayOf());
// paint delegate argument to the тип runtime expects
Выражение fexp = flde;
if (!dgty.равен(flde.тип))
{
fexp = new CastExp(место, flde, flde.тип);
fexp.тип = dgty;
}
ec = new VarExp(Место.initial, fdapply, нет);
ec = new CallExp(место, ec, fs.aggr, fexp);
ec.тип = Тип.tint32; // don't run semantic() on ec
}
else if (tab.ty == Tdelegate)
{
/* Call:
* aggr(flde)
*/
if (fs.aggr.op == ТОК2.delegate_ && (cast(DelegateExp)fs.aggr).func.isNested() && !(cast(DelegateExp)fs.aggr).func.needThis())
{
// https://issues.dlang.org/show_bug.cgi?ид=3560
fs.aggr = (cast(DelegateExp)fs.aggr).e1;
}
ec = new CallExp(место, fs.aggr, flde);
ec = ec.ВыражениеSemantic(sc2);
if (ec.op == ТОК2.error)
goto case Terror;
if (ec.тип != Тип.tint32)
{
fs.выведиОшибку("`opApply()` function for `%s` must return an `цел`", tab.вТкст0());
goto case Terror;
}
}
else
{
version (none)
{
if (глоб2.парамы.vsafe)
{
message(место, "To enforce ``, the compiler allocates a closure unless `opApply()` uses `scope`");
}
flde.fd.tookAddressOf = 1;
}
else
{
if (глоб2.парамы.vsafe)
++flde.fd.tookAddressOf; // размести a closure unless the opApply() uses 'scope'
}
assert(tab.ty == Tstruct || tab.ty == Tclass);
assert(sapply);
/* Call:
* aggr.apply(flde)
*/
ec = new DotIdExp(место, fs.aggr, sapply.идент);
ec = new CallExp(место, ec, flde);
ec = ec.ВыражениеSemantic(sc2);
if (ec.op == ТОК2.error)
goto case Terror;
if (ec.тип != Тип.tint32)
{
fs.выведиОшибку("`opApply()` function for `%s` must return an `цел`", tab.вТкст0());
goto case Terror;
}
}
e = Выражение.combine(e, ec);
if (!fs.cases.dim)
{
// Easy case, a clean exit from the loop
e = new CastExp(место, e, Тип.tvoid); // https://issues.dlang.org/show_bug.cgi?ид=13899
s = new ExpStatement(место, e);
}
else
{
// Construct a switch инструкция around the return значение
// of the apply function.
auto a = new Инструкции();
// default: break; takes care of cases 0 and 1
s = new BreakStatement(Место.initial, null);
s = new DefaultStatement(Место.initial, s);
a.сунь(s);
// cases 2...
foreach (i, c; *fs.cases)
{
s = new CaseStatement(Место.initial, new IntegerExp(i + 2), c);
a.сунь(s);
}
s = new CompoundStatement(место, a);
s = new SwitchStatement(место, e, s, нет);
}
s = s.statementSemantic(sc2);
break;
}
assert(0);
case Terror:
s = new ErrorStatement();
break;
default:
fs.выведиОшибку("`foreach`: `%s` is not an aggregate тип", fs.aggr.тип.вТкст0());
goto case Terror;
}
sc2.вынь();
результат = s;
}
/*************************************
* Turn foreach body into the function literal:
* цел delegate(ref T param) { body }
* Параметры:
* sc = context
* fs = ForeachStatement
* tfld = тип of function literal to be created, can be null
* Возвращает:
* Function literal created, as an Выражение
* null if error.
*/
static FuncExp foreachBodyToFunction(Scope* sc, ForeachStatement fs, TypeFunction tfld)
{
auto парамы = new Параметры();
foreach (i; new бцел[0 .. fs.parameters.dim])
{
Параметр2 p = (*fs.parameters)[i];
КлассХранения stc = STC.ref_;
Идентификатор2 ид;
p.тип = p.тип.typeSemantic(fs.место, sc);
p.тип = p.тип.addStorageClass(p.классХранения);
if (tfld)
{
Параметр2 prm = tfld.parameterList[i];
//printf("\tprm = %s%s\n", (prm.классХранения&STC.ref_?"ref ":"").ptr, prm.идент.вТкст0());
stc = prm.классХранения & STC.ref_;
ид = p.идент; // argument копируй is not need.
if ((p.классХранения & STC.ref_) != stc)
{
if (!stc)
{
fs.выведиОшибку("`foreach`: cannot make `%s` `ref`", p.идент.вТкст0());
return null;
}
goto LcopyArg;
}
}
else if (p.классХранения & STC.ref_)
{
// default delegate parameters are marked as ref, then
// argument копируй is not need.
ид = p.идент;
}
else
{
// Make a копируй of the ref argument so it isn't
// a reference.
LcopyArg:
ид = Идентификатор2.генерируйИд("__applyArg", cast(цел)i);
Инициализатор ie = new ExpInitializer(fs.место, new IdentifierExp(fs.место, ид));
auto v = new VarDeclaration(fs.место, p.тип, p.идент, ie);
v.класс_хранения |= STC.temp;
Инструкция2 s = new ExpStatement(fs.место, v);
fs._body = new CompoundStatement(fs.место, s, fs._body);
}
парамы.сунь(new Параметр2(stc, p.тип, ид, null, null));
}
// https://issues.dlang.org/show_bug.cgi?ид=13840
// Throwable nested function inside function is acceptable.
КлассХранения stc = mergeFuncAttrs(STC.safe | STC.pure_ | STC.nogc, fs.func);
auto tf = new TypeFunction(СписокПараметров(парамы), Тип.tint32, LINK.d, stc);
fs.cases = new Инструкции();
fs.gotos = new ScopeStatements();
auto fld = new FuncLiteralDeclaration(fs.место, fs.endloc, tf, ТОК2.delegate_, fs);
fld.fbody = fs._body;
Выражение flde = new FuncExp(fs.место, fld);
flde = flde.ВыражениеSemantic(sc);
fld.tookAddressOf = 0;
if (flde.op == ТОК2.error)
return null;
return cast(FuncExp)flde;
}
override проц посети(ForeachRangeStatement fs)
{
/* https://dlang.org/spec/инструкция.html#foreach-range-инструкция
*/
//printf("ForeachRangeStatement::semantic() %p\n", fs);
auto место = fs.место;
fs.lwr = fs.lwr.ВыражениеSemantic(sc);
fs.lwr = resolveProperties(sc, fs.lwr);
fs.lwr = fs.lwr.optimize(WANTvalue);
if (!fs.lwr.тип)
{
fs.выведиОшибку("invalid range lower bound `%s`", fs.lwr.вТкст0());
return setError();
}
fs.upr = fs.upr.ВыражениеSemantic(sc);
fs.upr = resolveProperties(sc, fs.upr);
fs.upr = fs.upr.optimize(WANTvalue);
if (!fs.upr.тип)
{
fs.выведиОшибку("invalid range upper bound `%s`", fs.upr.вТкст0());
return setError();
}
if (fs.prm.тип)
{
fs.prm.тип = fs.prm.тип.typeSemantic(место, sc);
fs.prm.тип = fs.prm.тип.addStorageClass(fs.prm.классХранения);
fs.lwr = fs.lwr.implicitCastTo(sc, fs.prm.тип);
if (fs.upr.implicitConvTo(fs.prm.тип) || (fs.prm.классХранения & STC.ref_))
{
fs.upr = fs.upr.implicitCastTo(sc, fs.prm.тип);
}
else
{
// See if upr-1 fits in prm.тип
Выражение limit = new MinExp(место, fs.upr, IntegerExp.literal!(1));
limit = limit.ВыражениеSemantic(sc);
limit = limit.optimize(WANTvalue);
if (!limit.implicitConvTo(fs.prm.тип))
{
fs.upr = fs.upr.implicitCastTo(sc, fs.prm.тип);
}
}
}
else
{
/* Must infer types from lwr and upr
*/
Тип tlwr = fs.lwr.тип.toBasetype();
if (tlwr.ty == Tstruct || tlwr.ty == Tclass)
{
/* Just picking the first really isn't good enough.
*/
fs.prm.тип = fs.lwr.тип;
}
else if (fs.lwr.тип == fs.upr.тип)
{
/* Same logic as CondExp ?lwr:upr
*/
fs.prm.тип = fs.lwr.тип;
}
else
{
scope AddExp ea = new AddExp(место, fs.lwr, fs.upr);
if (typeCombine(ea, sc))
return setError();
fs.prm.тип = ea.тип;
fs.lwr = ea.e1;
fs.upr = ea.e2;
}
fs.prm.тип = fs.prm.тип.addStorageClass(fs.prm.классХранения);
}
if (fs.prm.тип.ty == Terror || fs.lwr.op == ТОК2.error || fs.upr.op == ТОК2.error)
{
return setError();
}
/* Convert to a for loop:
* foreach (ключ; lwr .. upr) =>
* for (auto ключ = lwr, auto tmp = upr; ключ < tmp; ++ключ)
*
* foreach_reverse (ключ; lwr .. upr) =>
* for (auto tmp = lwr, auto ключ = upr; ключ-- > tmp;)
*/
auto ie = new ExpInitializer(место, (fs.op == ТОК2.foreach_) ? fs.lwr : fs.upr);
fs.ключ = new VarDeclaration(место, fs.upr.тип.mutableOf(), Идентификатор2.генерируйИд("__key"), ie);
fs.ключ.класс_хранения |= STC.temp;
SignExtendedNumber lower = getIntRange(fs.lwr).imin;
SignExtendedNumber upper = getIntRange(fs.upr).imax;
if (lower <= upper)
{
fs.ключ.range = new IntRange(lower, upper);
}
Идентификатор2 ид = Идентификатор2.генерируйИд("__limit");
ie = new ExpInitializer(место, (fs.op == ТОК2.foreach_) ? fs.upr : fs.lwr);
auto tmp = new VarDeclaration(место, fs.upr.тип, ид, ie);
tmp.класс_хранения |= STC.temp;
auto cs = new Инструкции();
// Keep order of evaluation as lwr, then upr
if (fs.op == ТОК2.foreach_)
{
cs.сунь(new ExpStatement(место, fs.ключ));
cs.сунь(new ExpStatement(место, tmp));
}
else
{
cs.сунь(new ExpStatement(место, tmp));
cs.сунь(new ExpStatement(место, fs.ключ));
}
Инструкция2 forinit = new CompoundDeclarationStatement(место, cs);
Выражение cond;
if (fs.op == ТОК2.foreach_reverse_)
{
cond = new PostExp(ТОК2.minusMinus, место, new VarExp(место, fs.ключ));
if (fs.prm.тип.isscalar())
{
// ключ-- > tmp
cond = new CmpExp(ТОК2.greaterThan, место, cond, new VarExp(место, tmp));
}
else
{
// ключ-- != tmp
cond = new EqualExp(ТОК2.notEqual, место, cond, new VarExp(место, tmp));
}
}
else
{
if (fs.prm.тип.isscalar())
{
// ключ < tmp
cond = new CmpExp(ТОК2.lessThan, место, new VarExp(место, fs.ключ), new VarExp(место, tmp));
}
else
{
// ключ != tmp
cond = new EqualExp(ТОК2.notEqual, место, new VarExp(место, fs.ключ), new VarExp(место, tmp));
}
}
Выражение increment = null;
if (fs.op == ТОК2.foreach_)
{
// ключ += 1
//increment = new AddAssignExp(место, new VarExp(место, fs.ключ), IntegerExp.literal!(1));
increment = new PreExp(ТОК2.prePlusPlus, место, new VarExp(место, fs.ключ));
}
if ((fs.prm.классХранения & STC.ref_) && fs.prm.тип.равен(fs.ключ.тип))
{
fs.ключ.range = null;
auto v = new AliasDeclaration(место, fs.prm.идент, fs.ключ);
fs._body = new CompoundStatement(место, new ExpStatement(место, v), fs._body);
}
else
{
ie = new ExpInitializer(место, new CastExp(место, new VarExp(место, fs.ключ), fs.prm.тип));
auto v = new VarDeclaration(место, fs.prm.тип, fs.prm.идент, ie);
v.класс_хранения |= STC.temp | STC.foreach_ | (fs.prm.классХранения & STC.ref_);
fs._body = new CompoundStatement(место, new ExpStatement(место, v), fs._body);
if (fs.ключ.range && !fs.prm.тип.isMutable())
{
/* Limit the range of the ключ to the specified range
*/
v.range = new IntRange(fs.ключ.range.imin, fs.ключ.range.imax - SignExtendedNumber(1));
}
}
if (fs.prm.классХранения & STC.ref_)
{
if (fs.ключ.тип.constConv(fs.prm.тип) <= MATCH.nomatch)
{
fs.выведиОшибку("argument тип mismatch, `%s` to `ref %s`", fs.ключ.тип.вТкст0(), fs.prm.тип.вТкст0());
return setError();
}
}
auto s = new ForStatement(место, forinit, cond, increment, fs._body, fs.endloc);
if (LabelStatement ls = checkLabeledLoop(sc, fs))
ls.gotoTarget = s;
результат = s.statementSemantic(sc);
}
override проц посети(IfStatement ifs)
{
/* https://dlang.org/spec/инструкция.html#IfStatement
*/
// check in syntax уровень
ifs.условие = checkAssignmentAsCondition(ifs.условие);
auto sym = new ScopeDsymbol();
sym.родитель = sc.scopesym;
sym.endlinnum = ifs.endloc.номстр;
Scope* scd = sc.сунь(sym);
if (ifs.prm)
{
/* Declare prm, which we will set to be the
* результат of условие.
*/
auto ei = new ExpInitializer(ifs.место, ifs.условие);
ifs.match = new VarDeclaration(ifs.место, ifs.prm.тип, ifs.prm.идент, ei);
ifs.match.родитель = scd.func;
ifs.match.класс_хранения |= ifs.prm.классХранения;
ifs.match.dsymbolSemantic(scd);
auto de = new DeclarationExp(ifs.место, ifs.match);
auto ve = new VarExp(ifs.место, ifs.match);
ifs.условие = new CommaExp(ifs.место, de, ve);
ifs.условие = ifs.условие.ВыражениеSemantic(scd);
if (ifs.match.edtor)
{
Инструкция2 sdtor = new DtorExpStatement(ifs.место, ifs.match.edtor, ifs.match);
sdtor = new ScopeGuardStatement(ifs.место, ТОК2.onScopeExit, sdtor);
ifs.ifbody = new CompoundStatement(ifs.место, sdtor, ifs.ifbody);
ifs.match.класс_хранения |= STC.nodtor;
// the destructor is always called
// whether the 'ifbody' is executed or not
Инструкция2 sdtor2 = new DtorExpStatement(ifs.место, ifs.match.edtor, ifs.match);
if (ifs.elsebody)
ifs.elsebody = new CompoundStatement(ifs.место, sdtor2, ifs.elsebody);
else
ifs.elsebody = sdtor2;
}
}
else
{
if (ifs.условие.op == ТОК2.dotIdentifier)
(cast(DotIdExp)ifs.условие).noderef = да;
ifs.условие = ifs.условие.ВыражениеSemantic(scd);
ifs.условие = resolveProperties(scd, ifs.условие);
ifs.условие = ifs.условие.addDtorHook(scd);
}
if (checkNonAssignmentArrayOp(ifs.условие))
ifs.условие = new ErrorExp();
ifs.условие = checkGC(scd, ifs.условие);
// Convert to булean after declaring prm so this works:
// if (S prm = S()) {}
// where S is a struct that defines opCast!бул.
ifs.условие = ifs.условие.toBoolean(scd);
// If we can short-circuit evaluate the if инструкция, don't do the
// semantic analysis of the skipped code.
// This feature allows a limited form of conditional compilation.
ifs.условие = ifs.условие.optimize(WANTvalue);
// Save 'root' of two branches (then and else) at the point where it forks
CtorFlow ctorflow_root = scd.ctorflow.clone();
ifs.ifbody = ifs.ifbody.semanticNoScope(scd);
scd.вынь();
CtorFlow ctorflow_then = sc.ctorflow; // move flow результатs
sc.ctorflow = ctorflow_root; // сбрось flow analysis back to root
if (ifs.elsebody)
ifs.elsebody = ifs.elsebody.semanticScope(sc, null, null);
// Merge 'then' результатs into 'else' результатs
sc.merge(ifs.место, ctorflow_then);
ctorflow_then.freeFieldinit(); // free extra копируй of the данные
if (ifs.условие.op == ТОК2.error ||
(ifs.ifbody && ifs.ifbody.isErrorStatement()) ||
(ifs.elsebody && ifs.elsebody.isErrorStatement()))
{
return setError();
}
результат = ifs;
}
override проц посети(ConditionalStatement cs)
{
//printf("ConditionalStatement::semantic()\n");
// If we can short-circuit evaluate the if инструкция, don't do the
// semantic analysis of the skipped code.
// This feature allows a limited form of conditional compilation.
if (cs.условие.include(sc))
{
DebugCondition dc = cs.условие.isDebugCondition();
if (dc)
{
sc = sc.сунь();
sc.flags |= SCOPE.debug_;
cs.ifbody = cs.ifbody.statementSemantic(sc);
sc.вынь();
}
else
cs.ifbody = cs.ifbody.statementSemantic(sc);
результат = cs.ifbody;
}
else
{
if (cs.elsebody)
cs.elsebody = cs.elsebody.statementSemantic(sc);
результат = cs.elsebody;
}
}
override проц посети(PragmaStatement ps)
{
/* https://dlang.org/spec/инструкция.html#pragma-инструкция
*/
// Should be merged with PragmaDeclaration
//printf("PragmaStatement::semantic() %s\n", ps.вТкст0());
//printf("body = %p\n", ps._body);
if (ps.идент == Id.msg)
{
if (ps.args)
{
foreach (arg; *ps.args)
{
sc = sc.startCTFE();
auto e = arg.ВыражениеSemantic(sc);
e = resolveProperties(sc, e);
sc = sc.endCTFE();
// pragma(msg) is allowed to contain types as well as Выражения
e = ctfeInterpretForPragmaMsg(e);
if (e.op == ТОК2.error)
{
errorSupplemental(ps.место, "while evaluating `pragma(msg, %s)`", arg.вТкст0());
return setError();
}
if (auto se = e.вТкстExp())
{
const slice = se.toUTF8(sc).peekString();
fprintf(stderr, "%.*s", cast(цел)slice.length, slice.ptr);
}
else
fprintf(stderr, "%s", e.вТкст0());
}
fprintf(stderr, "\n");
}
}
else if (ps.идент == Id.lib)
{
version (all)
{
/* Should this be allowed?
*/
ps.выведиОшибку("`pragma(lib)` not allowed as инструкция");
return setError();
}
else
{
if (!ps.args || ps.args.dim != 1)
{
ps.выведиОшибку("`ткст` expected for library имя");
return setError();
}
else
{
auto se = semanticString(sc, (*ps.args)[0], "library имя");
if (!se)
return setError();
if (глоб2.парамы.verbose)
{
message("library %.*s", cast(цел)se.len, se.ткст);
}
}
}
}
else if (ps.идент == Id.linkerDirective)
{
/* Should this be allowed?
*/
ps.выведиОшибку("`pragma(linkerDirective)` not allowed as инструкция");
return setError();
}
else if (ps.идент == Id.startaddress)
{
if (!ps.args || ps.args.dim != 1)
ps.выведиОшибку("function имя expected for start address");
else
{
Выражение e = (*ps.args)[0];
sc = sc.startCTFE();
e = e.ВыражениеSemantic(sc);
e = resolveProperties(sc, e);
sc = sc.endCTFE();
e = e.ctfeInterpret();
(*ps.args)[0] = e;
ДСимвол sa = getDsymbol(e);
if (!sa || !sa.isFuncDeclaration())
{
ps.выведиОшибку("function имя expected for start address, not `%s`", e.вТкст0());
return setError();
}
if (ps._body)
{
ps._body = ps._body.statementSemantic(sc);
if (ps._body.isErrorStatement())
{
результат = ps._body;
return;
}
}
результат = ps;
return;
}
}
else if (ps.идент == Id.Pinline)
{
PINLINE inlining = PINLINE.default_;
if (!ps.args || ps.args.dim == 0)
inlining = PINLINE.default_;
else if (!ps.args || ps.args.dim != 1)
{
ps.выведиОшибку("булean Выражение expected for `pragma(inline)`");
return setError();
}
else
{
Выражение e = (*ps.args)[0];
if (e.op != ТОК2.int64 || !e.тип.равен(Тип.tбул))
{
ps.выведиОшибку("pragma(inline, да or нет) expected, not `%s`", e.вТкст0());
return setError();
}
if (e.isBool(да))
inlining = PINLINE.always;
else if (e.isBool(нет))
inlining = PINLINE.never;
FuncDeclaration fd = sc.func;
if (!fd)
{
ps.выведиОшибку("`pragma(inline)` is not inside a function");
return setError();
}
fd.inlining = inlining;
}
}
else if (!глоб2.парамы.ignoreUnsupportedPragmas)
{
ps.выведиОшибку("unrecognized `pragma(%s)`", ps.идент.вТкст0());
return setError();
}
if (ps._body)
{
if (ps.идент == Id.msg || ps.идент == Id.startaddress)
{
ps.выведиОшибку("`pragma(%s)` is missing a terminating `;`", ps.идент.вТкст0());
return setError();
}
ps._body = ps._body.statementSemantic(sc);
}
результат = ps._body;
}
override проц посети(StaticAssertStatement s)
{
s.sa.semantic2(sc);
}
override проц посети(SwitchStatement ss)
{
/* https://dlang.org/spec/инструкция.html#switch-инструкция
*/
//printf("SwitchStatement::semantic(%p)\n", ss);
ss.tryBody = sc.tryBody;
ss.tf = sc.tf;
if (ss.cases)
{
результат = ss; // already run
return;
}
бул conditionError = нет;
ss.условие = ss.условие.ВыражениеSemantic(sc);
ss.условие = resolveProperties(sc, ss.условие);
Тип att = null;
TypeEnum te = null;
while (ss.условие.op != ТОК2.error)
{
// preserve enum тип for final switches
if (ss.условие.тип.ty == Tenum)
te = cast(TypeEnum)ss.условие.тип;
if (ss.условие.тип.isString())
{
// If it's not an массив, cast it to one
if (ss.условие.тип.ty != Tarray)
{
ss.условие = ss.условие.implicitCastTo(sc, ss.условие.тип.nextOf().arrayOf());
}
ss.условие.тип = ss.условие.тип.constOf();
break;
}
ss.условие = integralPromotions(ss.условие, sc);
if (ss.условие.op != ТОК2.error && ss.условие.тип.isintegral())
break;
auto ad = isAggregate(ss.условие.тип);
if (ad && ad.aliasthis && ss.условие.тип != att)
{
if (!att && ss.условие.тип.checkAliasThisRec())
att = ss.условие.тип;
if (auto e = resolveAliasThis(sc, ss.условие, да))
{
ss.условие = e;
continue;
}
}
if (ss.условие.op != ТОК2.error)
{
ss.выведиОшибку("`%s` must be of integral or ткст тип, it is a `%s`",
ss.условие.вТкст0(), ss.условие.тип.вТкст0());
conditionError = да;
break;
}
}
if (checkNonAssignmentArrayOp(ss.условие))
ss.условие = new ErrorExp();
ss.условие = ss.условие.optimize(WANTvalue);
ss.условие = checkGC(sc, ss.условие);
if (ss.условие.op == ТОК2.error)
conditionError = да;
бул needswitcherror = нет;
ss.lastVar = sc.lastVar;
sc = sc.сунь();
sc.sbreak = ss;
sc.sw = ss;
ss.cases = new CaseStatements();
const inLoopSave = sc.inLoop;
sc.inLoop = да; // BUG: should use Scope::mergeCallSuper() for each case instead
ss._body = ss._body.statementSemantic(sc);
sc.inLoop = inLoopSave;
if (conditionError || (ss._body && ss._body.isErrorStatement()))
{
sc.вынь();
return setError();
}
// Resolve any goto case's with exp
Lgotocase:
foreach (gcs; ss.gotoCases)
{
if (!gcs.exp)
{
gcs.выведиОшибку("no `case` инструкция following `goto case;`");
sc.вынь();
return setError();
}
for (Scope* scx = sc; scx; scx = scx.enclosing)
{
if (!scx.sw)
continue;
foreach (cs; *scx.sw.cases)
{
if (cs.exp.равен(gcs.exp))
{
gcs.cs = cs;
continue Lgotocase;
}
}
}
gcs.выведиОшибку("`case %s` not found", gcs.exp.вТкст0());
sc.вынь();
return setError();
}
if (ss.isFinal)
{
Тип t = ss.условие.тип;
ДСимвол ds;
EnumDeclaration ed = null;
if (t && ((ds = t.toDsymbol(sc)) !is null))
ed = ds.isEnumDeclaration(); // typedef'ed enum
if (!ed && te && ((ds = te.toDsymbol(sc)) !is null))
ed = ds.isEnumDeclaration();
if (ed)
{
Lmembers:
foreach (es; *ed.члены)
{
EnumMember em = es.isEnumMember();
if (em)
{
foreach (cs; *ss.cases)
{
if (cs.exp.равен(em.значение) || (!cs.exp.тип.isString() && !em.значение.тип.isString() && cs.exp.toInteger() == em.значение.toInteger()))
continue Lmembers;
}
ss.выведиОшибку("`enum` member `%s` not represented in `switch`", em.вТкст0());
sc.вынь();
return setError();
}
}
}
else
needswitcherror = да;
}
if (!sc.sw.sdefault && (!ss.isFinal || needswitcherror || глоб2.парамы.useAssert == CHECKENABLE.on))
{
ss.hasNoDefault = 1;
if (!ss.isFinal && (!ss._body || !ss._body.isErrorStatement()))
ss.выведиОшибку("`switch` инструкция without a `default`; use `switch` or add `default: assert(0);` or add `default: break;`");
// Generate runtime error if the default is hit
auto a = new Инструкции();
CompoundStatement cs;
Инструкция2 s;
if (глоб2.парамы.useSwitchError == CHECKENABLE.on &&
глоб2.парамы.checkAction != CHECKACTION.halt)
{
if (глоб2.парамы.checkAction == CHECKACTION.C)
{
/* Rewrite as an assert(0) and let e2ir generate
* the call to the C assert failure function
*/
s = new ExpStatement(ss.место, new AssertExp(ss.место, new IntegerExp(ss.место, 0, Тип.tint32)));
}
else
{
if (!verifyHookExist(ss.место, *sc, Id.__switch_error, "generating assert messages"))
return setError();
Выражение sl = new IdentifierExp(ss.место, Id.empty);
sl = new DotIdExp(ss.место, sl, Id.объект);
sl = new DotIdExp(ss.место, sl, Id.__switch_error);
Выражения* args = new Выражения(2);
(*args)[0] = new StringExp(ss.место, ss.место.имяф.вТкстД());
(*args)[1] = new IntegerExp(ss.место.номстр);
sl = new CallExp(ss.место, sl, args);
sl.ВыражениеSemantic(sc);
s = new SwitchErrorStatement(ss.место, sl);
}
}
else
s = new ExpStatement(ss.место, new HaltExp(ss.место));
a.резервируй(2);
sc.sw.sdefault = new DefaultStatement(ss.место, s);
a.сунь(ss._body);
if (ss._body.blockExit(sc.func, нет) & BE.fallthru)
a.сунь(new BreakStatement(Место.initial, null));
a.сунь(sc.sw.sdefault);
cs = new CompoundStatement(ss.место, a);
ss._body = cs;
}
if (ss.checkLabel())
{
sc.вынь();
return setError();
}
if (ss.условие.тип.isString())
{
// Transform a switch with ткст labels into a switch with integer labels.
// The integer значение of each case corresponds to the index of each label
// ткст in the sorted массив of label strings.
// The значение of the integer условие is obtained by calling the druntime template
// switch(объект.__switch(cond, опции...)) {0: {...}, 1: {...}, ...}
// We sort a копируй of the массив of labels because we want to do a binary search in объект.__switch,
// without modifying the order of the case blocks here in the compiler.
if (!verifyHookExist(ss.место, *sc, Id.__switch, "switch cases on strings"))
return setError();
т_мера numcases = 0;
if (ss.cases)
numcases = ss.cases.dim;
for (т_мера i = 0; i < numcases; i++)
{
CaseStatement cs = (*ss.cases)[i];
cs.index = cast(цел)i;
}
// Make a копируй of all the cases so that qsort doesn't scramble the actual
// данные we pass to codegen (the order of the cases in the switch).
CaseStatements *csCopy = (*ss.cases).копируй();
if (numcases)
{
extern (C) static цел sort_compare(ук x, ук y)
{
CaseStatement ox = *cast(CaseStatement *)x;
CaseStatement oy = *cast(CaseStatement*)y;
auto se1 = ox.exp.isStringExp();
auto se2 = oy.exp.isStringExp();
return (se1 && se2) ? se1.compare(se2) : 0;
}
// Sort cases for efficient lookup
qsort((*csCopy)[].ptr, numcases, CaseStatement.sizeof, cast(_compare_fp_t)&sort_compare);
}
// The actual lowering
auto arguments = new Выражения();
arguments.сунь(ss.условие);
auto compileTimeArgs = new Объекты();
// The тип & label no.
compileTimeArgs.сунь(new TypeExp(ss.место, ss.условие.тип.nextOf()));
// The switch labels
foreach (caseString; *csCopy)
{
compileTimeArgs.сунь(caseString.exp);
}
Выражение sl = new IdentifierExp(ss.место, Id.empty);
sl = new DotIdExp(ss.место, sl, Id.объект);
sl = new DotTemplateInstanceExp(ss.место, sl, Id.__switch, compileTimeArgs);
sl = new CallExp(ss.место, sl, arguments);
sl.ВыражениеSemantic(sc);
ss.условие = sl;
auto i = 0;
foreach (c; *csCopy)
{
(*ss.cases)[c.index].exp = new IntegerExp(i++);
}
//printf("%s\n", ss._body.вТкст0());
ss.statementSemantic(sc);
}
sc.вынь();
результат = ss;
}
override проц посети(CaseStatement cs)
{
SwitchStatement sw = sc.sw;
бул errors = нет;
//printf("CaseStatement::semantic() %s\n", вТкст0());
sc = sc.startCTFE();
cs.exp = cs.exp.ВыражениеSemantic(sc);
cs.exp = resolveProperties(sc, cs.exp);
sc = sc.endCTFE();
if (sw)
{
cs.exp = cs.exp.implicitCastTo(sc, sw.условие.тип);
cs.exp = cs.exp.optimize(WANTvalue | WANTexpand);
Выражение e = cs.exp;
// Remove all the casts the user and/or implicitCastTo may introduce
// otherwise we'd sometimes fail the check below.
while (e.op == ТОК2.cast_)
e = (cast(CastExp)e).e1;
/* This is where variables are allowed as case Выражения.
*/
if (e.op == ТОК2.variable)
{
VarExp ve = cast(VarExp)e;
VarDeclaration v = ve.var.isVarDeclaration();
Тип t = cs.exp.тип.toBasetype();
if (v && (t.isintegral() || t.ty == Tclass))
{
/* Flag that we need to do special code generation
* for this, i.e. generate a sequence of if-then-else
*/
sw.hasVars = 1;
/* TODO check if v can be uninitialized at that point.
*/
if (!v.isConst() && !v.isImmutable())
{
cs.deprecation("`case` variables have to be `const` or `const`");
}
if (sw.isFinal)
{
cs.выведиОшибку("`case` variables not allowed in `switch` statements");
errors = да;
}
/* Find the outermost scope `scx` that set `sw`.
* Then search scope `scx` for a declaration of `v`.
*/
for (Scope* scx = sc; scx; scx = scx.enclosing)
{
if (scx.enclosing && scx.enclosing.sw == sw)
continue;
assert(scx.sw == sw);
if (!scx.search(cs.exp.место, v.идент, null))
{
cs.выведиОшибку("`case` variable `%s` declared at %s cannot be declared in `switch` body",
v.вТкст0(), v.место.вТкст0());
errors = да;
}
break;
}
goto L1;
}
}
else
cs.exp = cs.exp.ctfeInterpret();
if (StringExp se = cs.exp.вТкстExp())
cs.exp = se;
else if (cs.exp.op != ТОК2.int64 && cs.exp.op != ТОК2.error)
{
cs.выведиОшибку("`case` must be a `ткст` or an integral constant, not `%s`", cs.exp.вТкст0());
errors = да;
}
L1:
foreach (cs2; *sw.cases)
{
//printf("comparing '%s' with '%s'\n", exp.вТкст0(), cs.exp.вТкст0());
if (cs2.exp.равен(cs.exp))
{
cs.выведиОшибку("duplicate `case %s` in `switch` инструкция", cs.exp.вТкст0());
errors = да;
break;
}
}
sw.cases.сунь(cs);
// Resolve any goto case's with no exp to this case инструкция
for (т_мера i = 0; i < sw.gotoCases.dim;)
{
GotoCaseStatement gcs = sw.gotoCases[i];
if (!gcs.exp)
{
gcs.cs = cs;
sw.gotoCases.удали(i); // удали from массив
continue;
}
i++;
}
if (sc.sw.tf != sc.tf)
{
cs.выведиОшибку("`switch` and `case` are in different `finally` blocks");
errors = да;
}
if (sc.sw.tryBody != sc.tryBody)
{
cs.выведиОшибку("case cannot be in different `try` block уровень from `switch`");
errors = да;
}
}
else
{
cs.выведиОшибку("`case` not in `switch` инструкция");
errors = да;
}
sc.ctorflow.orCSX(CSX.label);
cs.инструкция = cs.инструкция.statementSemantic(sc);
if (cs.инструкция.isErrorStatement())
{
результат = cs.инструкция;
return;
}
if (errors || cs.exp.op == ТОК2.error)
return setError();
cs.lastVar = sc.lastVar;
результат = cs;
}
override проц посети(CaseRangeStatement crs)
{
SwitchStatement sw = sc.sw;
if (sw is null)
{
crs.выведиОшибку("case range not in `switch` инструкция");
return setError();
}
//printf("CaseRangeStatement::semantic() %s\n", вТкст0());
бул errors = нет;
if (sw.isFinal)
{
crs.выведиОшибку("case ranges not allowed in `switch`");
errors = да;
}
sc = sc.startCTFE();
crs.first = crs.first.ВыражениеSemantic(sc);
crs.first = resolveProperties(sc, crs.first);
sc = sc.endCTFE();
crs.first = crs.first.implicitCastTo(sc, sw.условие.тип);
crs.first = crs.first.ctfeInterpret();
sc = sc.startCTFE();
crs.last = crs.last.ВыражениеSemantic(sc);
crs.last = resolveProperties(sc, crs.last);
sc = sc.endCTFE();
crs.last = crs.last.implicitCastTo(sc, sw.условие.тип);
crs.last = crs.last.ctfeInterpret();
if (crs.first.op == ТОК2.error || crs.last.op == ТОК2.error || errors)
{
if (crs.инструкция)
crs.инструкция.statementSemantic(sc);
return setError();
}
uinteger_t fval = crs.first.toInteger();
uinteger_t lval = crs.last.toInteger();
if ((crs.first.тип.isunsigned() && fval > lval) || (!crs.first.тип.isunsigned() && cast(sinteger_t)fval > cast(sinteger_t)lval))
{
crs.выведиОшибку("first `case %s` is greater than last `case %s`", crs.first.вТкст0(), crs.last.вТкст0());
errors = да;
lval = fval;
}
if (lval - fval > 256)
{
crs.выведиОшибку("had %llu cases which is more than 256 cases in case range", lval - fval);
errors = да;
lval = fval + 256;
}
if (errors)
return setError();
/* This works by replacing the CaseRange with an массив of Case's.
*
* case a: .. case b: s;
* =>
* case a:
* [...]
* case b:
* s;
*/
auto statements = new Инструкции();
for (uinteger_t i = fval; i != lval + 1; i++)
{
Инструкция2 s = crs.инструкция;
if (i != lval) // if not last case
s = new ExpStatement(crs.место, cast(Выражение)null);
Выражение e = new IntegerExp(crs.место, i, crs.first.тип);
Инструкция2 cs = new CaseStatement(crs.место, e, s);
statements.сунь(cs);
}
Инструкция2 s = new CompoundStatement(crs.место, statements);
sc.ctorflow.orCSX(CSX.label);
s = s.statementSemantic(sc);
результат = s;
}
override проц посети(DefaultStatement ds)
{
//printf("DefaultStatement::semantic()\n");
бул errors = нет;
if (sc.sw)
{
if (sc.sw.sdefault)
{
ds.выведиОшибку("`switch` инструкция already has a default");
errors = да;
}
sc.sw.sdefault = ds;
if (sc.sw.tf != sc.tf)
{
ds.выведиОшибку("`switch` and `default` are in different `finally` blocks");
errors = да;
}
if (sc.sw.tryBody != sc.tryBody)
{
ds.выведиОшибку("default cannot be in different `try` block уровень from `switch`");
errors = да;
}
if (sc.sw.isFinal)
{
ds.выведиОшибку("`default` инструкция not allowed in `switch` инструкция");
errors = да;
}
}
else
{
ds.выведиОшибку("`default` not in `switch` инструкция");
errors = да;
}
sc.ctorflow.orCSX(CSX.label);
ds.инструкция = ds.инструкция.statementSemantic(sc);
if (errors || ds.инструкция.isErrorStatement())
return setError();
ds.lastVar = sc.lastVar;
результат = ds;
}
override проц посети(GotoDefaultStatement gds)
{
/* https://dlang.org/spec/инструкция.html#goto-инструкция
*/
gds.sw = sc.sw;
if (!gds.sw)
{
gds.выведиОшибку("`goto default` not in `switch` инструкция");
return setError();
}
if (gds.sw.isFinal)
{
gds.выведиОшибку("`goto default` not allowed in `switch` инструкция");
return setError();
}
результат = gds;
}
override проц посети(GotoCaseStatement gcs)
{
/* https://dlang.org/spec/инструкция.html#goto-инструкция
*/
if (!sc.sw)
{
gcs.выведиОшибку("`goto case` not in `switch` инструкция");
return setError();
}
if (gcs.exp)
{
gcs.exp = gcs.exp.ВыражениеSemantic(sc);
gcs.exp = gcs.exp.implicitCastTo(sc, sc.sw.условие.тип);
gcs.exp = gcs.exp.optimize(WANTvalue);
if (gcs.exp.op == ТОК2.error)
return setError();
}
sc.sw.gotoCases.сунь(gcs);
результат = gcs;
}
override проц посети(ReturnStatement rs)
{
/* https://dlang.org/spec/инструкция.html#return-инструкция
*/
//printf("ReturnStatement.dsymbolSemantic() %p, %s\n", rs, rs.вТкст0());
FuncDeclaration fd = sc.родитель.isFuncDeclaration();
if (fd.fes)
fd = fd.fes.func; // fd is now function enclosing foreach
TypeFunction tf = cast(TypeFunction)fd.тип;
assert(tf.ty == Tfunction);
if (rs.exp && rs.exp.op == ТОК2.variable && (cast(VarExp)rs.exp).var == fd.vрезультат)
{
// return vрезультат;
if (sc.fes)
{
assert(rs.caseDim == 0);
sc.fes.cases.сунь(rs);
результат = new ReturnStatement(Место.initial, new IntegerExp(sc.fes.cases.dim + 1));
return;
}
if (fd.returnLabel)
{
auto gs = new GotoStatement(rs.место, Id.returnLabel);
gs.label = fd.returnLabel;
результат = gs;
return;
}
if (!fd.returns)
fd.returns = new ReturnStatements();
fd.returns.сунь(rs);
результат = rs;
return;
}
Тип tret = tf.следщ;
Тип tbret = tret ? tret.toBasetype() : null;
бул inferRef = (tf.isref && (fd.класс_хранения & STC.auto_));
Выражение e0 = null;
бул errors = нет;
if (sc.flags & SCOPE.contract)
{
rs.выведиОшибку("`return` statements cannot be in contracts");
errors = да;
}
if (sc.ос && sc.ос.tok != ТОК2.onScopeFailure)
{
rs.выведиОшибку("`return` statements cannot be in `%s` bodies", Сема2.вТкст0(sc.ос.tok));
errors = да;
}
if (sc.tf)
{
rs.выведиОшибку("`return` statements cannot be in `finally` bodies");
errors = да;
}
if (fd.isCtorDeclaration())
{
if (rs.exp)
{
rs.выведиОшибку("cannot return Выражение from constructor");
errors = да;
}
// Constructors implicitly do:
// return this;
rs.exp = new ThisExp(Место.initial);
rs.exp.тип = tret;
}
else if (rs.exp)
{
fd.hasReturnExp |= (fd.hasReturnExp & 1 ? 16 : 1);
FuncLiteralDeclaration fld = fd.isFuncLiteralDeclaration();
if (tret)
rs.exp = inferType(rs.exp, tret);
else if (fld && fld.treq)
rs.exp = inferType(rs.exp, fld.treq.nextOf().nextOf());
rs.exp = rs.exp.ВыражениеSemantic(sc);
rs.exp.checkSharedAccess(sc);
// for static alias this: https://issues.dlang.org/show_bug.cgi?ид=17684
if (rs.exp.op == ТОК2.тип)
rs.exp = resolveAliasThis(sc, rs.exp);
rs.exp = resolveProperties(sc, rs.exp);
if (rs.exp.checkType())
rs.exp = new ErrorExp();
if (auto f = isFuncAddress(rs.exp))
{
if (fd.inferRetType && f.checkForwardRef(rs.exp.место))
rs.exp = new ErrorExp();
}
if (checkNonAssignmentArrayOp(rs.exp))
rs.exp = new ErrorExp();
// Extract side-effect part
rs.exp = Выражение.extractLast(rs.exp, e0);
if (rs.exp.op == ТОК2.call)
rs.exp = valueNoDtor(rs.exp);
if (e0)
e0 = e0.optimize(WANTvalue);
/* Void-return function can have проц typed Выражение
* on return инструкция.
*/
if (tbret && tbret.ty == Tvoid || rs.exp.тип.ty == Tvoid)
{
if (rs.exp.тип.ty != Tvoid)
{
rs.выведиОшибку("cannot return non-проц from `проц` function");
errors = да;
rs.exp = new CastExp(rs.место, rs.exp, Тип.tvoid);
rs.exp = rs.exp.ВыражениеSemantic(sc);
}
/* Replace:
* return exp;
* with:
* exp; return;
*/
e0 = Выражение.combine(e0, rs.exp);
rs.exp = null;
}
if (e0)
e0 = checkGC(sc, e0);
}
if (rs.exp)
{
if (fd.inferRetType) // infer return тип
{
if (!tret)
{
tf.следщ = rs.exp.тип;
}
else if (tret.ty != Terror && !rs.exp.тип.равен(tret))
{
цел m1 = rs.exp.тип.implicitConvTo(tret);
цел m2 = tret.implicitConvTo(rs.exp.тип);
//printf("exp.тип = %s m2<-->m1 tret %s\n", exp.тип.вТкст0(), tret.вТкст0());
//printf("m1 = %d, m2 = %d\n", m1, m2);
if (m1 && m2)
{
}
else if (!m1 && m2)
tf.следщ = rs.exp.тип;
else if (m1 && !m2)
{
}
else if (rs.exp.op != ТОК2.error)
{
rs.выведиОшибку("Expected return тип of `%s`, not `%s`:",
tret.вТкст0(),
rs.exp.тип.вТкст0());
errorSupplemental((fd.returns) ? (*fd.returns)[0].место : fd.место,
"Return тип of `%s` inferred here.",
tret.вТкст0());
errors = да;
tf.следщ = Тип.terror;
}
}
tret = tf.следщ;
tbret = tret.toBasetype();
}
if (inferRef) // deduce 'auto ref'
{
/* Determine "refness" of function return:
* if it's an lvalue, return by ref, else return by значение
* https://dlang.org/spec/function.html#auto-ref-functions
*/
проц turnOffRef()
{
tf.isref = нет; // return by значение
tf.isreturn = нет; // ignore 'return' attribute, whether explicit or inferred
fd.класс_хранения &= ~STC.return_;
}
if (rs.exp.isLvalue())
{
/* May return by ref
*/
if (checkReturnEscapeRef(sc, rs.exp, да))
turnOffRef();
else if (!rs.exp.тип.constConv(tf.следщ))
turnOffRef();
}
else
turnOffRef();
/* The "refness" is determined by all of return statements.
* This means:
* return 3; return x; // ok, x can be a значение
* return x; return 3; // ok, x can be a значение
*/
}
}
else
{
// infer return тип
if (fd.inferRetType)
{
if (tf.следщ && tf.следщ.ty != Tvoid)
{
if (tf.следщ.ty != Terror)
{
rs.выведиОшибку("mismatched function return тип inference of `проц` and `%s`", tf.следщ.вТкст0());
}
errors = да;
tf.следщ = Тип.terror;
}
else
tf.следщ = Тип.tvoid;
tret = tf.следщ;
tbret = tret.toBasetype();
}
if (inferRef) // deduce 'auto ref'
tf.isref = нет;
if (tbret.ty != Tvoid) // if non-проц return
{
if (tbret.ty != Terror)
rs.выведиОшибку("`return` Выражение expected");
errors = да;
}
else if (fd.isMain())
{
// main() returns 0, even if it returns проц
rs.exp = IntegerExp.literal!(0);
}
}
// If any branches have called a ctor, but this branch hasn't, it's an error
if (sc.ctorflow.callSuper & CSX.any_ctor && !(sc.ctorflow.callSuper & (CSX.this_ctor | CSX.super_ctor)))
{
rs.выведиОшибку("`return` without calling constructor");
errors = да;
}
if (sc.ctorflow.fieldinit.length) // if aggregate fields are being constructed
{
auto ad = fd.isMemberLocal();
assert(ad);
foreach (i, v; ad.fields)
{
бул mustInit = (v.класс_хранения & STC.nodefaultctor || v.тип.needsNested());
if (mustInit && !(sc.ctorflow.fieldinit[i].csx & CSX.this_ctor))
{
rs.выведиОшибку("an earlier `return` инструкция skips field `%s` initialization", v.вТкст0());
errors = да;
}
}
}
sc.ctorflow.orCSX(CSX.return_);
if (errors)
return setError();
if (sc.fes)
{
if (!rs.exp)
{
// Send out "case receiver" инструкция to the foreach.
// return exp;
Инструкция2 s = new ReturnStatement(Место.initial, rs.exp);
sc.fes.cases.сунь(s);
// Immediately rewrite "this" return инструкция as:
// return cases.dim+1;
rs.exp = new IntegerExp(sc.fes.cases.dim + 1);
if (e0)
{
результат = new CompoundStatement(rs.место, new ExpStatement(rs.место, e0), rs);
return;
}
результат = rs;
return;
}
else
{
fd.buildрезультатVar(null, rs.exp.тип);
бул r = fd.vрезультат.checkNestedReference(sc, Место.initial);
assert(!r); // vрезультат should be always accessible
// Send out "case receiver" инструкция to the foreach.
// return vрезультат;
Инструкция2 s = new ReturnStatement(Место.initial, new VarExp(Место.initial, fd.vрезультат));
sc.fes.cases.сунь(s);
// Save receiver index for the later rewriting from:
// return exp;
// to:
// vрезультат = exp; retrun caseDim;
rs.caseDim = sc.fes.cases.dim + 1;
}
}
if (rs.exp)
{
if (!fd.returns)
fd.returns = new ReturnStatements();
fd.returns.сунь(rs);
}
if (e0)
{
if (e0.op == ТОК2.declaration || e0.op == ТОК2.comma)
{
rs.exp = Выражение.combine(e0, rs.exp);
}
else
{
результат = new CompoundStatement(rs.место, new ExpStatement(rs.место, e0), rs);
return;
}
}
результат = rs;
}
override проц посети(BreakStatement bs)
{
/* https://dlang.org/spec/инструкция.html#break-инструкция
*/
//printf("BreakStatement::semantic()\n");
// If:
// break Идентификатор2;
if (bs.идент)
{
bs.идент = fixupLabelName(sc, bs.идент);
FuncDeclaration thisfunc = sc.func;
for (Scope* scx = sc; scx; scx = scx.enclosing)
{
if (scx.func != thisfunc) // if in enclosing function
{
if (sc.fes) // if this is the body of a foreach
{
/* Post this инструкция to the fes, and replace
* it with a return значение that caller will put into
* a switch. Caller will figure out where the break
* label actually is.
* Case numbers start with 2, not 0, as 0 is continue
* and 1 is break.
*/
sc.fes.cases.сунь(bs);
результат = new ReturnStatement(Место.initial, new IntegerExp(sc.fes.cases.dim + 1));
return;
}
break; // can't break to it
}
LabelStatement ls = scx.slabel;
if (ls && ls.идент == bs.идент)
{
Инструкция2 s = ls.инструкция;
if (!s || !s.hasBreak())
bs.выведиОшибку("label `%s` has no `break`", bs.идент.вТкст0());
else if (ls.tf != sc.tf)
bs.выведиОшибку("cannot break out of `finally` block");
else
{
ls.breaks = да;
результат = bs;
return;
}
return setError();
}
}
bs.выведиОшибку("enclosing label `%s` for `break` not found", bs.идент.вТкст0());
return setError();
}
else if (!sc.sbreak)
{
if (sc.ос && sc.ос.tok != ТОК2.onScopeFailure)
{
bs.выведиОшибку("`break` is not inside `%s` bodies", Сема2.вТкст0(sc.ос.tok));
}
else if (sc.fes)
{
// Replace break; with return 1;
результат = new ReturnStatement(Место.initial, IntegerExp.literal!(1));
return;
}
else
bs.выведиОшибку("`break` is not inside a loop or `switch`");
return setError();
}
else if (sc.sbreak.isForwardingStatement())
{
bs.выведиОшибку("must use labeled `break` within `static foreach`");
}
результат = bs;
}
override проц посети(ContinueStatement cs)
{
/* https://dlang.org/spec/инструкция.html#continue-инструкция
*/
//printf("ContinueStatement::semantic() %p\n", cs);
if (cs.идент)
{
cs.идент = fixupLabelName(sc, cs.идент);
Scope* scx;
FuncDeclaration thisfunc = sc.func;
for (scx = sc; scx; scx = scx.enclosing)
{
LabelStatement ls;
if (scx.func != thisfunc) // if in enclosing function
{
if (sc.fes) // if this is the body of a foreach
{
for (; scx; scx = scx.enclosing)
{
ls = scx.slabel;
if (ls && ls.идент == cs.идент && ls.инструкция == sc.fes)
{
// Replace continue идент; with return 0;
результат = new ReturnStatement(Место.initial, IntegerExp.literal!(0));
return;
}
}
/* Post this инструкция to the fes, and replace
* it with a return значение that caller will put into
* a switch. Caller will figure out where the break
* label actually is.
* Case numbers start with 2, not 0, as 0 is continue
* and 1 is break.
*/
sc.fes.cases.сунь(cs);
результат = new ReturnStatement(Место.initial, new IntegerExp(sc.fes.cases.dim + 1));
return;
}
break; // can't continue to it
}
ls = scx.slabel;
if (ls && ls.идент == cs.идент)
{
Инструкция2 s = ls.инструкция;
if (!s || !s.hasContinue())
cs.выведиОшибку("label `%s` has no `continue`", cs.идент.вТкст0());
else if (ls.tf != sc.tf)
cs.выведиОшибку("cannot continue out of `finally` block");
else
{
результат = cs;
return;
}
return setError();
}
}
cs.выведиОшибку("enclosing label `%s` for `continue` not found", cs.идент.вТкст0());
return setError();
}
else if (!sc.scontinue)
{
if (sc.ос && sc.ос.tok != ТОК2.onScopeFailure)
{
cs.выведиОшибку("`continue` is not inside `%s` bodies", Сема2.вТкст0(sc.ос.tok));
}
else if (sc.fes)
{
// Replace continue; with return 0;
результат = new ReturnStatement(Место.initial, IntegerExp.literal!(0));
return;
}
else
cs.выведиОшибку("`continue` is not inside a loop");
return setError();
}
else if (sc.scontinue.isForwardingStatement())
{
cs.выведиОшибку("must use labeled `continue` within `static foreach`");
}
результат = cs;
}
override проц посети(SynchronizedStatement ss)
{
/* https://dlang.org/spec/инструкция.html#synchronized-инструкция
*/
if (ss.exp)
{
ss.exp = ss.exp.ВыражениеSemantic(sc);
ss.exp = resolveProperties(sc, ss.exp);
ss.exp = ss.exp.optimize(WANTvalue);
ss.exp = checkGC(sc, ss.exp);
if (ss.exp.op == ТОК2.error)
{
if (ss._body)
ss._body = ss._body.statementSemantic(sc);
return setError();
}
ClassDeclaration cd = ss.exp.тип.isClassHandle();
if (!cd)
{
ss.выведиОшибку("can only `synchronize` on class objects, not `%s`", ss.exp.тип.вТкст0());
return setError();
}
else if (cd.isInterfaceDeclaration())
{
/* Cast the interface to an объект, as the объект has the monitor,
* not the interface.
*/
if (!ClassDeclaration.объект)
{
ss.выведиОшибку("missing or corrupt объект.d");
fatal();
}
Тип t = ClassDeclaration.объект.тип;
t = t.typeSemantic(Место.initial, sc).toBasetype();
assert(t.ty == Tclass);
ss.exp = new CastExp(ss.место, ss.exp, t);
ss.exp = ss.exp.ВыражениеSemantic(sc);
}
version (all)
{
/* Rewrite as:
* auto tmp = exp;
* _d_monitorenter(tmp);
* try { body } finally { _d_monitorexit(tmp); }
*/
auto tmp = copyToTemp(0, "__sync", ss.exp);
tmp.dsymbolSemantic(sc);
auto cs = new Инструкции();
cs.сунь(new ExpStatement(ss.место, tmp));
auto args = new Параметры();
args.сунь(new Параметр2(0, ClassDeclaration.объект.тип, null, null, null));
FuncDeclaration fdenter = FuncDeclaration.genCfunc(args, Тип.tvoid, Id.monitorenter);
Выражение e = new CallExp(ss.место, fdenter, new VarExp(ss.место, tmp));
e.тип = Тип.tvoid; // do not run semantic on e
cs.сунь(new ExpStatement(ss.место, e));
FuncDeclaration fdexit = FuncDeclaration.genCfunc(args, Тип.tvoid, Id.monitorexit);
e = new CallExp(ss.место, fdexit, new VarExp(ss.место, tmp));
e.тип = Тип.tvoid; // do not run semantic on e
Инструкция2 s = new ExpStatement(ss.место, e);
s = new TryFinallyStatement(ss.место, ss._body, s);
cs.сунь(s);
s = new CompoundStatement(ss.место, cs);
результат = s.statementSemantic(sc);
}
}
else
{
/* Generate our own critical section, then rewrite as:
* static shared align(D_CRITICAL_SECTION.alignof) byte[D_CRITICAL_SECTION.sizeof] __critsec;
* _d_criticalenter(&__critsec[0]);
* try { body } finally { _d_criticalexit(&__critsec[0]); }
*/
auto ид = Идентификатор2.генерируйИд("__critsec");
auto t = Тип.tint8.sarrayOf(target.ptrsize + target.critsecsize());
auto tmp = new VarDeclaration(ss.место, t, ид, null);
tmp.класс_хранения |= STC.temp | STC.shared_ | STC.static_;
Выражение tmpExp = new VarExp(ss.место, tmp);
auto cs = new Инструкции();
cs.сунь(new ExpStatement(ss.место, tmp));
/* This is just a dummy variable for "goto skips declaration" error.
* Backend optimizer could удали this unused variable.
*/
auto v = new VarDeclaration(ss.место, Тип.tvoidptr, Идентификатор2.генерируйИд("__sync"), null);
v.dsymbolSemantic(sc);
cs.сунь(new ExpStatement(ss.место, v));
auto args = new Параметры();
args.сунь(new Параметр2(0, t.pointerTo(), null, null, null));
FuncDeclaration fdenter = FuncDeclaration.genCfunc(args, Тип.tvoid, Id.criticalenter, STC.nothrow_);
Выражение int0 = new IntegerExp(ss.место, dinteger_t(0), Тип.tint8);
Выражение e = new AddrExp(ss.место, new IndexExp(ss.место, tmpExp, int0));
e = e.ВыражениеSemantic(sc);
e = new CallExp(ss.место, fdenter, e);
e.тип = Тип.tvoid; // do not run semantic on e
cs.сунь(new ExpStatement(ss.место, e));
FuncDeclaration fdexit = FuncDeclaration.genCfunc(args, Тип.tvoid, Id.criticalexit, STC.nothrow_);
e = new AddrExp(ss.место, new IndexExp(ss.место, tmpExp, int0));
e = e.ВыражениеSemantic(sc);
e = new CallExp(ss.место, fdexit, e);
e.тип = Тип.tvoid; // do not run semantic on e
Инструкция2 s = new ExpStatement(ss.место, e);
s = new TryFinallyStatement(ss.место, ss._body, s);
cs.сунь(s);
s = new CompoundStatement(ss.место, cs);
результат = s.statementSemantic(sc);
// set the explicit __critsec alignment after semantic()
tmp.alignment = target.ptrsize;
}
}
override проц посети(WithStatement ws)
{
/* https://dlang.org/spec/инструкция.html#with-инструкция
*/
ScopeDsymbol sym;
Инициализатор _иниц;
//printf("WithStatement::semantic()\n");
ws.exp = ws.exp.ВыражениеSemantic(sc);
ws.exp = resolveProperties(sc, ws.exp);
ws.exp = ws.exp.optimize(WANTvalue);
ws.exp = checkGC(sc, ws.exp);
if (ws.exp.op == ТОК2.error)
return setError();
if (ws.exp.op == ТОК2.scope_)
{
sym = new WithScopeSymbol(ws);
sym.родитель = sc.scopesym;
sym.endlinnum = ws.endloc.номстр;
}
else if (ws.exp.op == ТОК2.тип)
{
ДСимвол s = (cast(TypeExp)ws.exp).тип.toDsymbol(sc);
if (!s || !s.isScopeDsymbol())
{
ws.выведиОшибку("`with` тип `%s` has no члены", ws.exp.вТкст0());
return setError();
}
sym = new WithScopeSymbol(ws);
sym.родитель = sc.scopesym;
sym.endlinnum = ws.endloc.номстр;
}
else
{
Тип t = ws.exp.тип.toBasetype();
Выражение olde = ws.exp;
if (t.ty == Tpointer)
{
ws.exp = new PtrExp(ws.место, ws.exp);
ws.exp = ws.exp.ВыражениеSemantic(sc);
t = ws.exp.тип.toBasetype();
}
assert(t);
t = t.toBasetype();
if (t.isClassHandle())
{
_иниц = new ExpInitializer(ws.место, ws.exp);
ws.wthis = new VarDeclaration(ws.место, ws.exp.тип, Id.withSym, _иниц);
ws.wthis.dsymbolSemantic(sc);
sym = new WithScopeSymbol(ws);
sym.родитель = sc.scopesym;
sym.endlinnum = ws.endloc.номстр;
}
else if (t.ty == Tstruct)
{
if (!ws.exp.isLvalue())
{
/* Re-пиши to
* {
* auto __withtmp = exp
* with(__withtmp)
* {
* ...
* }
* }
*/
auto tmp = copyToTemp(0, "__withtmp", ws.exp);
tmp.dsymbolSemantic(sc);
auto es = new ExpStatement(ws.место, tmp);
ws.exp = new VarExp(ws.место, tmp);
Инструкция2 ss = new ScopeStatement(ws.место, new CompoundStatement(ws.место, es, ws), ws.endloc);
результат = ss.statementSemantic(sc);
return;
}
Выражение e = ws.exp.addressOf();
_иниц = new ExpInitializer(ws.место, e);
ws.wthis = new VarDeclaration(ws.место, e.тип, Id.withSym, _иниц);
ws.wthis.dsymbolSemantic(sc);
sym = new WithScopeSymbol(ws);
// Need to set the scope to make use of resolveAliasThis
sym.setScope(sc);
sym.родитель = sc.scopesym;
sym.endlinnum = ws.endloc.номстр;
}
else
{
ws.выведиОшибку("`with` Выражения must be aggregate types or pointers to them, not `%s`", olde.тип.вТкст0());
return setError();
}
}
if (ws._body)
{
sym._scope = sc;
sc = sc.сунь(sym);
sc.вставь(sym);
ws._body = ws._body.statementSemantic(sc);
sc.вынь();
if (ws._body && ws._body.isErrorStatement())
{
результат = ws._body;
return;
}
}
результат = ws;
}
// https://dlang.org/spec/инструкция.html#TryStatement
override проц посети(TryCatchStatement tcs)
{
//printf("TryCatchStatement.semantic()\n");
if (!глоб2.парамы.useExceptions)
{
tcs.выведиОшибку("Cannot use try-catch statements with -betterC");
return setError();
}
if (!ClassDeclaration.throwable)
{
tcs.выведиОшибку("Cannot use try-catch statements because `объект.Throwable` was not declared");
return setError();
}
бцел flags;
const FLAGcpp = 1;
const FLAGd = 2;
tcs.tryBody = sc.tryBody;
scope sc2 = sc.сунь();
sc2.tryBody = tcs;
tcs._body = tcs._body.semanticScope(sc, null, null);
assert(tcs._body);
sc2.вынь();
/* Even if body is empty, still do semantic analysis on catches
*/
бул catchErrors = нет;
foreach (i, c; *tcs.catches)
{
c.catchSemantic(sc);
if (c.errors)
{
catchErrors = да;
continue;
}
auto cd = c.тип.toBasetype().isClassHandle();
flags |= cd.isCPPclass() ? FLAGcpp : FLAGd;
// Determine if current catch 'hides' any previous catches
foreach (j; new бцел[0 .. i])
{
Уловитель cj = (*tcs.catches)[j];
const si = c.место.вТкст0();
const sj = cj.место.вТкст0();
if (c.тип.toBasetype().implicitConvTo(cj.тип.toBasetype()))
{
tcs.выведиОшибку("`catch` at %s hides `catch` at %s", sj, si);
catchErrors = да;
}
}
}
if (sc.func)
{
sc.func.flags |= FUNCFLAG.hasCatches;
if (flags == (FLAGcpp | FLAGd))
{
tcs.выведиОшибку("cannot mix catching D and C++ exceptions in the same try-catch");
catchErrors = да;
}
}
if (catchErrors)
return setError();
if (tcs._body.isErrorStatement())
{
результат = tcs._body;
return;
}
/* If the try body never throws, we can eliminate any catches
* of recoverable exceptions.
*/
if (!(tcs._body.blockExit(sc.func, нет) & BE.throw_) && ClassDeclaration.exception)
{
foreach_reverse (i; new бцел[0 .. tcs.catches.dim])
{
Уловитель c = (*tcs.catches)[i];
/* If catch exception тип is derived from Exception
*/
if (c.тип.toBasetype().implicitConvTo(ClassDeclaration.exception.тип) &&
(!c.handler || !c.handler.comeFrom()))
{
// Remove c from the массив of catches
tcs.catches.удали(i);
}
}
}
if (tcs.catches.dim == 0)
{
результат = tcs._body.hasCode() ? tcs._body : null;
return;
}
результат = tcs;
}
override проц посети(TryFinallyStatement tfs)
{
//printf("TryFinallyStatement::semantic()\n");
tfs.tryBody = sc.tryBody;
auto sc2 = sc.сунь();
sc.tryBody = tfs;
tfs._body = tfs._body.statementSemantic(sc);
sc2.вынь();
sc = sc.сунь();
sc.tf = tfs;
sc.sbreak = null;
sc.scontinue = null; // no break or continue out of finally block
tfs.finalbody = tfs.finalbody.semanticNoScope(sc);
sc.вынь();
if (!tfs._body)
{
результат = tfs.finalbody;
return;
}
if (!tfs.finalbody)
{
результат = tfs._body;
return;
}
auto blockexit = tfs._body.blockExit(sc.func, нет);
// if not worrying about exceptions
if (!(глоб2.парамы.useExceptions && ClassDeclaration.throwable))
blockexit &= ~BE.throw_; // don't worry about paths that otherwise may throw
// Don't care about paths that halt, either
if ((blockexit & ~BE.halt) == BE.fallthru)
{
результат = new CompoundStatement(tfs.место, tfs._body, tfs.finalbody);
return;
}
tfs.bodyFallsThru = (blockexit & BE.fallthru) != 0;
результат = tfs;
}
override проц посети(ScopeGuardStatement oss)
{
/* https://dlang.org/spec/инструкция.html#scope-guard-инструкция
*/
if (oss.tok != ТОК2.onScopeExit)
{
// scope(успех) and scope(failure) are rewritten to try-catch(-finally) инструкция,
// so the generated catch block cannot be placed in finally block.
// See also Уловитель::semantic.
if (sc.ос && sc.ос.tok != ТОК2.onScopeFailure)
{
// If enclosing is scope(успех) or scope(exit), this will be placed in finally block.
oss.выведиОшибку("cannot put `%s` инструкция inside `%s`", Сема2.вТкст0(oss.tok), Сема2.вТкст0(sc.ос.tok));
return setError();
}
if (sc.tf)
{
oss.выведиОшибку("cannot put `%s` инструкция inside `finally` block", Сема2.вТкст0(oss.tok));
return setError();
}
}
sc = sc.сунь();
sc.tf = null;
sc.ос = oss;
if (oss.tok != ТОК2.onScopeFailure)
{
// Jump out from scope(failure) block is allowed.
sc.sbreak = null;
sc.scontinue = null;
}
oss.инструкция = oss.инструкция.semanticNoScope(sc);
sc.вынь();
if (!oss.инструкция || oss.инструкция.isErrorStatement())
{
результат = oss.инструкция;
return;
}
результат = oss;
}
override проц посети(ThrowStatement ts)
{
/* https://dlang.org/spec/инструкция.html#throw-инструкция
*/
//printf("ThrowStatement::semantic()\n");
if (!глоб2.парамы.useExceptions)
{
ts.выведиОшибку("Cannot use `throw` statements with -betterC");
return setError();
}
if (!ClassDeclaration.throwable)
{
ts.выведиОшибку("Cannot use `throw` statements because `объект.Throwable` was not declared");
return setError();
}
FuncDeclaration fd = sc.родитель.isFuncDeclaration();
fd.hasReturnExp |= 2;
if (ts.exp.op == ТОК2.new_)
{
NewExp ne = cast(NewExp)ts.exp;
ne.thrownew = да;
}
ts.exp = ts.exp.ВыражениеSemantic(sc);
ts.exp = resolveProperties(sc, ts.exp);
ts.exp = checkGC(sc, ts.exp);
if (ts.exp.op == ТОК2.error)
return setError();
checkThrowEscape(sc, ts.exp, нет);
ClassDeclaration cd = ts.exp.тип.toBasetype().isClassHandle();
if (!cd || ((cd != ClassDeclaration.throwable) && !ClassDeclaration.throwable.isBaseOf(cd, null)))
{
ts.выведиОшибку("can only throw class objects derived from `Throwable`, not тип `%s`", ts.exp.тип.вТкст0());
return setError();
}
результат = ts;
}
override проц посети(DebugStatement ds)
{
if (ds.инструкция)
{
sc = sc.сунь();
sc.flags |= SCOPE.debug_;
ds.инструкция = ds.инструкция.statementSemantic(sc);
sc.вынь();
}
результат = ds.инструкция;
}
override проц посети(GotoStatement gs)
{
/* https://dlang.org/spec/инструкция.html#goto-инструкция
*/
//printf("GotoStatement::semantic()\n");
FuncDeclaration fd = sc.func;
gs.идент = fixupLabelName(sc, gs.идент);
gs.label = fd.searchLabel(gs.идент);
gs.tryBody = sc.tryBody;
gs.tf = sc.tf;
gs.ос = sc.ос;
gs.lastVar = sc.lastVar;
if (!gs.label.инструкция && sc.fes)
{
/* Either the goto label is forward referenced or it
* is in the function that the enclosing foreach is in.
* Can't know yet, so wrap the goto in a scope инструкция
* so we can patch it later, and add it to a 'look at this later'
* list.
*/
gs.label.deleted = да;
auto ss = new ScopeStatement(gs.место, gs, gs.место);
sc.fes.gotos.сунь(ss); // 'look at this later' list
результат = ss;
return;
}
// Add to fwdref list to check later
if (!gs.label.инструкция)
{
if (!fd.gotos)
fd.gotos = new GotoStatements();
fd.gotos.сунь(gs);
}
else if (gs.checkLabel())
return setError();
результат = gs;
}
override проц посети(LabelStatement ls)
{
//printf("LabelStatement::semantic()\n");
FuncDeclaration fd = sc.родитель.isFuncDeclaration();
ls.идент = fixupLabelName(sc, ls.идент);
ls.tryBody = sc.tryBody;
ls.tf = sc.tf;
ls.ос = sc.ос;
ls.lastVar = sc.lastVar;
LabelDsymbol ls2 = fd.searchLabel(ls.идент);
if (ls2.инструкция)
{
ls.выведиОшибку("label `%s` already defined", ls2.вТкст0());
return setError();
}
else
ls2.инструкция = ls;
sc = sc.сунь();
sc.scopesym = sc.enclosing.scopesym;
sc.ctorflow.orCSX(CSX.label);
sc.slabel = ls;
if (ls.инструкция)
ls.инструкция = ls.инструкция.statementSemantic(sc);
sc.вынь();
результат = ls;
}
override проц посети(AsmStatement s)
{
/* https://dlang.org/spec/инструкция.html#asm
*/
результат = asmSemantic(s, sc);
}
override проц посети(CompoundAsmStatement cas)
{
// Apply postfix attributes of the asm block to each инструкция.
sc = sc.сунь();
sc.stc |= cas.stc;
foreach (ref s; *cas.statements)
{
s = s ? s.statementSemantic(sc) : null;
}
assert(sc.func);
// use setImpure/setGC when the deprecation cycle is over
PURE purity;
if (!(cas.stc & STC.pure_) && (purity = sc.func.isPureBypassingInference()) != PURE.impure && purity != PURE.fwdref)
cas.deprecation("`asm` инструкция is assumed to be impure - mark it with `` if it is not");
if (!(cas.stc & STC.nogc) && sc.func.isNogcBypassingInference())
cas.deprecation("`asm` инструкция is assumed to use the СМ - mark it with `` if it does not");
if (!(cas.stc & (STC.trusted | STC.safe)) && sc.func.setUnsafe())
cas.выведиОшибку("`asm` инструкция is assumed to be `@system` - mark it with `@trusted` if it is not");
sc.вынь();
результат = cas;
}
override проц посети(ImportStatement imps)
{
/* https://dlang.org/spec/module.html#ImportDeclaration
*/
foreach (i; new бцел[0 .. imps.imports.dim])
{
Импорт s = (*imps.imports)[i].isImport();
assert(!s.aliasdecls.dim);
foreach (j, имя; s.имена)
{
Идентификатор2 _alias = s.ники[j];
if (!_alias)
_alias = имя;
auto tname = new TypeIdentifier(s.место, имя);
auto ad = new AliasDeclaration(s.место, _alias, tname);
ad._import = s;
s.aliasdecls.сунь(ad);
}
s.dsymbolSemantic(sc);
// https://issues.dlang.org/show_bug.cgi?ид=19942
// If the module that's being imported doesn't exist, don't add it to the symbol table
// for the current scope.
if (s.mod !is null)
{
Module.addDeferredSemantic2(s); // https://issues.dlang.org/show_bug.cgi?ид=14666
sc.вставь(s);
foreach (aliasdecl; s.aliasdecls)
{
sc.вставь(aliasdecl);
}
}
}
результат = imps;
}
}
проц catchSemantic(Уловитель c, Scope* sc)
{
//printf("Уловитель::semantic(%s)\n", идент.вТкст0());
if (sc.ос && sc.ос.tok != ТОК2.onScopeFailure)
{
// If enclosing is scope(успех) or scope(exit), this will be placed in finally block.
выведиОшибку(c.место, "cannot put `catch` инструкция inside `%s`", Сема2.вТкст0(sc.ос.tok));
c.errors = да;
}
if (sc.tf)
{
/* This is because the _d_local_unwind() gets the stack munged
* up on this. The workaround is to place any try-catches into
* a separate function, and call that.
* To fix, have the compiler automatically convert the finally
* body into a nested function.
*/
выведиОшибку(c.место, "cannot put `catch` инструкция inside `finally` block");
c.errors = да;
}
auto sym = new ScopeDsymbol();
sym.родитель = sc.scopesym;
sc = sc.сунь(sym);
if (!c.тип)
{
выведиОшибку(c.место, "`catch` инструкция without an exception specification is deprecated");
errorSupplemental(c.место, "use `catch(Throwable)` for old behavior");
c.errors = да;
// reference .объект.Throwable
c.тип = getThrowable();
}
c.тип = c.тип.typeSemantic(c.место, sc);
if (c.тип == Тип.terror)
c.errors = да;
else
{
КлассХранения stc;
auto cd = c.тип.toBasetype().isClassHandle();
if (!cd)
{
выведиОшибку(c.место, "can only catch class objects, not `%s`", c.тип.вТкст0());
c.errors = да;
}
else if (cd.isCPPclass())
{
if (!target.cpp.exceptions)
{
выведиОшибку(c.место, "catching C++ class objects not supported for this target");
c.errors = да;
}
if (sc.func && !sc.intypeof && !c.internalCatch && sc.func.setUnsafe())
{
выведиОшибку(c.место, "cannot catch C++ class objects in `` code");
c.errors = да;
}
}
else if (cd != ClassDeclaration.throwable && !ClassDeclaration.throwable.isBaseOf(cd, null))
{
выведиОшибку(c.место, "can only catch class objects derived from `Throwable`, not `%s`", c.тип.вТкст0());
c.errors = да;
}
else if (sc.func && !sc.intypeof && !c.internalCatch && ClassDeclaration.exception &&
cd != ClassDeclaration.exception && !ClassDeclaration.exception.isBaseOf(cd, null) &&
sc.func.setUnsafe())
{
выведиОшибку(c.место, "can only catch class objects derived from `Exception` in `` code, not `%s`", c.тип.вТкст0());
c.errors = да;
}
else if (глоб2.парамы.ehnogc)
{
stc |= STC.scope_;
}
// DIP1008 requires destruction of the Throwable, even if the user didn't specify an идентификатор
auto идент = c.идент;
if (!идент && глоб2.парамы.ehnogc)
идент = Идентификатор2.анонимный();
if (идент)
{
c.var = new VarDeclaration(c.место, c.тип, идент, null, stc);
c.var.iscatchvar = да;
c.var.dsymbolSemantic(sc);
sc.вставь(c.var);
if (глоб2.парамы.ehnogc && stc & STC.scope_)
{
/* Add a destructor for c.var
* try { handler } finally { if (!__ctfe) _d_delThrowable(var); }
*/
assert(!c.var.edtor); // ensure we didn't создай one in callScopeDtor()
Место место = c.место;
Выражение e = new VarExp(место, c.var);
e = new CallExp(место, new IdentifierExp(место, Id._d_delThrowable), e);
Выражение ec = new IdentifierExp(место, Id.ctfe);
ec = new NotExp(место, ec);
Инструкция2 s = new IfStatement(место, null, ec, new ExpStatement(место, e), null, место);
c.handler = new TryFinallyStatement(место, c.handler, s);
}
}
c.handler = c.handler.statementSemantic(sc);
if (c.handler && c.handler.isErrorStatement())
c.errors = да;
}
sc.вынь();
}
Инструкция2 semanticNoScope(Инструкция2 s, Scope* sc)
{
//printf("Инструкция2::semanticNoScope() %s\n", вТкст0());
if (!s.isCompoundStatement() && !s.isScopeStatement())
{
s = new CompoundStatement(s.место, s); // so scopeCode() gets called
}
s = s.statementSemantic(sc);
return s;
}
// Same as semanticNoScope(), but do создай a new scope
Инструкция2 semanticScope(Инструкция2 s, Scope* sc, Инструкция2 sbreak, Инструкция2 scontinue)
{
auto sym = new ScopeDsymbol();
sym.родитель = sc.scopesym;
Scope* scd = sc.сунь(sym);
if (sbreak)
scd.sbreak = sbreak;
if (scontinue)
scd.scontinue = scontinue;
s = s.semanticNoScope(scd);
scd.вынь();
return s;
}
/*******************
* Determines additional argument types for makeTupleForeach.
*/
static template TupleForeachArgs(бул isStatic, бул isDecl)
{
alias T Seq(T...);
static if(isStatic) alias Seq!(бул) T;
else alias Seq!() T;
static if(!isDecl) alias T TupleForeachArgs;
else alias Seq!(Дсимволы*,T) TupleForeachArgs;
}
/*******************
* Determines the return тип of makeTupleForeach.
*/
static template TupleForeachRet(бул isStatic, бул isDecl)
{
alias T Seq(T...);
static if(!isDecl) alias Инструкция2 TupleForeachRet;
else alias Дсимволы* TupleForeachRet;
}
/*******************
* See StatementSemanticVisitor.makeTupleForeach. This is a simple
* wrapper that returns the generated statements/declarations.
*/
TupleForeachRet!(isStatic, isDecl) makeTupleForeach(бул isStatic, бул isDecl)(Scope* sc, ForeachStatement fs, TupleForeachArgs!(isStatic, isDecl) args)
{
scope v = new StatementSemanticVisitor(sc);
static if(!isDecl)
{
v.makeTupleForeach!(isStatic, isDecl)(fs, args);
return v.результат;
}
else
{
return v.makeTupleForeach!(isStatic, isDecl)(fs, args);
}
}
| D |
// xasm 3.1.0 by Piotr Fusik <fox@scene.pl>
// http://xasm.atari.org
// Can be compiled with DMD v2.061.
// Poetic License:
//
// This work 'as-is' we provide.
// No warranty express or implied.
// We've done our best,
// to debug and test.
// Liability for damages denied.
//
// Permission is granted hereby,
// to copy, share, and modify.
// Use as is fit,
// free or for profit.
// These rights, on this notice, rely.
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.path;
import std.stdio;
version (Windows) {
import std.c.windows.windows;
extern (Windows) HANDLE GetStdHandle(DWORD nStdHandle);
}
const string TITLE = "xasm 3.1.0";
string sourceFilename = null;
bool[26] options;
string[26] optionParameters;
string[] commandLineDefinitions = null;
string makeTarget;
string[] makeSources = null;
int exitCode = 0;
int totalLines;
bool pass2 = false;
bool optionFill; // opt f
bool option5200; // opt g
bool optionHeaders; // opt h
bool optionListing; // opt l
bool optionObject; // opt o
string currentFilename;
int lineNo;
int includeLevel = 0;
string line;
int column;
bool foundEnd;
class AssemblyError : Exception {
this(string msg) {
super(msg);
}
}
class Label {
int value;
bool unused = true;
bool unknownInPass1 = false;
bool passed = false;
this(int value) {
this.value = value;
}
}
Label[string] labelTable;
Label currentLabel;
alias int function(int a, int b) OperatorFunction;
bool inOpcode = false;
struct ValOp {
int value;
OperatorFunction func;
int priority;
}
ValOp[] valOpStack;
int value;
bool unknownInPass1;
enum AddrMode {
ACCUMULATOR = 0,
IMMEDIATE = 1,
ABSOLUTE = 2,
ZEROPAGE = 3,
ABSOLUTE_X = 4,
ZEROPAGE_X = 5,
ABSOLUTE_Y = 6,
ZEROPAGE_Y = 7,
INDIRECT_X = 8,
INDIRECT_Y = 9,
INDIRECT = 10,
ABS_OR_ZP = 11, // temporarily used in readAddrMode
STANDARD_MASK = 15,
INCREMENT = 0x20,
DECREMENT = 0x30,
ZERO = 0x40
}
AddrMode addrMode;
int origin = -1;
int loadOrigin;
int loadingOrigin;
ushort[] blockEnds;
int blockIndex;
bool repeating; // line
int repeatCounter; // line
bool instructionBegin;
bool pairing;
bool willSkip;
bool skipping;
ushort[] skipOffsets;
int skipOffsetsIndex = 0;
int repeatOffset; // instruction repeat
bool wereManyInstructions;
alias void function(int move) MoveFunction;
int value1;
AddrMode addrMode1;
int value2;
AddrMode addrMode2;
struct IfContext {
bool condition;
bool wasElse;
bool aConditionMatched;
}
IfContext[] ifContexts;
File listingStream;
char[32] listingLine;
int listingColumn;
string lastListedFilename = null;
File objectStream;
int objectBytes = 0;
bool getOption(char letter) {
assert(letter >= 'a' && letter <= 'z');
return options[letter - 'a'];
}
void warning(string msg, bool error = false) {
stdout.flush();
version (Windows) {
HANDLE stderrHandle = GetStdHandle(STD_ERROR_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(stderrHandle, &csbi);
SetConsoleTextAttribute(stderrHandle, (csbi.wAttributes & ~0xf) | (error ? 12 : 14));
scope (exit) SetConsoleTextAttribute(stderrHandle, csbi.wAttributes);
}
if (line !is null)
stderr.writeln(line);
stderr.writefln("%s (%d) %s: %s", currentFilename, lineNo, error ? "ERROR" : "WARNING", msg);
exitCode = 1;
}
void illegalCharacter() {
throw new AssemblyError("Illegal character");
}
bool eol() {
return column >= line.length;
}
char readChar() {
if (eol())
throw new AssemblyError("Unexpected end of line");
return line[column++];
}
int readDigit(int base) {
if (eol()) return -1;
int r = line[column];
if (r >= '0' && r <= '9') {
r -= '0';
} else {
r &= 0xdf;
if (r >= 'A' && r <= 'Z')
r -= 'A' - 10;
else
return -1;
}
if (r < base) {
column++;
return r;
}
return -1;
}
int readNumber(int base) {
long r = readDigit(base);
if (r < 0)
illegalCharacter();
do {
int d = readDigit(base);
if (d < 0)
return cast(int) r;
r = r * base + d;
} while (r <= 0x7fffffff);
throw new AssemblyError("Number too big");
}
void readSpaces() {
switch (readChar()) {
case '\t':
case ' ':
break;
default:
throw new AssemblyError("Space expected");
}
while (!eol()) {
switch (line[column]) {
case '\t':
case ' ':
column++;
break;
default:
return;
}
}
}
string readLabel() {
string label;
while (!eol()) {
char c = line[column++];
if (c >= '0' && c <= '9' || c == '_') {
label ~= c;
continue;
}
c &= 0xdf;
if (c >= 'A' && c <= 'Z') {
label ~= c;
continue;
}
column--;
break;
}
return label >= "A" ? label : null;
}
void readComma() {
if (readChar() != ',')
throw new AssemblyError("Bad or missing function parameter");
}
string readInstruction() {
string r;
for (int i = 0; i < 3; i++) {
char c = readChar() & 0xdf;
if (c < 'A' || c > 'Z')
throw new AssemblyError("Illegal instruction");
r ~= c;
}
return r;
}
string readFunction() {
if (column + 5 >= line.length) return null;
if (line[column + 3] != '(') return null;
string r;
for (int i = 0; i < 3; i++) {
char c = line[column + i] & 0xdf;
if (c < 'A' || c > 'Z') return null;
r ~= c;
}
column += 4;
return r;
}
string readFilename() {
readSpaces();
char delimiter = readChar();
switch (delimiter) {
case '"':
case '\'':
string filename;
char c;
while ((c = readChar()) != delimiter)
filename ~= c;
return filename;
default:
illegalCharacter();
}
assert(0);
}
void readStringChar(char c) {
if (readChar() != c)
throw new AssemblyError("String error");
}
ubyte[] readString() {
if (eol()) return null;
char delimiter = readChar();
switch (delimiter) {
case '"':
case '\'':
ubyte[] r;
for (;;) {
char c = readChar();
if (c == delimiter) {
if (eol()) return r;
if (line[column] != delimiter) {
if (line[column] == '*') {
column++;
foreach (ref ubyte b; r)
b ^= 0x80;
}
return r;
}
column++;
}
r ~= cast(ubyte) c;
}
default:
column--;
return null;
}
}
void checkNoExtraCharacters() {
if (eol()) return;
switch (line[column]) {
case '\t':
case ' ':
return;
default:
throw new AssemblyError("Extra characters on line");
}
}
void checkOriginDefined() {
if (origin < 0)
throw new AssemblyError("No ORG specified");
}
int operatorPlus(int a, int b) {
return b;
}
int operatorMinus(int a, int b) {
return -b;
}
int operatorLow(int a, int b) {
return b & 0xff;
}
int operatorHigh(int a, int b) {
return (b >> 8) & 0xff;
}
int operatorLogicalNot(int a, int b) {
return !b;
}
int operatorBitwiseNot(int a, int b) {
return ~b;
}
int operatorAdd(int a, int b) {
long r = cast(long) a + b;
if (r < -0x80000000L || r > 0x7fffffffL)
throw new AssemblyError("Arithmetic overflow");
return a + b;
}
int operatorSubtract(int a, int b) {
long r = cast(long) a - b;
if (r < -0x80000000L || r > 0x7fffffffL)
throw new AssemblyError("Arithmetic overflow");
return a - b;
}
int operatorMultiply(int a, int b) {
long r = cast(long) a * b;
if (r < -0x80000000L || r > 0x7fffffffL)
throw new AssemblyError("Arithmetic overflow");
return a * b;
}
int operatorDivide(int a, int b) {
if (b == 0)
throw new AssemblyError("Divide by zero");
return a / b;
}
int operatorModulus(int a, int b) {
if (b == 0)
throw new AssemblyError("Divide by zero");
return a % b;
}
int operatorAnd(int a, int b) {
return a & b;
}
int operatorOr(int a, int b) {
return a | b;
}
int operatorXor(int a, int b) {
return a ^ b;
}
int operatorEqual(int a, int b) {
return a == b;
}
int operatorNotEqual(int a, int b) {
return a != b;
}
int operatorLess(int a, int b) {
return a < b;
}
int operatorGreater(int a, int b) {
return a > b;
}
int operatorLessEqual(int a, int b) {
return a <= b;
}
int operatorGreaterEqual(int a, int b) {
return a >= b;
}
int operatorShiftLeft(int a, int b) {
if (b < 0)
return operatorShiftRight(a, -b);
if (a != 0 && b >= 32)
throw new AssemblyError("Arithmetic overflow");
long r = cast(long) a << b;
if (r & 0xffffffff00000000L)
throw new AssemblyError("Arithmetic overflow");
return a << b;
}
int operatorShiftRight(int a, int b) {
if (b < 0)
return operatorShiftLeft(a, -b);
if (b >= 32)
b = 31;
return a >> b;
}
int operatorLogicalAnd(int a, int b) {
return a && b;
}
int operatorLogicalOr(int a, int b) {
return a || b;
}
void pushValOp(int value, OperatorFunction func, int priority) {
ValOp valOp;
valOp.value = value;
valOp.func = func;
valOp.priority = priority;
valOpStack ~= valOp;
}
void readValue() {
assert(valOpStack.length == 0);
unknownInPass1 = false;
int priority = 0;
do {
int operand;
char c = readChar();
switch (c) {
case '[':
priority += 10;
continue;
case '+':
pushValOp(0, &operatorPlus, priority + 8);
continue;
case '-':
pushValOp(0, &operatorMinus, priority + 8);
continue;
case '<':
pushValOp(0, &operatorLow, priority + 8);
continue;
case '>':
pushValOp(0, &operatorHigh, priority + 8);
continue;
case '!':
pushValOp(0, &operatorLogicalNot, priority + 4);
continue;
case '~':
pushValOp(0, &operatorBitwiseNot, priority + 8);
continue;
case '(':
throw new AssemblyError("Use square brackets instead");
case '*':
checkOriginDefined();
operand = origin;
break;
case '#':
if (!repeating)
throw new AssemblyError("'#' is allowed only in repeated lines");
operand = repeatCounter;
break;
case '\'':
case '"':
operand = readChar();
if (operand == c)
readStringChar(c);
readStringChar(c);
if (!eol() && line[column] == '*') {
column++;
operand ^= 0x80;
}
break;
case '^':
switch (readChar()) {
case '0':
operand = option5200 ? 0xc000 : 0xd000;
break;
case '1':
operand = option5200 ? 0xc010 : 0xd010;
break;
case '2':
operand = option5200 ? 0xe800 : 0xd200;
break;
case '3':
if (option5200)
throw new AssemblyError("There's no PIA chip in Atari 5200");
operand = 0xd300;
break;
case '4':
operand = 0xd400;
break;
default:
illegalCharacter();
}
int d = readDigit(16);
if (d < 0)
illegalCharacter();
operand += d;
break;
case '{':
if (inOpcode)
throw new AssemblyError("Nested opcodes not supported");
ValOp[] savedValOpStack = valOpStack;
AddrMode savedAddrMode = addrMode;
bool savedUnknownInPass1 = unknownInPass1;
bool savedInstructionBegin = instructionBegin;
valOpStack.length = 0;
inOpcode = true;
assemblyInstruction(readInstruction());
if (readChar() != '}')
throw new AssemblyError("Missing '}'");
assert(!instructionBegin);
inOpcode = false;
valOpStack = savedValOpStack;
addrMode = savedAddrMode;
unknownInPass1 = savedUnknownInPass1;
instructionBegin = savedInstructionBegin;
operand = value;
break;
case '$':
operand = readNumber(16);
break;
case '%':
operand = readNumber(2);
break;
default:
column--;
if (c >= '0' && c <= '9') {
operand = readNumber(10);
break;
}
string label = readLabel();
if (label is null)
illegalCharacter();
if (label in labelTable) {
Label l = labelTable[label];
operand = l.value;
l.unused = false;
if (pass2) {
if (l.passed) {
if (l.unknownInPass1)
unknownInPass1 = true;
} else {
if (l.unknownInPass1)
throw new AssemblyError("Illegal forward reference");
unknownInPass1 = true;
}
} else {
if (l.unknownInPass1)
unknownInPass1 = true;
}
} else {
if (pass2)
throw new AssemblyError("Undeclared label: " ~ label);
unknownInPass1 = true;
}
break;
}
while (!eol() && line[column] == ']') {
column++;
priority -= 10;
if (priority < 0)
throw new AssemblyError("Unmatched bracket");
}
if (eol()) {
if (priority != 0)
throw new AssemblyError("Unmatched bracket");
pushValOp(operand, &operatorPlus, 1);
} else {
switch (line[column++]) {
case '+':
pushValOp(operand, &operatorAdd, priority + 6);
break;
case '-':
pushValOp(operand, &operatorSubtract, priority + 6);
break;
case '*':
pushValOp(operand, &operatorMultiply, priority + 7);
break;
case '/':
pushValOp(operand, &operatorDivide, priority + 7);
break;
case '%':
pushValOp(operand, &operatorModulus, priority + 7);
break;
case '<':
switch (readChar()) {
case '<':
pushValOp(operand, &operatorShiftLeft, priority + 7);
break;
case '=':
pushValOp(operand, &operatorLessEqual, priority + 5);
break;
case '>':
pushValOp(operand, &operatorNotEqual, priority + 5);
break;
default:
column--;
pushValOp(operand, &operatorLess, priority + 5);
break;
}
break;
case '=':
switch (readChar()) {
default:
column--;
goto case '=';
case '=':
pushValOp(operand, &operatorEqual, priority + 5);
break;
}
break;
case '>':
switch (readChar()) {
case '>':
pushValOp(operand, &operatorShiftRight, priority + 7);
break;
case '=':
pushValOp(operand, &operatorGreaterEqual, priority + 5);
break;
default:
column--;
pushValOp(operand, &operatorGreater, priority + 5);
break;
}
break;
case '!':
switch (readChar()) {
case '=':
pushValOp(operand, &operatorNotEqual, priority + 5);
break;
default:
illegalCharacter();
}
break;
case '&':
switch (readChar()) {
case '&':
pushValOp(operand, &operatorLogicalAnd, priority + 3);
break;
default:
column--;
pushValOp(operand, &operatorAnd, priority + 7);
break;
}
break;
case '|':
switch (readChar()) {
case '|':
pushValOp(operand, &operatorLogicalOr, priority + 2);
break;
default:
column--;
pushValOp(operand, &operatorOr, priority + 6);
break;
}
break;
case '^':
pushValOp(operand, &operatorXor, priority + 6);
break;
default:
column--;
if (priority != 0)
throw new AssemblyError("Unmatched bracket");
pushValOp(operand, &operatorPlus, 1);
break;
}
}
for (;;) {
immutable sp = valOpStack.length - 1;
if (sp <= 0 || valOpStack[sp].priority > valOpStack[sp - 1].priority)
break;
int operand1 = valOpStack[sp - 1].value;
OperatorFunction func1 = valOpStack[sp - 1].func;
valOpStack[sp - 1] = valOpStack[sp];
valOpStack.length = sp;
if (pass2 || !unknownInPass1) { // skip operations if unknown operands
valOpStack[sp - 1].value = func1(operand1, valOpStack[sp - 1].value);
}
}
} while (valOpStack.length != 1 || valOpStack[0].priority != 1);
value = valOpStack[0].value;
valOpStack.length = 0;
}
debug int testValue(string l) {
line = l;
column = 0;
readValue();
writefln("Value of %s is %x", l, value);
return value;
}
unittest {
assert(testValue("123") == 123);
assert(testValue("$1234abCd") == 0x1234abcd);
assert(testValue("%101") == 5);
assert(testValue("^07") == 0xd007);
assert(testValue("^1f") == 0xd01f);
assert(testValue("^23") == 0xd203);
assert(testValue("^31") == 0xd301);
assert(testValue("^49") == 0xd409);
assert(testValue("!0") == 1);
assert(testValue("<$1234") == 0x34);
assert(testValue(">$1234567") == 0x45);
assert(testValue("1+2") == 3);
assert(testValue("1+2*3") == 7);
assert(testValue("[1+2]*3") == 9);
assert(testValue("{nop}") == 0xea);
assert(testValue("{CLC}+{sec}") == 0x50);
assert(testValue("{Jsr}") == 0x20);
assert(testValue("{bit a:}") == 0x2c);
assert(testValue("{bIt $7d}") == 0x24);
}
void mustBeKnownInPass1() {
if (unknownInPass1)
throw new AssemblyError("Label not defined before");
}
void readWord() {
readValue();
if ((!unknownInPass1 || pass2) && (value < -0xffff || value > 0xffff))
throw new AssemblyError("Value out of range");
}
void readUnsignedWord() {
readWord();
if ((!unknownInPass1 || pass2) && value < 0)
throw new AssemblyError("Value out of range");
}
void readKnownPositive() {
readValue();
mustBeKnownInPass1();
if (value <= 0)
throw new AssemblyError("Value out of range");
}
void optionalIncDec() {
if (eol()) return;
switch (line[column]) {
case '+':
column++;
addrMode += AddrMode.INCREMENT;
return;
case '-':
column++;
addrMode += AddrMode.DECREMENT;
return;
default:
return;
}
}
void readAddrMode() {
readSpaces();
char c = readChar();
switch (c) {
case '@':
addrMode = AddrMode.ACCUMULATOR;
return;
case '#':
case '<':
case '>':
addrMode = AddrMode.IMMEDIATE;
if (inOpcode && line[column] == '}')
return;
readWord();
final switch (c) {
case '#':
break;
case '<':
value &= 0xff;
break;
case '>':
value = (value >> 8) & 0xff;
break;
}
return;
case '(':
if (inOpcode) {
switch (readChar()) {
case ',':
switch (readChar()) {
case 'X':
case 'x':
break;
default:
illegalCharacter();
}
if (readChar() != ')')
throw new AssemblyError("Need parenthesis");
addrMode = AddrMode.INDIRECT_X;
return;
case ')':
if (readChar() == ',') {
switch (readChar()) {
case 'Y':
case 'y':
break;
default:
illegalCharacter();
}
addrMode = AddrMode.INDIRECT_Y;
return;
} else {
column--;
addrMode = AddrMode.INDIRECT;
return;
}
default:
column--;
break;
}
}
readUnsignedWord();
switch (readChar()) {
case ',':
switch (readChar()) {
case 'X':
case 'x':
addrMode = AddrMode.INDIRECT_X;
break;
case '0':
addrMode = cast(AddrMode) (AddrMode.INDIRECT_X + AddrMode.ZERO);
break;
default:
illegalCharacter();
}
if (readChar() != ')')
throw new AssemblyError("Need parenthesis");
return;
case ')':
if (eol()) {
addrMode = AddrMode.INDIRECT;
return;
}
if (line[column] == ',') {
column++;
switch (readChar()) {
case 'Y':
case 'y':
addrMode = AddrMode.INDIRECT_Y;
break;
case '0':
addrMode = cast(AddrMode) (AddrMode.INDIRECT_Y + AddrMode.ZERO);
break;
default:
illegalCharacter();
}
optionalIncDec();
return;
}
addrMode = AddrMode.INDIRECT;
return;
default:
illegalCharacter();
}
break;
case 'A':
case 'a':
if (!eol() && line[column] == ':') {
column++;
addrMode = AddrMode.ABSOLUTE;
} else {
addrMode = AddrMode.ABS_OR_ZP;
column--;
}
break;
case 'Z':
case 'z':
if (!eol() && line[column] == ':') {
column++;
addrMode = AddrMode.ZEROPAGE;
} else {
addrMode = AddrMode.ABS_OR_ZP;
column--;
}
break;
default:
addrMode = AddrMode.ABS_OR_ZP;
column--;
break;
}
// absolute or zeropage addressing, optionally indexed
if (inOpcode && (addrMode == AddrMode.ABSOLUTE || addrMode == AddrMode.ZEROPAGE)) {
switch (readChar()) {
case '}':
column--;
return;
case ',':
switch (readChar()) {
case 'X':
case 'x':
addrMode += cast(AddrMode) (AddrMode.ABSOLUTE_X - AddrMode.ABSOLUTE);
return;
case 'Y':
case 'y':
addrMode += cast(AddrMode) (AddrMode.ABSOLUTE_Y - AddrMode.ABSOLUTE);
return;
default:
illegalCharacter();
}
return;
default:
column--;
break;
}
}
readUnsignedWord();
if (addrMode == AddrMode.ABS_OR_ZP) {
if (unknownInPass1 || value > 0xff)
addrMode = AddrMode.ABSOLUTE;
else
addrMode = AddrMode.ZEROPAGE;
}
if (eol()) return;
if (line[column] == ',') {
column++;
switch (readChar()) {
case 'X':
case 'x':
addrMode += cast(AddrMode) (AddrMode.ABSOLUTE_X - AddrMode.ABSOLUTE);
optionalIncDec();
return;
case 'Y':
case 'y':
addrMode += cast(AddrMode) (AddrMode.ABSOLUTE_Y - AddrMode.ABSOLUTE);
optionalIncDec();
return;
default:
illegalCharacter();
}
}
}
void readAbsoluteAddrMode() {
if (inOpcode && readChar() == '}') {
column--;
} else {
readAddrMode();
switch (addrMode) {
case AddrMode.ABSOLUTE:
case AddrMode.ZEROPAGE:
break;
default:
illegalAddrMode();
}
}
addrMode = AddrMode.ABSOLUTE;
}
debug AddrMode testAddrMode(string l) {
line = l;
column = 0;
readAddrMode();
writefln("Addressing mode of \"%s\" is %x", l, addrMode);
return addrMode;
}
unittest {
assert(testAddrMode(" @") == AddrMode.ACCUMULATOR);
assert(testAddrMode(" #0") == AddrMode.IMMEDIATE);
assert(testAddrMode(" $abc,x-") == cast(AddrMode) (AddrMode.ABSOLUTE_X + AddrMode.DECREMENT));
assert(testAddrMode(" $ab,Y+") == cast(AddrMode) (AddrMode.ZEROPAGE_Y + AddrMode.INCREMENT));
assert(testAddrMode(" (0,x)") == AddrMode.INDIRECT_X);
assert(testAddrMode(" ($ff),Y+") == cast(AddrMode) (AddrMode.INDIRECT_Y + AddrMode.INCREMENT));
assert(testAddrMode(" ($abcd)") == AddrMode.INDIRECT);
inOpcode = true;
assert(testAddrMode(" a:}") == AddrMode.ABSOLUTE);
assert(testAddrMode(" z:}") == AddrMode.ZEROPAGE);
assert(testAddrMode(" a:,x}") == AddrMode.ABSOLUTE_X);
assert(testAddrMode(" z:,y}") == AddrMode.ZEROPAGE_Y);
assert(testAddrMode(" (,X)}") == AddrMode.INDIRECT_X);
assert(testAddrMode(" (),y}") == AddrMode.INDIRECT_Y);
assert(testAddrMode(" ()}") == AddrMode.INDIRECT);
inOpcode = false;
}
bool inFalseCondition() {
foreach (IfContext ic; ifContexts) {
if (!ic.condition) return true;
}
return false;
}
string makeEscape(string s) {
return s.replace("$", "$$");
}
File openInputFile(string filename) {
if (find(makeSources, filename).empty)
makeSources ~= filename;
try {
return File(filename);
} catch (Exception e) {
throw new AssemblyError(e.msg);
}
}
File openOutputFile(char letter, string defaultExt) {
string filename = optionParameters[letter - 'a'];
if (filename is null)
filename = sourceFilename.setExtension(defaultExt);
if (letter == 'o')
makeTarget = makeEscape(filename);
try {
return File(filename, "wb");
} catch (Exception e) {
throw new AssemblyError(e.msg);
}
}
void ensureListingFileOpen(char letter, string msg) {
if (!listingStream.isOpen) {
listingStream = openOutputFile(letter, "lst");
if (!getOption('q'))
write(msg);
listingStream.writeln(TITLE);
}
}
void listNibble(int x) {
listingLine[listingColumn++] = cast(char) (x <= 9 ? x + '0' : x + ('A' - 10));
}
void listByte(ubyte x) {
listNibble(x >> 4);
listNibble(x & 0xf);
}
void listWord(ushort x) {
listByte(cast(ubyte) (x >> 8));
listByte(cast(ubyte) x);
}
void listLine() {
if (!optionListing || !getOption('l') || line is null)
return;
assert(pass2);
if (inFalseCondition() && !getOption('c'))
return;
if (getOption('i') && includeLevel > 0)
return;
ensureListingFileOpen('l', "Writing listing file...\n");
if (currentFilename != lastListedFilename) {
listingStream.writeln("Source: ", currentFilename);
lastListedFilename = currentFilename;
}
int i = 4;
int x = lineNo;
while (x > 0 && i >= 0) {
listingLine[i--] = '0' + x % 10;
x /= 10;
}
while (i >= 0)
listingLine[i--] = ' ';
listingLine[5] = ' ';
while (listingColumn < 32)
listingLine[listingColumn++] = ' ';
listingStream.writefln("%.32s%s", listingLine, line);
}
void listCommentLine() {
if (currentLabel is null)
listingColumn = 6;
else {
assert(!inFalseCondition());
checkOriginDefined();
}
listLine();
}
void listLabelTable() {
if (optionParameters['t' - 'a'] !is null && listingStream.isOpen)
listingStream.close();
ensureListingFileOpen('t', "Writing label table...\n");
listingStream.writeln("Label table:");
foreach (string name; labelTable.keys.sort) {
Label l = labelTable[name];
listingStream.write(l.unused ? 'n' : ' ');
listingStream.write(l.unknownInPass1 ? '2' : ' ');
int value = l.value;
char sign = ' ';
if (value < 0) {
sign = '-';
value = -value;
}
listingStream.writefln(
(l.value & 0xffff0000) != 0 ? " %s%08X %s" : " %s%04X %s",
sign, value, name);
}
}
debug ubyte[] objectBuffer;
void objectByte(ubyte b) {
debug {
objectBuffer ~= b;
} else {
assert(pass2);
if (!optionObject) return;
if (!objectStream.isOpen) {
objectStream = openOutputFile('o', "obx");
if (!getOption('q'))
writeln("Writing object file...");
}
ubyte[1] buffer;
buffer[0] = b;
try {
objectStream.rawWrite(buffer);
} catch (Exception e) {
throw new AssemblyError("Error writing object file");
}
}
objectBytes++;
}
void objectWord(ushort w) {
objectByte(cast(ubyte) w);
objectByte(cast(ubyte) (w >> 8));
}
void putByte(ubyte b) {
if (inOpcode) {
if (instructionBegin) {
value = b;
instructionBegin = false;
}
return;
}
if (willSkip) {
assert(!pass2);
willSkip = false;
skipping = true;
}
if (skipping) {
assert(!pass2);
skipOffsets[$ - 1]++;
}
if (instructionBegin) {
repeatOffset = -2;
instructionBegin = false;
}
repeatOffset--;
if (optionFill && loadingOrigin >= 0 && loadingOrigin != loadOrigin) {
if (loadingOrigin > loadOrigin)
throw new AssemblyError("Can't fill from higher to lower memory location");
if (pass2) {
while (loadingOrigin < loadOrigin) {
objectByte(0xff);
loadingOrigin++;
}
}
}
debug {
objectByte(b);
}
if (pass2) {
debug {
}else {
objectByte(b);
}
if (listingColumn < 29) {
listByte(b);
listingLine[listingColumn++] = ' ';
} else {
listingLine[29] = '+';
listingColumn = 30;
}
}
if (optionHeaders) {
if (origin < 0)
throw new AssemblyError("No ORG specified");
assert(blockIndex >= 0);
if (!pass2) {
blockEnds[blockIndex] = cast(ushort) loadOrigin;
}
}
if (origin >= 0) {
origin++;
loadingOrigin = ++loadOrigin;
}
}
void putWord(ushort w) {
putByte(cast(ubyte) w);
putByte(cast(ubyte) (w >> 8));
}
void putCommand(ubyte b) {
putByte(b);
if (inOpcode) return;
switch (addrMode & AddrMode.STANDARD_MASK) {
case AddrMode.ACCUMULATOR:
break;
case AddrMode.IMMEDIATE:
case AddrMode.ZEROPAGE:
case AddrMode.ZEROPAGE_X:
case AddrMode.ZEROPAGE_Y:
case AddrMode.INDIRECT_X:
case AddrMode.INDIRECT_Y:
if (pass2 && (value < -0xff || value > 0xff))
throw new AssemblyError("Value out of range");
putByte(cast(ubyte) value);
break;
case AddrMode.ABSOLUTE:
case AddrMode.ABSOLUTE_X:
case AddrMode.ABSOLUTE_Y:
case AddrMode.INDIRECT:
putWord(cast(ushort) value);
break;
default:
assert(0);
}
switch (addrMode) {
case cast(AddrMode) (AddrMode.ABSOLUTE_X + AddrMode.INCREMENT):
case cast(AddrMode) (AddrMode.ZEROPAGE_X + AddrMode.INCREMENT):
putByte(0xe8);
break;
case cast(AddrMode) (AddrMode.ABSOLUTE_X + AddrMode.DECREMENT):
case cast(AddrMode) (AddrMode.ZEROPAGE_X + AddrMode.DECREMENT):
putByte(0xca);
break;
case cast(AddrMode) (AddrMode.ABSOLUTE_Y + AddrMode.INCREMENT):
case cast(AddrMode) (AddrMode.ZEROPAGE_Y + AddrMode.INCREMENT):
case cast(AddrMode) (AddrMode.INDIRECT_Y + AddrMode.INCREMENT):
case cast(AddrMode) (AddrMode.INDIRECT_Y + AddrMode.INCREMENT + AddrMode.ZERO):
putByte(0xc8);
break;
case cast(AddrMode) (AddrMode.ABSOLUTE_Y + AddrMode.DECREMENT):
case cast(AddrMode) (AddrMode.ZEROPAGE_Y + AddrMode.DECREMENT):
case cast(AddrMode) (AddrMode.INDIRECT_Y + AddrMode.DECREMENT):
case cast(AddrMode) (AddrMode.INDIRECT_Y + AddrMode.DECREMENT + AddrMode.ZERO):
putByte(0x88);
break;
default:
break;
}
}
void noOpcode() {
if (inOpcode)
throw new AssemblyError("Can't get opcode of this");
}
void directive() {
noOpcode();
if (repeating)
throw new AssemblyError("Can't repeat this directive");
if (pairing)
throw new AssemblyError("Can't pair this directive");
}
void noRepeatSkipDirective() {
directive();
if (willSkip)
throw new AssemblyError("Can't skip over this");
repeatOffset = 0;
}
void illegalAddrMode() {
throw new AssemblyError("Illegal addressing mode");
}
void addrModeForMove(int move) {
final switch (move) {
case 0:
readAddrMode();
break;
case 1:
value = value1;
addrMode = addrMode1;
break;
case 2:
value = value2;
addrMode = addrMode2;
break;
}
}
void assemblyAccumulator(ubyte b, ubyte prefix, int move) {
addrModeForMove(move);
if (prefix != 0)
putByte(prefix);
switch (addrMode & AddrMode.STANDARD_MASK) {
case AddrMode.ACCUMULATOR:
case AddrMode.INDIRECT:
illegalAddrMode();
case AddrMode.IMMEDIATE:
if (b == 0x80) {
// STA #
illegalAddrMode();
}
putCommand(cast(ubyte) (b + 9));
break;
case AddrMode.ABSOLUTE:
putCommand(cast(ubyte) (b + 0xd));
break;
case AddrMode.ZEROPAGE:
putCommand(cast(ubyte) (b + 5));
break;
case AddrMode.ABSOLUTE_X:
putCommand(cast(ubyte) (b + 0x1d));
break;
case AddrMode.ZEROPAGE_X:
putCommand(cast(ubyte) (b + 0x15));
break;
case AddrMode.ZEROPAGE_Y:
addrMode -= 1;
goto case AddrMode.ABSOLUTE_Y;
case AddrMode.ABSOLUTE_Y:
putCommand(cast(ubyte) (b + 0x19));
break;
case AddrMode.INDIRECT_X:
if ((addrMode & AddrMode.ZERO) != 0)
putWord(0x00a2);
putCommand(cast(ubyte) (b + 1));
break;
case AddrMode.INDIRECT_Y:
if ((addrMode & AddrMode.ZERO) != 0)
putWord(0x00a0);
putCommand(cast(ubyte) (b + 0x11));
break;
default:
assert(0);
}
}
void assemblyShift(ubyte b) {
readAddrMode();
switch (addrMode & AddrMode.STANDARD_MASK) {
case AddrMode.ACCUMULATOR:
if (b == 0xc0 || b == 0xe0) {
// INC @, DEC @
illegalAddrMode();
}
putByte(cast(ubyte) (b + 0xa));
break;
case AddrMode.ABSOLUTE:
putCommand(cast(ubyte) (b + 0xe));
break;
case AddrMode.ZEROPAGE:
putCommand(cast(ubyte) (b + 6));
break;
case AddrMode.ABSOLUTE_X:
putCommand(cast(ubyte) (b + 0x1e));
break;
case AddrMode.ZEROPAGE_X:
putCommand(cast(ubyte) (b + 0x16));
break;
default:
illegalAddrMode();
}
}
void assemblyCompareIndex(ubyte b) {
readAddrMode();
switch (addrMode) {
case AddrMode.IMMEDIATE:
putCommand(b);
break;
case AddrMode.ABSOLUTE:
putCommand(cast(ubyte) (b + 0xc));
break;
case AddrMode.ZEROPAGE:
putCommand(cast(ubyte) (b + 4));
break;
default:
illegalAddrMode();
}
}
void assemblyLda(int move) {
assemblyAccumulator(0xa0, 0, move);
}
void assemblyLdx(int move) {
addrModeForMove(move);
switch (addrMode & AddrMode.STANDARD_MASK) {
case AddrMode.IMMEDIATE:
putCommand(0xa2);
break;
case AddrMode.ABSOLUTE:
putCommand(0xae);
break;
case AddrMode.ZEROPAGE:
putCommand(0xa6);
break;
case AddrMode.ABSOLUTE_Y:
putCommand(0xbe);
break;
case AddrMode.ZEROPAGE_Y:
putCommand(0xb6);
break;
default:
illegalAddrMode();
}
}
void assemblyLdy(int move) {
addrModeForMove(move);
switch (addrMode & AddrMode.STANDARD_MASK) {
case AddrMode.IMMEDIATE:
putCommand(0xa0);
break;
case AddrMode.ABSOLUTE:
putCommand(0xac);
break;
case AddrMode.ZEROPAGE:
putCommand(0xa4);
break;
case AddrMode.ABSOLUTE_X:
putCommand(0xbc);
break;
case AddrMode.ZEROPAGE_X:
putCommand(0xb4);
break;
default:
illegalAddrMode();
}
}
void assemblySta(int move) {
assemblyAccumulator(0x80, 0, move);
}
void assemblyStx(int move) {
addrModeForMove(move);
switch (addrMode & AddrMode.STANDARD_MASK) {
case AddrMode.ABSOLUTE:
putCommand(0x8e);
break;
case AddrMode.ZEROPAGE:
putCommand(0x86);
break;
case AddrMode.ABSOLUTE_Y:
addrMode += 1;
goto case AddrMode.ZEROPAGE_Y;
case AddrMode.ZEROPAGE_Y:
putCommand(0x96);
break;
default:
illegalAddrMode();
}
}
void assemblySty(int move) {
addrModeForMove(move);
switch (addrMode & AddrMode.STANDARD_MASK) {
case AddrMode.ABSOLUTE:
putCommand(0x8c);
break;
case AddrMode.ZEROPAGE:
putCommand(0x84);
break;
case AddrMode.ABSOLUTE_X:
addrMode += 1;
goto case AddrMode.ZEROPAGE_X;
case AddrMode.ZEROPAGE_X:
putCommand(0x94);
break;
default:
illegalAddrMode();
}
}
void assemblyBit() {
readAddrMode();
switch (addrMode) {
case AddrMode.ABSOLUTE:
putCommand(0x2c);
break;
case AddrMode.ZEROPAGE:
putCommand(0x24);
break;
default:
illegalAddrMode();
}
}
void putJump() {
switch (addrMode) {
case AddrMode.ZEROPAGE:
addrMode = AddrMode.ABSOLUTE;
goto case AddrMode.ABSOLUTE;
case AddrMode.ABSOLUTE:
putCommand(0x4c);
break;
case AddrMode.INDIRECT:
if (pass2 && (value & 0xff) == 0xff)
warning("Buggy indirect jump");
putCommand(0x6c);
break;
default:
illegalAddrMode();
}
}
void assemblyJmp() {
readAddrMode();
putJump();
}
void assemblyConditionalJump(ubyte b) {
noOpcode();
readAddrMode();
if ((addrMode == AddrMode.ABSOLUTE || addrMode == AddrMode.ZEROPAGE)
&& pass2 && origin >= 0 && value - origin - 2 >= -0x80 && value - origin - 2 <= 0x7f) {
warning("Plain branch instruction would be sufficient");
}
putByte(b);
putByte(3);
putJump();
}
void assemblyJsr() {
readAbsoluteAddrMode();
putCommand(0x20);
}
ubyte calculateBranch(int offset) {
if (offset < -0x80 || offset > 0x7f) {
int dist = offset < 0 ? -offset - 0x80 : offset - 0x7f;
throw new AssemblyError("Branch out of range by " ~ to!string(dist) ~ " bytes");
}
return cast(ubyte) offset;
}
void assemblyBranch(ubyte b) {
readAbsoluteAddrMode();
if (inOpcode) {
putByte(b);
return;
}
checkOriginDefined();
putByte(b);
putByte(pass2 ? calculateBranch(value - origin - 1) : 0);
}
void assemblyRepeat(ubyte b) {
noOpcode();
int offset = repeatOffset;
if (offset >= 0)
throw new AssemblyError("No instruction to repeat");
if (pass2 && wereManyInstructions)
warning("Repeating only the last instruction");
putByte(b);
putByte(calculateBranch(offset));
}
void assemblySkip(ubyte b) {
noOpcode();
if (willSkip) {
skipOffsets[$ - 1] = 2;
willSkip = false;
}
putByte(b);
if (pass2)
putByte(calculateBranch(skipOffsets[skipOffsetsIndex++]));
else {
putByte(0);
skipOffsets ~= 0;
willSkip = true;
}
}
void assemblyInw() {
noOpcode();
readAddrMode();
switch (addrMode) {
case AddrMode.ABSOLUTE:
putCommand(0xee);
putWord(0x03d0);
value++;
putCommand(0xee);
break;
case AddrMode.ZEROPAGE:
putCommand(0xe6);
putWord(0x02d0);
value++;
putCommand(0xe6);
break;
case AddrMode.ABSOLUTE_X:
putCommand(0xfe);
putWord(0x03d0);
value++;
putCommand(0xfe);
break;
case AddrMode.ZEROPAGE_X:
putCommand(0xf6);
putWord(0x02d0);
value++;
putCommand(0xf6);
break;
default:
illegalAddrMode();
}
}
void assemblyMove() {
noOpcode();
readAddrMode();
value1 = value;
addrMode1 = addrMode;
bool unknown1 = unknownInPass1;
readAddrMode();
value2 = value;
addrMode2 = addrMode;
unknownInPass1 = unknown1;
}
void assemblyMoveByte(MoveFunction load, MoveFunction store) {
assemblyMove();
load(1);
store(2);
}
void assemblyMoveWord(MoveFunction load, MoveFunction store, ubyte inc, ubyte dec) {
assemblyMove();
switch (addrMode2) {
case AddrMode.ABSOLUTE:
case AddrMode.ZEROPAGE:
case AddrMode.ABSOLUTE_X:
case AddrMode.ZEROPAGE_X:
case AddrMode.ABSOLUTE_Y:
case AddrMode.ZEROPAGE_Y:
break;
default:
illegalAddrMode();
}
switch (addrMode1) {
case AddrMode.IMMEDIATE:
int high = value1 >> 8;
value1 &= 0xff;
load(1);
store(2);
value2++;
if (unknownInPass1) {
value1 = high;
load(1);
} else {
if (inc != 0 && cast(ubyte) (value1 + 1) == high)
putByte(inc);
else if (dec != 0 && cast(ubyte) (value1 - 1) == high)
putByte(dec);
else if (value1 != high) {
value1 = high;
load(1);
}
}
store(2);
break;
case AddrMode.ABSOLUTE:
case AddrMode.ZEROPAGE:
case AddrMode.ABSOLUTE_X:
case AddrMode.ZEROPAGE_X:
case AddrMode.ABSOLUTE_Y:
case AddrMode.ZEROPAGE_Y:
load(1);
store(2);
value1++;
value2++;
load(1);
store(2);
break;
default:
illegalAddrMode();
}
}
void storeDtaNumber(int val, char letter) {
int limit = 0xffff;
if (letter == 'b') limit = 0xff;
if ((!unknownInPass1 || pass2) && (val < -limit || val > limit))
throw new AssemblyError("Value out of range");
final switch (letter) {
case 'a':
putWord(cast(ushort) val);
break;
case 'b':
case 'l':
putByte(cast(ubyte) val);
break;
case 'h':
putByte(cast(ubyte) (val >> 8));
break;
}
}
void assemblyDtaInteger(char letter) {
if (readFunction() == "SIN") {
readWord();
int sinCenter = value;
readComma();
readWord();
int sinAmp = value;
readComma();
readKnownPositive();
int sinPeriod = value;
int sinMin = 0;
int sinMax = sinPeriod - 1;
switch (readChar()) {
case ')':
break;
case ',':
readUnsignedWord();
mustBeKnownInPass1();
sinMin = value;
readComma();
readUnsignedWord();
mustBeKnownInPass1();
sinMax = value;
if (readChar() != ')') {
illegalCharacter();
}
break;
default:
illegalCharacter();
}
while (sinMin <= sinMax) {
int val = sinCenter + cast(int) rint(sinAmp * sin(sinMin * 2 * PI / sinPeriod));
storeDtaNumber(val, letter);
sinMin++;
}
return;
}
readWord();
storeDtaNumber(value, letter);
}
bool realSign;
int realExponent;
long realMantissa;
void putReal() {
if (realMantissa == 0) {
putWord(0);
putWord(0);
putWord(0);
return;
}
while (realMantissa < 0x1000000000L) {
realMantissa <<= 4;
realExponent--;
}
if ((realExponent & 1) != 0) {
if (realMantissa & 0xf)
throw new AssemblyError("Out of precision");
realMantissa >>= 4;
}
realExponent = (realExponent + 0x89) >> 1;
if (realExponent < 64 - 49)
throw new AssemblyError("Out of precision");
if (realExponent > 64 + 49)
throw new AssemblyError("Number too big");
putByte(cast(ubyte) (realSign ? realExponent + 0x80 : realExponent));
putByte(cast(ubyte) (realMantissa >> 32));
putByte(cast(ubyte) (realMantissa >> 24));
putByte(cast(ubyte) (realMantissa >> 16));
putByte(cast(ubyte) (realMantissa >> 8));
putByte(cast(ubyte) realMantissa);
}
bool readSign() {
switch (readChar()) {
case '+':
return false;
case '-':
return true;
default:
column--;
return false;
}
}
void readExponent() {
bool sign = readSign();
char c = readChar();
if (c < '0' || c > '9')
illegalCharacter();
int e = c - '0';
c = readChar();
if (c >= '0' && c <= '9')
e = 10 * e + c - '0';
else
column--;
realExponent += sign ? -e : e;
putReal();
}
void readFraction() {
for (;;) {
char c = readChar();
if (c >= '0' && c <= '9') {
if (c != '0' && realMantissa >= 0x1000000000L)
throw new AssemblyError("Out of precision");
realMantissa <<= 4;
realMantissa += c - '0';
realExponent--;
continue;
}
if (c == 'E' || c == 'e') {
readExponent();
return;
}
column--;
putReal();
return;
}
}
void assemblyDtaReal() {
realSign = readSign();
realExponent = 0;
realMantissa = 0;
char c = readChar();
if (c == '.') {
readFraction();
return;
}
if (c < '0' || c > '9')
illegalCharacter();
do {
if (realMantissa < 0x1000000000L) {
realMantissa <<= 4;
realMantissa += c - '0';
} else {
if (c != '0')
throw new AssemblyError("Out of precision");
realExponent++;
}
c = readChar();
} while (c >= '0' && c <= '9');
switch (c) {
case '.':
readFraction();
break;
case 'E':
case 'e':
readExponent();
break;
default:
column--;
putReal();
break;
}
}
void assemblyDtaNumbers(char letter) {
if (eol() || line[column] != '(') {
column--;
assemblyDtaInteger('b');
return;
}
column++;
for (;;) {
final switch (letter) {
case 'a':
case 'b':
case 'h':
case 'l':
assemblyDtaInteger(letter);
break;
case 'r':
assemblyDtaReal();
break;
}
switch (readChar()) {
case ')':
return;
case ',':
break;
default:
illegalCharacter();
}
}
}
void assemblyDta() {
noOpcode();
readSpaces();
for (;;) {
switch (readChar()) {
case 'A':
case 'a':
assemblyDtaNumbers('a');
break;
case 'B':
case 'b':
assemblyDtaNumbers('b');
break;
case 'C':
case 'c':
ubyte[] s = readString();
if (s is null) {
column--;
assemblyDtaInteger('b');
break;
}
foreach (ubyte b; s) {
putByte(b);
}
break;
case 'D':
case 'd':
ubyte[] s = readString();
if (s is null) {
column--;
assemblyDtaInteger('b');
break;
}
foreach (ubyte b; s) {
final switch (b & 0x60) {
case 0x00:
putByte(cast(ubyte) (b + 0x40));
break;
case 0x20:
case 0x40:
putByte(cast(ubyte) (b - 0x20));
break;
case 0x60:
putByte(b);
break;
}
}
break;
case 'H':
case 'h':
assemblyDtaNumbers('h');
break;
case 'L':
case 'l':
assemblyDtaNumbers('l');
break;
case 'R':
case 'r':
assemblyDtaNumbers('r');
break;
default:
column--;
assemblyDtaInteger('b');
break;
}
if (eol() || line[column] != ',')
break;
column++;
}
}
void assemblyEqu() {
directive();
if (currentLabel is null)
throw new AssemblyError("Label name required");
currentLabel.value = 0;
readSpaces();
readValue();
currentLabel.value = value;
currentLabel.unknownInPass1 = unknownInPass1;
if (optionListing) {
listingLine[6] = '=';
int val = value;
listingLine[7] = ' ';
if (val < 0) {
listingLine[7] = '-';
val = -val;
}
listingColumn = 8;
if ((val & 0xffff0000) != 0)
listWord(cast(ushort) (val >> 16));
else {
while (listingColumn < 12)
listingLine[listingColumn++] = ' ';
}
listWord(cast(ushort) val);
}
}
void assemblyEnd() {
directive();
assert(!foundEnd);
foundEnd = true;
}
void assemblyIftEli() {
ifContexts[$ - 1].condition = true;
if (!inFalseCondition()) {
readSpaces();
readValue();
mustBeKnownInPass1();
if (value != 0)
ifContexts[$ - 1].aConditionMatched = true;
else
listLine();
ifContexts[$ - 1].condition = value != 0;
}
}
void checkMissingIft() {
if (ifContexts.length == 0)
throw new AssemblyError("Missing IFT");
}
void assemblyIft() {
directive();
ifContexts.length++;
assemblyIftEli();
}
void assemblyEliEls() {
directive();
checkMissingIft();
if (ifContexts[$ - 1].wasElse)
throw new AssemblyError("EIF expected");
}
void assemblyEli() {
assemblyEliEls();
if (ifContexts[$ - 1].aConditionMatched) {
ifContexts[$ - 1].condition = false;
return;
}
assemblyIftEli();
}
void assemblyEls() {
assemblyEliEls();
with (ifContexts[$ - 1]) {
if (condition && aConditionMatched)
listLine();
wasElse = true;
condition = !aConditionMatched;
}
}
void assemblyEif() {
directive();
checkMissingIft();
ifContexts.length--;
}
void assemblyErt() {
directive();
readSpaces();
readValue();
if (pass2 && value != 0)
throw new AssemblyError("User-defined error");
}
bool readOption() {
switch (readChar()) {
case '-':
return false;
case '+':
return true;
default:
illegalCharacter();
}
assert(0);
}
void assemblyOpt() {
directive();
readSpaces();
while (!eol()) {
switch (line[column++]) {
case 'F':
case 'f':
optionFill = readOption();
break;
case 'G':
case 'g':
option5200 = readOption();
break;
case 'H':
case 'h':
optionHeaders = readOption();
break;
case 'L':
case 'l':
optionListing = readOption() && !pass2;
break;
case 'O':
case 'o':
optionObject = readOption();
break;
default:
column--;
return;
}
}
}
void originWord(ushort value, char listingChar) {
objectWord(value);
listWord(value);
listingLine[listingColumn++] = listingChar;
}
void setOrigin(int addr, bool requestedHeader, bool requestedFFFF) {
origin = loadOrigin = addr;
if (requestedHeader || loadingOrigin < 0 || (addr != loadingOrigin && !optionFill)) {
blockIndex++;
if (!pass2) {
assert(blockIndex == blockEnds.length);
blockEnds ~= cast(ushort) (addr - 1);
}
if (pass2 && optionHeaders) {
if (addr - 1 == blockEnds[blockIndex]) {
if (requestedHeader)
throw new AssemblyError("Cannot generate an empty block");
return;
}
if (requestedFFFF || objectBytes == 0) {
assert(requestedHeader || addr != loadingOrigin);
originWord(0xffff, '>');
listingLine[listingColumn++] = ' ';
}
if (requestedHeader || addr != loadingOrigin) {
originWord(cast(ushort) addr, '-');
originWord(blockEnds[blockIndex], '>');
listingLine[listingColumn++] = ' ';
loadingOrigin = -1;
}
}
}
}
void checkHeadersOn() {
if (!optionHeaders)
throw new AssemblyError("Illegal when Atari file headers disabled");
}
void assemblyOrg() {
noRepeatSkipDirective();
readSpaces();
bool requestedFFFF = false;
bool requestedHeader = false;
if (column + 2 < line.length && line[column + 1] == ':') {
switch (line[column]) {
case 'F':
case 'f':
requestedFFFF = true;
goto case 'A';
case 'A':
case 'a':
checkHeadersOn();
column += 2;
requestedHeader = true;
break;
case 'R':
case 'r':
column += 2;
checkOriginDefined();
readUnsignedWord();
mustBeKnownInPass1();
origin = value;
return;
default:
break;
}
}
readUnsignedWord();
mustBeKnownInPass1();
setOrigin(value, requestedHeader, requestedFFFF);
}
void assemblyRunIni(ushort addr) {
noRepeatSkipDirective();
checkHeadersOn();
loadingOrigin = -1; // don't fill
setOrigin(addr, false, false);
readSpaces();
readUnsignedWord();
putWord(cast(ushort) (value));
loadingOrigin = -1; // don't fill
}
void assemblyIcl() {
directive();
string filename = readFilename();
checkNoExtraCharacters();
listLine();
includeLevel++;
assemblyFile(filename);
includeLevel--;
line = null;
}
void assemblyIns() {
string filename = readFilename();
int offset = 0;
int length = -1;
if (!eol() && line[column] == ',') {
column++;
readValue();
mustBeKnownInPass1();
offset = value;
if (!eol() && line[column] == ',') {
column++;
readKnownPositive();
length = value;
}
}
File stream = openInputFile(filename);
scope (exit) stream.close();
try {
stream.seek(offset, offset >= 0 ? SEEK_SET : SEEK_END);
} catch (Exception e) {
throw new AssemblyError("Error seeking file");
}
if (inOpcode)
length = 1;
while (length != 0) {
ubyte[1] buffer;
try {
if (stream.rawRead(buffer) == null) {
if (length > 0)
throw new AssemblyError("File is too short");
break;
}
} catch (Exception e) {
throw new AssemblyError("Error reading file");
}
putByte(buffer[0]);
if (length > 0) length--;
}
}
void assemblyInstruction(string instruction) {
if (!inOpcode && origin < 0 && currentLabel !is null && instruction != "EQU")
throw new AssemblyError("No ORG specified");
instructionBegin = true;
switch (instruction) {
case "ADC":
assemblyAccumulator(0x60, 0, 0);
break;
case "ADD":
assemblyAccumulator(0x60, 0x18, 0);
break;
case "AND":
assemblyAccumulator(0x20, 0, 0);
break;
case "ASL":
assemblyShift(0x00);
break;
case "BCC":
assemblyBranch(0x90);
break;
case "BCS":
assemblyBranch(0xb0);
break;
case "BEQ":
assemblyBranch(0xf0);
break;
case "BIT":
assemblyBit();
break;
case "BMI":
assemblyBranch(0x30);
break;
case "BNE":
assemblyBranch(0xd0);
break;
case "BPL":
assemblyBranch(0x10);
break;
case "BRK":
putByte(0x00);
break;
case "BVC":
assemblyBranch(0x50);
break;
case "BVS":
assemblyBranch(0x70);
break;
case "CLC":
putByte(0x18);
break;
case "CLD":
putByte(0xd8);
break;
case "CLI":
putByte(0x58);
break;
case "CLV":
putByte(0xb8);
break;
case "CMP":
assemblyAccumulator(0xc0, 0, 0);
break;
case "CPX":
assemblyCompareIndex(0xe0);
break;
case "CPY":
assemblyCompareIndex(0xc0);
break;
case "DEC":
assemblyShift(0xc0);
break;
case "DEX":
putByte(0xca);
break;
case "DEY":
putByte(0x88);
break;
case "DTA":
assemblyDta();
break;
case "EIF":
assemblyEif();
break;
case "ELI":
assemblyEli();
break;
case "ELS":
assemblyEls();
break;
case "END":
assemblyEnd();
break;
case "EOR":
assemblyAccumulator(0x40, 0, 0);
break;
case "EQU":
assemblyEqu();
break;
case "ERT":
assemblyErt();
break;
case "ICL":
assemblyIcl();
break;
case "IFT":
assemblyIft();
break;
case "INC":
assemblyShift(0xe0);
break;
case "INI":
assemblyRunIni(0x2e2);
break;
case "INS":
assemblyIns();
break;
case "INX":
putByte(0xe8);
break;
case "INY":
putByte(0xc8);
break;
case "INW":
assemblyInw();
break;
case "JCC":
assemblyConditionalJump(0xb0);
break;
case "JCS":
assemblyConditionalJump(0x90);
break;
case "JEQ":
assemblyConditionalJump(0xd0);
break;
case "JMI":
assemblyConditionalJump(0x10);
break;
case "JMP":
assemblyJmp();
break;
case "JNE":
assemblyConditionalJump(0xf0);
break;
case "JPL":
assemblyConditionalJump(0x30);
break;
case "JSR":
assemblyJsr();
break;
case "JVC":
assemblyConditionalJump(0x70);
break;
case "JVS":
assemblyConditionalJump(0x50);
break;
case "LDA":
assemblyAccumulator(0xa0, 0, 0);
break;
case "LDX":
assemblyLdx(0);
break;
case "LDY":
assemblyLdy(0);
break;
case "LSR":
assemblyShift(0x40);
break;
case "MVA":
assemblyMoveByte(&assemblyLda, &assemblySta);
break;
case "MVX":
assemblyMoveByte(&assemblyLdx, &assemblyStx);
break;
case "MVY":
assemblyMoveByte(&assemblyLdy, &assemblySty);
break;
case "MWA":
assemblyMoveWord(&assemblyLda, &assemblySta, 0, 0);
break;
case "MWX":
assemblyMoveWord(&assemblyLdx, &assemblyStx, 0xe8, 0xca);
break;
case "MWY":
assemblyMoveWord(&assemblyLdy, &assemblySty, 0xc8, 0x88);
break;
case "NOP":
putByte(0xea);
break;
case "OPT":
assemblyOpt();
break;
case "ORA":
assemblyAccumulator(0x00, 0, 0);
break;
case "ORG":
assemblyOrg();
break;
case "PHA":
putByte(0x48);
break;
case "PHP":
putByte(0x08);
break;
case "PLA":
putByte(0x68);
break;
case "PLP":
putByte(0x28);
break;
case "RCC":
assemblyRepeat(0x90);
break;
case "RCS":
assemblyRepeat(0xb0);
break;
case "REQ":
assemblyRepeat(0xf0);
break;
case "RMI":
assemblyRepeat(0x30);
break;
case "RNE":
assemblyRepeat(0xd0);
break;
case "ROL":
assemblyShift(0x20);
break;
case "ROR":
assemblyShift(0x60);
break;
case "RPL":
assemblyRepeat(0x10);
break;
case "RTI":
putByte(0x40);
break;
case "RTS":
putByte(0x60);
break;
case "RUN":
assemblyRunIni(0x2e0);
break;
case "RVC":
assemblyRepeat(0x50);
break;
case "RVS":
assemblyRepeat(0x70);
break;
case "SBC":
assemblyAccumulator(0xe0, 0, 0);
break;
case "SCC":
assemblySkip(0x90);
break;
case "SCS":
assemblySkip(0xb0);
break;
case "SEC":
putByte(0x38);
break;
case "SED":
putByte(0xf8);
break;
case "SEI":
putByte(0x78);
break;
case "SEQ":
assemblySkip(0xf0);
break;
case "SMI":
assemblySkip(0x30);
break;
case "SNE":
assemblySkip(0xd0);
break;
case "SPL":
assemblySkip(0x10);
break;
case "STA":
assemblyAccumulator(0x80, 0, 0);
break;
case "STX":
assemblyStx(0);
break;
case "STY":
assemblySty(0);
break;
case "SUB":
assemblyAccumulator(0xe0, 0x38, 0);
break;
case "SVC":
assemblySkip(0x50);
break;
case "SVS":
assemblySkip(0x70);
break;
case "TAX":
putByte(0xaa);
break;
case "TAY":
putByte(0xa8);
break;
case "TSX":
putByte(0xba);
break;
case "TXA":
putByte(0x8a);
break;
case "TXS":
putByte(0x9a);
break;
case "TYA":
putByte(0x98);
break;
default:
throw new AssemblyError("Illegal instruction");
}
skipping = false;
}
debug ubyte[] testInstruction(string l) {
objectBuffer.length = 0;
line = l;
column = 0;
assemblyInstruction(readInstruction());
write(line, " assembles to");
foreach (ubyte b; objectBuffer)
writef(" %02x", b);
writeln();
return objectBuffer;
}
unittest {
assert(testInstruction("nop") == cast(ubyte[]) x"ea");
assert(testInstruction("add (5,0)") == cast(ubyte[]) x"18a2006105");
assert(testInstruction("mwa #$abcd $1234") == cast(ubyte[]) x"a9cd8d3412a9ab8d3512");
assert(testInstruction("dta 5,d'Foo'*,a($4589)") == cast(ubyte[]) x"05a6efef8945");
assert(testInstruction("dta r(1,12,123,1234567890,12345678900000,.5,.03,000.1664534589,1e97)")
== cast(ubyte[]) x"400100000000 401200000000 410123000000 441234567890 461234567890 3f5000000000 3f0300000000 3f1664534589 701000000000");
}
void assemblyPair() {
assert(!inOpcode);
string instruction = readInstruction();
if (!eol() && line[column] == ':') {
pairing = true;
column++;
string instruction2 = readInstruction();
int savedColumn = column;
if (willSkip)
warning("Skipping only the first instruction");
assemblyInstruction(instruction);
checkNoExtraCharacters();
column = savedColumn;
wereManyInstructions = false;
assemblyInstruction(instruction2);
wereManyInstructions = true;
} else {
pairing = false;
assemblyInstruction(instruction);
wereManyInstructions = false;
}
}
void assemblyLine() {
debug {
writeln(line);
}
lineNo++;
totalLines++;
column = 0;
listingColumn = 6;
if (origin >= 0) {
listWord(cast(ushort) origin);
listingLine[listingColumn++] = ' ';
}
string label = readLabel();
currentLabel = null;
if (label !is null) {
if (!inFalseCondition()) {
if (!pass2) {
if (label in labelTable)
throw new AssemblyError("Label declared twice");
currentLabel = new Label(origin);
labelTable[label] = currentLabel;
} else {
assert(label in labelTable);
currentLabel = labelTable[label];
currentLabel.passed = true;
if (currentLabel.unused && getOption('u'))
warning("Unused label");
}
}
if (eol()) {
listCommentLine();
return;
}
readSpaces();
}
commentOrRep: for (;;) {
if (eol()) {
listCommentLine();
return;
}
switch (line[column]) {
case '\t':
case ' ':
column++;
continue;
case '*':
case ';':
case '|':
listCommentLine();
return;
case ':':
if (inFalseCondition()) {
listCommentLine();
return;
}
column++;
readUnsignedWord();
mustBeKnownInPass1();
int repeatLimit = value;
if (repeatLimit == 0) {
listCommentLine();
return;
}
readSpaces();
repeating = true;
if (repeatLimit == 1)
break;
if (willSkip)
warning("Skipping only the first instruction");
int savedColumn = column;
for (repeatCounter = 0; repeatCounter < repeatLimit; repeatCounter++) {
column = savedColumn;
assemblyPair();
}
checkNoExtraCharacters();
listLine();
wereManyInstructions = true;
return;
default:
repeating = false;
break commentOrRep;
}
}
if (inFalseCondition()) {
switch (readInstruction()) {
case "END":
assemblyEnd();
break;
case "IFT":
assemblyIft();
break;
case "ELI":
assemblyEli();
break;
case "ELS":
assemblyEls();
break;
case "EIF":
assemblyEif();
break;
default:
listCommentLine();
return;
}
checkNoExtraCharacters();
listCommentLine();
return;
}
assemblyPair();
checkNoExtraCharacters();
listLine();
}
void assemblyFile(string filename) {
filename = filename.defaultExtension("asx");
if (getOption('p'))
filename = absolutePath(filename);
File stream = openInputFile(filename);
scope (exit) stream.close();
string oldFilename = currentFilename;
int oldLineNo = lineNo;
currentFilename = filename;
lineNo = 0;
foundEnd = false;
line = "";
readChar: while (!foundEnd) {
ubyte[1] buffer;
if (stream.rawRead(buffer) == null)
break;
switch (buffer[0]) {
case '\r':
assemblyLine();
line = "";
if (stream.rawRead(buffer) == null)
break readChar;
if (buffer[0] != '\n')
line ~= cast(char) buffer[0];
break;
case '\n':
case '\x9b':
assemblyLine();
line = "";
break;
default:
line ~= cast(char) buffer[0];
break;
}
}
if (!foundEnd)
assemblyLine();
foundEnd = false;
currentFilename = oldFilename;
lineNo = oldLineNo;
}
void assemblyPass() {
origin = -1;
loadOrigin = -1;
loadingOrigin = -1;
blockIndex = -1;
optionFill = false;
option5200 = false;
optionHeaders = true;
optionListing = pass2;
optionObject = true;
willSkip = false;
skipping = false;
repeatOffset = 0;
wereManyInstructions = false;
currentFilename = "command line";
lineNo = 0;
foreach (definition; commandLineDefinitions) {
line = replaceFirst(definition, "=", " equ ");
assemblyLine();
}
line = null;
totalLines = 0;
assemblyFile(sourceFilename);
if (ifContexts.length != 0)
throw new AssemblyError("Missing EIF");
if (willSkip)
throw new AssemblyError("Can't skip over this");
}
pure bool isOption(string arg) {
if (arg.length < 2) return false;
if (arg[0] == '-') return true;
if (arg[0] != '/') return false;
if (arg.length == 2) return true;
if (arg[2] == ':') return true;
return false;
}
void setOption(char letter) {
assert(letter >= 'a' && letter <= 'z');
if (options[letter - 'a']) {
exitCode = 3;
return;
}
options[letter - 'a'] = true;
}
int main(string[] args) {
for (int i = 1; i < args.length; i++) {
string arg = args[i];
if (isOption(arg)) {
char letter = arg[1];
if (letter >= 'A' && letter <= 'Z')
letter += 'a' - 'A';
switch (letter) {
case 'c':
case 'i':
case 'm':
case 'p':
case 'q':
case 'u':
if (arg.length != 2)
exitCode = 3;
setOption(letter);
break;
case 'd':
string definition = null;
if (arg[0] == '/') {
if (arg.length >= 3 && arg[2] == ':')
definition = arg[3 .. $];
} else if (i + 1 < args.length && !isOption(args[i + 1]))
definition = args[++i];
if (definition is null || find(definition, '=').empty)
exitCode = 3;
commandLineDefinitions ~= definition;
break;
case 'l':
case 't':
case 'o':
setOption(letter);
string filename = null;
if (arg[0] == '/') {
if (arg.length >= 3 && arg[2] == ':')
filename = arg[3 .. $];
} else if (i + 1 < args.length && !isOption(args[i + 1]))
filename = args[++i];
if (filename is null && (letter == 'o' || arg.length != 2))
exitCode = 3;
optionParameters[letter - 'a'] = filename;
break;
default:
exitCode = 3;
break;
}
continue;
}
if (sourceFilename !is null)
exitCode = 3;
sourceFilename = arg;
}
if (sourceFilename is null)
exitCode = 3;
if (!getOption('q'))
writeln(TITLE);
if (exitCode != 0) {
write(
"Syntax: xasm source [options]\n"
"/c Include false conditionals in listing\n"
"/d:label=value Define a label\n"
"/i Don't list included files\n"
"/l[:filename] Generate listing\n"
"/o:filename Set object file name\n"
"/M Print Makefile rule\n"
"/p Print absolute paths in listing and error messages\n"
"/q Suppress info messages\n"
"/t[:filename] List label table\n"
"/u Warn of unused labels\n");
return exitCode;
}
try {
assemblyPass();
pass2 = true;
assemblyPass();
if (getOption('t') && labelTable.length > 0)
listLabelTable();
} catch (AssemblyError e) {
warning(e.msg, true);
exitCode = 2;
}
listingStream.close();
objectStream.close();
if (exitCode <= 1) {
if (!getOption('q')) {
writefln("%d lines of source assembled", totalLines);
if (objectBytes > 0)
writefln("%d bytes written to the object file", objectBytes);
}
if (getOption('m')) {
writef("%s:", makeTarget);
foreach (filename; makeSources)
writef(" %s", makeEscape(filename));
write("\n\txasm");
for (int i = 1; i < args.length; i++) {
string arg = args[i];
if (isOption(arg)) {
char letter = arg[1];
if (letter >= 'A' && letter <= 'Z')
letter += 'a' - 'A';
switch (letter) {
case 'm':
break;
case 'o':
if (arg[0] == '/')
writef(" /%c:$@", arg[1]);
else {
writef(" -%c $@", arg[1]);
++i;
}
break;
default:
if (arg[0] == '-'
&& (letter == 'd' || letter == 'l' || letter == 't')
&& i + 1 < args.length && !isOption(args[i + 1])) {
writef(" %s %s", arg, makeEscape(args[++i]));
}
else {
writef(" %s", makeEscape(arg));
}
break;
}
continue;
}
write(" $<");
}
writeln();
}
}
return exitCode;
}
| D |
/home/mailboxhead/Documents/Practice/rust/HelloWorld/target/rls/debug/deps/cc-9708bd74239a2b1c.rmeta: /home/mailboxhead/.cargo/registry/src/github.com-1ecc6299db9ec823/cc-1.0.38/src/lib.rs /home/mailboxhead/.cargo/registry/src/github.com-1ecc6299db9ec823/cc-1.0.38/src/windows_registry.rs
/home/mailboxhead/Documents/Practice/rust/HelloWorld/target/rls/debug/deps/libcc-9708bd74239a2b1c.rlib: /home/mailboxhead/.cargo/registry/src/github.com-1ecc6299db9ec823/cc-1.0.38/src/lib.rs /home/mailboxhead/.cargo/registry/src/github.com-1ecc6299db9ec823/cc-1.0.38/src/windows_registry.rs
/home/mailboxhead/Documents/Practice/rust/HelloWorld/target/rls/debug/deps/cc-9708bd74239a2b1c.d: /home/mailboxhead/.cargo/registry/src/github.com-1ecc6299db9ec823/cc-1.0.38/src/lib.rs /home/mailboxhead/.cargo/registry/src/github.com-1ecc6299db9ec823/cc-1.0.38/src/windows_registry.rs
/home/mailboxhead/.cargo/registry/src/github.com-1ecc6299db9ec823/cc-1.0.38/src/lib.rs:
/home/mailboxhead/.cargo/registry/src/github.com-1ecc6299db9ec823/cc-1.0.38/src/windows_registry.rs:
| D |
/Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/ObjectMapper.build/Objects-normal/x86_64/DateFormatterTransform.o : /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/FromJSON.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/ToJSON.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/Mappable.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/ImmutableMappable.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/TransformType.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/TransformOf.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/URLTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/DataTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/DateTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/ISO8601DateTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/EnumTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/NSDecimalNumberTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/DateFormatterTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/HexColorTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/CustomDateFormatTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/DictionaryTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/Map.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/Mapper.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/MapError.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/Operators.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/TransformOperators.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/EnumOperators.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/IntegerOperators.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/Target\ Support\ Files/ObjectMapper/ObjectMapper-umbrella.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/ObjectMapper.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
/Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/ObjectMapper.build/Objects-normal/x86_64/DateFormatterTransform~partial.swiftmodule : /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/FromJSON.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/ToJSON.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/Mappable.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/ImmutableMappable.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/TransformType.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/TransformOf.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/URLTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/DataTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/DateTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/ISO8601DateTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/EnumTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/NSDecimalNumberTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/DateFormatterTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/HexColorTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/CustomDateFormatTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/DictionaryTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/Map.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/Mapper.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/MapError.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/Operators.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/TransformOperators.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/EnumOperators.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/IntegerOperators.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/Target\ Support\ Files/ObjectMapper/ObjectMapper-umbrella.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/ObjectMapper.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
/Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/ObjectMapper.build/Objects-normal/x86_64/DateFormatterTransform~partial.swiftdoc : /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/FromJSON.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/ToJSON.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/Mappable.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/ImmutableMappable.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/TransformType.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/TransformOf.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/URLTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/DataTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/DateTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/ISO8601DateTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/EnumTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/NSDecimalNumberTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/DateFormatterTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/HexColorTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/CustomDateFormatTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/DictionaryTransform.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/Map.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/Mapper.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/MapError.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/Operators.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/TransformOperators.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/EnumOperators.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/ObjectMapper/Sources/IntegerOperators.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/Target\ Support\ Files/ObjectMapper/ObjectMapper-umbrella.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/ObjectMapper.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
| D |
PLONG PLAT ED95 KD LOMAGAGE HIMAGAGE SLAT SLONG RESULTNO DP DM WT ROCKTYPE
273 54 4 0 46 48 -33.5 151.300003 1769 6 6 0.982534559 intrusives, basalt
298.399994 61.7000008 5.9000001 0 58 62 -19.6000004 116.099998 141 3.29999995 8 0.712780352 sediments, sandstones, siltstones
310.200012 40.5999985 4.69999981 120.900002 56 59 -33.2000008 151.100006 241 8.60000038 8.60000038 0.976048249 extrusives
306.399994 74.1999969 4.30000019 0 52 55 -31.8999996 151.300003 8785 5.9000001 5.9000001 0.979871906 extrusives, basalts
333.200012 64.6999969 6.5999999 0 52 55 -31.8999996 151.300003 8786 10.3000002 11.6999998 0.953868769 extrusives, basalts
219.300003 -4.19999981 9.39999962 22.3999996 56 65 -10 121 7800 4.9000001 9.60000038 0.633082237 extrusives, basalts, andesites
292.5 65.5 1.60000002 262.700012 34 39 -38.7999992 143.399994 7097 2.5 2.5 0.797163631 sediments, red-brown clays
-65.400002 61.2999992 1.39999998 297 50 70 -31.6000004 145.600006 9339 2.20000005 2.20000005 0.747826958 sediments, saprolite
264.399994 75 15.6000004 0 2 65 -8.80000019 126.699997 1206 10.3999996 18 0.481617303 extrusives, intrusives
346 61 9 41.2000008 35 100 -31.3999996 138.600006 1170 13 15 0.60225049 sediments
333 45 9 16.5 35 100 -30.3999996 139.399994 1161 17 18 0.60225049 sediments, tillite
317 57 5 200 35 100 -30.5 139.300003 1165 9 10 0.657595119 sediments, redbeds
329 58 25 4.0999999 35 100 -30.2000008 139 1166 41.5999985 45.5999985 0.309291489 sediments, sandstone, tillite
223 26 13 14.8000002 35 100 -30.2999992 139.5 1157 26 26 0.528069163 extrusives
320 63 9 15.5 34 65 -38 145.5 1854 16 16 0.80473188 extrusives
314 70 6 132 48 50 -33.2999992 151.199997 1844 9 10 0.961558173 intrusives, basalt
317 63 14 16 23 56 -32.5 151 1840 20 20 0.626482891 extrusives, basalts
302.700012 66.8000031 6.80000019 35 34 65 -38 145.5 1819 10.8000002 12.1000004 0.838270532 extrusives
305 73 17 29 23 56 -42 147 1821 25 29 0.566091285 extrusives, basalts
305.600006 70.5 3.5999999 48.5 52 54 -32 151.399994 1892 5.30000019 5.30000019 0.985805384 extrusives
274 66 27.6000004 8.60000038 25 65 -41.2999992 145.899994 1873 39.7999992 46.9000015 0.392001791 intrusives, granite
321 64 6 27.5 25 65 -35.5999985 137.5 1874 10 11 0.761558173 sediments
269 40 30.996521 0 50 300 -32.5999985 151.5 1868 0 0 0.0791177871 extrusives, andesites
294 75 11 7 25 65 -41.0999985 146.100006 1871 16.2999992 18.8999996 0.682114083 sediments, sandstone
315 66 10.5 18 25 65 -41 145.5 1872 18.2000008 19.6000004 0.691352269 extrusives, sediments
298 58.7999992 2.4000001 0 35 65 -27 141.5 1972 3.79999995 3.79999995 0.893640785 sediments, weathered
314 66 5.5999999 161 48 50 -33.2999992 151.199997 1969 8.5 9.80000019 0.966341973 intrusives, basalt
297.200012 59.2000008 6 0 50 70 -30.5 151.5 1964 9.10000038 9.89999962 0.711558173 sediments, weathered
310.899994 68.5 5.19999981 0 40 60 -35 150 1927 5.19999981 5.19999981 0.970840415 extrusives, basalts
271 63 2.9000001 352 50 80 -34 151 1595 3.5 4.5 0.657408999 intrusives
278 66 2.0999999 333 48 50 -33.2999992 151.199997 1596 2.5999999 3.29999995 0.995123932 intrusives, basalt
318 37 6.80000019 41 56 59 -33.2000008 151.100006 1597 13.1999998 13.3999996 0.951173758 intrusives
| D |
/Users/abelfernandez/projects/vapor-server/Hello/.build/debug/Bits.build/HexEncoder.swift.o : /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Bytes+Base64.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+Convenience.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Data+BytesConvertible.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/String+BytesConvertible.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/UnsignedInteger+BytesConvertible.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/BytesConvertible.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+PatternMatching.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/UnsignedInteger+Shifting.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+Random.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Base64Encoder.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/HexEncoder.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Aliases.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/ByteSequence+Conversions.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+UTF8Numbers.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+ControlCharacters.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Operators.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+Alphabet.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Bytes+Percent.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Bytes+Hex.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/abelfernandez/projects/vapor-server/Hello/.build/debug/CHTTP.build/module.modulemap /Users/abelfernandez/projects/vapor-server/Hello/.build/debug/CSQLite.build/module.modulemap
/Users/abelfernandez/projects/vapor-server/Hello/.build/debug/Bits.build/HexEncoder~partial.swiftmodule : /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Bytes+Base64.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+Convenience.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Data+BytesConvertible.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/String+BytesConvertible.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/UnsignedInteger+BytesConvertible.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/BytesConvertible.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+PatternMatching.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/UnsignedInteger+Shifting.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+Random.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Base64Encoder.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/HexEncoder.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Aliases.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/ByteSequence+Conversions.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+UTF8Numbers.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+ControlCharacters.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Operators.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+Alphabet.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Bytes+Percent.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Bytes+Hex.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/abelfernandez/projects/vapor-server/Hello/.build/debug/CHTTP.build/module.modulemap /Users/abelfernandez/projects/vapor-server/Hello/.build/debug/CSQLite.build/module.modulemap
/Users/abelfernandez/projects/vapor-server/Hello/.build/debug/Bits.build/HexEncoder~partial.swiftdoc : /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Bytes+Base64.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+Convenience.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Data+BytesConvertible.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/String+BytesConvertible.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/UnsignedInteger+BytesConvertible.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/BytesConvertible.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+PatternMatching.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/UnsignedInteger+Shifting.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+Random.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Base64Encoder.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/HexEncoder.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Aliases.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/ByteSequence+Conversions.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+UTF8Numbers.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+ControlCharacters.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Operators.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Byte+Alphabet.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Bytes+Percent.swift /Users/abelfernandez/projects/vapor-server/Hello/.build/checkouts/bits.git-9196587591774126515/Sources/Bits/Bytes+Hex.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/abelfernandez/projects/vapor-server/Hello/.build/debug/CHTTP.build/module.modulemap /Users/abelfernandez/projects/vapor-server/Hello/.build/debug/CSQLite.build/module.modulemap
| D |
module android.java.android.icu.util.ValueIterator_d_interface;
import arsd.jni : IJavaObjectImplementation, JavaPackageId, JavaName, IJavaObject, ImportExportImpl, JavaInterfaceMembers;
static import arsd.jni;
import import0 = android.java.android.icu.util.ValueIterator_Element_d_interface;
import import1 = android.java.java.lang.Class_d_interface;
final class ValueIterator : IJavaObject {
static immutable string[] _d_canCastTo = [
];
@Import bool next(import0.ValueIterator_Element);
@Import void reset();
@Import void setRange(int, int);
@Import import1.Class getClass();
@Import int hashCode();
@Import bool equals(IJavaObject);
@Import @JavaName("toString") string toString_();
override string toString() { return arsd.jni.javaObjectToString(this); }
@Import void notify();
@Import void notifyAll();
@Import void wait(long);
@Import void wait(long, int);
@Import void wait();
mixin IJavaObjectImplementation!(false);
public static immutable string _javaParameterString = "Landroid/icu/util/ValueIterator;";
}
| D |
; Copyright (C) 2008 The Android Open Source Project
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
.source T_rem_int_2addr_5.java
.class public dot.junit.opcodes.rem_int_2addr.d.T_rem_int_2addr_5
.super java/lang/Object
.method public <init>()V
.limit regs 1
invoke-direct {v0}, java/lang/Object/<init>()V
return-void
.end method
.method public run(II)I
.limit regs 8
rem-int/2addr v5, v7
return v5
.end method
| D |
the state of being corrupt
lack of integrity or honesty (especially susceptibility to bribery
| D |
/*
RUN_OUTPUT:
---
Success
---
*/
import core.stdc.stdio;
/**************************************************/
void test1()
{
uint[char[]] a;
int i;
a["hello"] = 73;
a["world"] = 82;
foreach (uint u; a)
{
i++;
u++;
}
assert(i == 2);
assert(a["hello"] == 73);
assert(a["world"] == 82);
}
/**************************************************/
void test2()
{
uint[char[]] a;
int i;
a["hello"] = 73;
a["world"] = 82;
foreach (ref uint u; a)
{
i++;
u++;
}
assert(i == 2);
assert(a["hello"] == 74);
assert(a["world"] == 83);
}
/**************************************************/
void test3()
{
uint[char[]] a;
int i;
a["hello"] = 73;
a["world"] = 82;
foreach (ref uint u; a)
{
i++;
if (i)
break;
u++;
}
assert(i == 1);
assert(a["hello"] == 73);
assert(a["world"] == 82);
}
/**************************************************/
void test4()
{
uint[char[]] a;
int i;
a["hello"] = 73;
a["world"] = 82;
foreach (ref uint u; a)
{
i++;
if (i == 1)
continue;
u++;
}
assert(i == 2);
assert((a["hello"] == 73 && a["world"] == 83) ||
(a["hello"] == 74 && a["world"] == 82));
}
/**************************************************/
void test5()
{
uint[char[]] a;
int i;
a["hello"] = 73;
a["world"] = 82;
Loop:
while (1)
{
foreach (ref uint u; a)
{
i++;
if (i)
break Loop;
u++;
}
}
assert(i == 1);
assert(a["hello"] == 73);
assert(a["world"] == 82);
}
/**************************************************/
void test6()
{
uint[char[]] a;
int i;
a["hello"] = 73;
a["world"] = 82;
Loop:
while (1)
{
foreach (ref uint u; a)
{
i++;
if (i == 1)
continue Loop;
u++;
}
break;
}
assert(i == 3);
assert(a["hello"] == 74);
assert(a["world"] == 83);
}
/**************************************************/
void test7()
{
uint[char[]] a;
int i;
a["hello"] = 73;
a["world"] = 82;
foreach (ref uint u; a)
{
i++;
if (i)
goto Label;
u++;
}
assert(0);
Label:
assert(i == 1);
assert(a["hello"] == 73);
assert(a["world"] == 82);
}
/**************************************************/
void test8_x(uint[char[]] a)
{
int i;
foreach (ref uint u; a)
{
i++;
if (i)
return;
u++;
}
}
void test8()
{
uint[char[]] a;
int i;
a["hello"] = 73;
a["world"] = 82;
test8_x(a);
assert(i == 0);
assert(a["hello"] == 73);
assert(a["world"] == 82);
}
/**************************************************/
int test9_x(uint[char[]] a)
{
int i;
foreach (ref uint u; a)
{
i++;
if (i)
return 67;
u++;
}
return 23;
}
void test9()
{
uint[char[]] a;
int i;
a["hello"] = 73;
a["world"] = 82;
i = test9_x(a);
assert(i == 67);
assert(a["hello"] == 73);
assert(a["world"] == 82);
}
/**************************************************/
int test10_x(uint[char[]] a)
{
int i;
foreach (ref uint u; a)
{
i++;
if (i)
return i;
u++;
}
return 23;
}
void test10()
{
uint[char[]] a;
int i;
a["hello"] = 73;
a["world"] = 82;
i = test10_x(a);
assert(i == 1);
assert(a["hello"] == 73);
assert(a["world"] == 82);
}
/**************************************************/
int main()
{
test1();
test2();
test3();
test4();
test5();
test6();
test7();
test8();
test9();
test10();
printf("Success\n");
return 0;
}
| D |
// https://issues.dlang.org/show_bug.cgi?id=22202
/*
TEST_OUTPUT:
---
fail_compilation/fail22202.d(21): Error: function `fail22202.fun(SystemCopy _param_0)` is not callable using argument types `(SystemCopy)`
fail_compilation/fail22202.d(21): `inout ref inout(SystemCopy)(ref inout(SystemCopy) other)` copy constructor cannot be called from a `pure @safe nogc` context
---
*/
struct SystemCopy
{
this(ref inout SystemCopy other) inout {}
}
void fun(SystemCopy) @safe pure @nogc {}
void main() @safe pure @nogc
{
SystemCopy s;
fun(s);
}
| D |
/**
$(D std._parallelism) implements high-level primitives for SMP _parallelism.
These include parallel foreach, parallel reduce, parallel eager map, pipelining
and future/promise _parallelism. $(D std._parallelism) is recommended when the
same operation is to be executed in parallel on different data, or when a
function is to be executed in a background thread and its result returned to a
well-defined main thread. For communication between arbitrary threads, see
$(D std.concurrency).
$(D std._parallelism) is based on the concept of a $(D Task). A $(D Task) is an
object that represents the fundamental unit of work in this library and may be
executed in parallel with any other $(D Task). Using $(D Task)
directly allows programming with a future/promise paradigm. All other
supported _parallelism paradigms (parallel foreach, map, reduce, pipelining)
represent an additional level of abstraction over $(D Task). They
automatically create one or more $(D Task) objects, or closely related types
that are conceptually identical but not part of the public API.
After creation, a $(D Task) may be executed in a new thread, or submitted
to a $(D TaskPool) for execution. A $(D TaskPool) encapsulates a task queue
and its worker threads. Its purpose is to efficiently map a large
number of $(D Task)s onto a smaller number of threads. A task queue is a
FIFO queue of $(D Task) objects that have been submitted to the
$(D TaskPool) and are awaiting execution. A worker thread is a thread that
is associated with exactly one task queue. It executes the $(D Task) at the
front of its queue when the queue has work available, or sleeps when
no work is available. Each task queue is associated with zero or
more worker threads. If the result of a $(D Task) is needed before execution
by a worker thread has begun, the $(D Task) can be removed from the task queue
and executed immediately in the thread where the result is needed.
Warning: Unless marked as $(D @trusted) or $(D @safe), artifacts in
this module allow implicit data sharing between threads and cannot
guarantee that client code is free from low level data races.
Synopsis:
---
import std.algorithm, std.parallelism, std.range;
void main() {
// Parallel reduce can be combined with
// std.algorithm.map to interesting effect.
// The following example (thanks to Russel Winder)
// calculates pi by quadrature using
// std.algorithm.map and TaskPool.reduce.
// getTerm is evaluated in parallel as needed by
// TaskPool.reduce.
//
// Timings on an Athlon 64 X2 dual core machine:
//
// TaskPool.reduce: 12.170 s
// std.algorithm.reduce: 24.065 s
immutable n = 1_000_000_000;
immutable delta = 1.0 / n;
real getTerm(int i)
{
immutable x = ( i - 0.5 ) * delta;
return delta / ( 1.0 + x * x ) ;
}
immutable pi = 4.0 * taskPool.reduce!"a + b"(
std.algorithm.map!getTerm(iota(n))
);
}
---
Source: $(PHOBOSSRC std/_parallelism.d)
Author: David Simcha
Copyright: Copyright (c) 2009-2011, David Simcha.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0)
*/
module std.parallelism;
import core.atomic;
import core.cpuid;
import core.exception;
import core.memory;
import core.sync.condition;
import core.thread;
import std.algorithm;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.range;
import std.traits;
import std.typecons;
import std.typetuple;
version(OSX)
{
version = useSysctlbyname;
}
else version(FreeBSD)
{
version = useSysctlbyname;
}
version(Windows)
{
// BUGS: Only works on Windows 2000 and above.
import core.sys.windows.windows;
struct SYSTEM_INFO
{
union
{
DWORD dwOemId;
struct
{
WORD wProcessorArchitecture;
WORD wReserved;
};
};
DWORD dwPageSize;
LPVOID lpMinimumApplicationAddress;
LPVOID lpMaximumApplicationAddress;
LPVOID dwActiveProcessorMask;
DWORD dwNumberOfProcessors;
DWORD dwProcessorType;
DWORD dwAllocationGranularity;
WORD wProcessorLevel;
WORD wProcessorRevision;
}
private extern(Windows) void GetSystemInfo(void*);
shared static this()
{
SYSTEM_INFO si;
GetSystemInfo(&si);
totalCPUs = max(1, cast(uint) si.dwNumberOfProcessors);
}
}
else version(linux)
{
import core.sys.posix.unistd;
shared static this()
{
totalCPUs = cast(uint) sysconf(_SC_NPROCESSORS_ONLN );
}
}
else version(useSysctlbyname)
{
extern(C) int sysctlbyname(
const char *, void *, size_t *, void *, size_t
);
shared static this()
{
version(OSX)
{
auto nameStr = "machdep.cpu.core_count\0".ptr;
}
else version(FreeBSD)
{
auto nameStr = "hw.ncpu\0".ptr;
}
uint ans;
size_t len = uint.sizeof;
sysctlbyname(nameStr, &ans, &len, null, 0);
totalCPUs = ans;
}
}
else
{
static assert(0, "Don't know how to get N CPUs on this OS.");
}
/* Atomics code. These forward to core.atomic, but are written like this
for two reasons:
1. They used to actually contain ASM code and I don' want to have to change
to directly calling core.atomic in a zillion different places.
2. core.atomic has some misc. issues that make my use cases difficult
without wrapping it. If I didn't wrap it, casts would be required
basically everywhere.
*/
private void atomicSetUbyte(ref ubyte stuff, ubyte newVal)
{
//core.atomic.cas(cast(shared) &stuff, stuff, newVal);
atomicStore(*(cast(shared) &stuff), newVal);
}
private ubyte atomicReadUbyte(ref ubyte val)
{
return atomicLoad(*(cast(shared) &val));
}
// This gets rid of the need for a lot of annoying casts in other parts of the
// code, when enums are involved.
private bool atomicCasUbyte(ref ubyte stuff, ubyte testVal, ubyte newVal)
{
return core.atomic.cas(cast(shared) &stuff, testVal, newVal);
}
/*--------------------- Generic helper functions, etc.------------------------*/
private template MapType(R, functions...)
{
static if(functions.length == 0)
{
alias typeof(unaryFun!(functions[0])(ElementType!R.init)) MapType;
}
else
{
alias typeof(adjoin!(staticMap!(unaryFun, functions))
(ElementType!R.init)) MapType;
}
}
private template ReduceType(alias fun, R, E)
{
alias typeof(binaryFun!fun(E.init, ElementType!R.init)) ReduceType;
}
private template noUnsharedAliasing(T)
{
enum bool noUnsharedAliasing = !hasUnsharedAliasing!T;
}
// This template tests whether a function may be executed in parallel from
// @safe code via Task.executeInNewThread(). There is an additional
// requirement for executing it via a TaskPool. (See isSafeReturn).
private template isSafeTask(F)
{
enum bool isSafeTask =
(functionAttributes!F & (FunctionAttribute.safe | FunctionAttribute.trusted)) != 0 &&
(functionAttributes!F & FunctionAttribute.ref_) == 0 &&
(isFunctionPointer!F || !hasUnsharedAliasing!F) &&
allSatisfy!(noUnsharedAliasing, ParameterTypeTuple!F);
}
unittest
{
alias void function() @safe F1;
alias void function() F2;
alias void function(uint, string) @trusted F3;
alias void function(uint, char[]) F4;
static assert( isSafeTask!F1);
static assert(!isSafeTask!F2);
static assert( isSafeTask!F3);
static assert(!isSafeTask!F4);
alias uint[] function(uint, string) pure @trusted F5;
static assert( isSafeTask!F5);
}
// This function decides whether Tasks that meet all of the other requirements
// for being executed from @safe code can be executed on a TaskPool.
// When executing via TaskPool, it's theoretically possible
// to return a value that is also pointed to by a worker thread's thread local
// storage. When executing from executeInNewThread(), the thread that executed
// the Task is terminated by the time the return value is visible in the calling
// thread, so this is a non-issue. It's also a non-issue for pure functions
// since they can't read global state.
private template isSafeReturn(T)
{
static if(!hasUnsharedAliasing!(T.ReturnType))
{
enum isSafeReturn = true;
}
else static if(T.isPure)
{
enum isSafeReturn = true;
}
else
{
enum isSafeReturn = false;
}
}
private template randAssignable(R)
{
enum randAssignable = isRandomAccessRange!R && hasAssignableElements!R;
}
// Work around syntactic ambiguity w.r.t. address of function return vals.
private T* addressOf(T)(ref T val) pure nothrow
{
return &val;
}
private enum TaskStatus : ubyte
{
notStarted,
inProgress,
done
}
private template AliasReturn(alias fun, T...)
{
alias typeof({ T args; return fun(args); }) AliasReturn;
}
// Should be private, but std.algorithm.reduce is used in the zero-thread case
// and won't work w/ private.
template reduceAdjoin(functions...)
{
static if(functions.length == 1)
{
alias binaryFun!(functions[0]) reduceAdjoin;
}
else
{
T reduceAdjoin(T, U)(T lhs, U rhs)
{
alias staticMap!(binaryFun, functions) funs;
foreach(i, Unused; typeof(lhs.expand))
{
lhs.expand[i] = funs[i](lhs.expand[i], rhs);
}
return lhs;
}
}
}
private template reduceFinish(functions...)
{
static if(functions.length == 1)
{
alias binaryFun!(functions[0]) reduceFinish;
}
else
{
T reduceFinish(T)(T lhs, T rhs)
{
alias staticMap!(binaryFun, functions) funs;
foreach(i, Unused; typeof(lhs.expand))
{
lhs.expand[i] = funs[i](lhs.expand[i], rhs.expand[i]);
}
return lhs;
}
}
}
private template isAssignable(T)
{
enum isAssignable = is(typeof({
T a;
T b;
a = b;
}));
}
private template isRoundRobin(R : RoundRobinBuffer!(C1, C2), C1, C2)
{
enum isRoundRobin = true;
}
private template isRoundRobin(T)
{
enum isRoundRobin = false;
}
unittest
{
static assert( isRoundRobin!(RoundRobinBuffer!(void delegate(char[]), bool delegate())));
static assert(!isRoundRobin!(uint));
}
// This is the base "class" for all of the other tasks. Using C-style
// polymorphism to allow more direct control over memory allocation, etc.
private struct AbstractTask
{
AbstractTask* prev;
AbstractTask* next;
// Pointer to a function that executes this task.
void function(void*) runTask;
Throwable exception;
ubyte taskStatus = TaskStatus.notStarted;
bool done() @property
{
if(atomicReadUbyte(taskStatus) == TaskStatus.done)
{
if(exception)
{
throw exception;
}
return true;
}
return false;
}
void job()
{
runTask(&this);
}
}
/**
$(D Task) represents the fundamental unit of work. A $(D Task) may be
executed in parallel with any other $(D Task). Using this struct directly
allows future/promise _parallelism. In this paradigm, a function (or delegate
or other callable) is executed in a thread other than the one it was called
from. The calling thread does not block while the function is being executed.
A call to $(D workForce), $(D yieldForce), or $(D spinForce) is used to
ensure that the $(D Task) has finished executing and to obtain the return
value, if any. These functions and $(D done) also act as full memory barriers,
meaning that any memory writes made in the thread that executed the $(D Task)
are guaranteed to be visible in the calling thread after one of these functions
returns.
The $(XREF parallelism, task) and $(XREF parallelism, scopedTask) functions can
be used to create an instance of this struct. See $(D task) for usage examples.
Function results are returned from $(D yieldForce), $(D spinForce) and
$(D workForce) by ref. If $(D fun) returns by ref, the reference will point
to the returned reference of $(D fun). Otherwise it will point to a
field in this struct.
Copying of this struct is disabled, since it would provide no useful semantics.
If you want to pass this struct around, you should do so by reference or
pointer.
Bugs: Changes to $(D ref) and $(D out) arguments are not propagated to the
call site, only to $(D args) in this struct.
*/
struct Task(alias fun, Args...)
{
AbstractTask base = {runTask : &impl};
alias base this;
private @property AbstractTask* basePtr()
{
return &base;
}
private static void impl(void* myTask)
{
Task* myCastedTask = cast(typeof(this)*) myTask;
static if(is(ReturnType == void))
{
fun(myCastedTask._args);
}
else static if(is(typeof(addressOf(fun(myCastedTask._args)))))
{
myCastedTask.returnVal = addressOf(fun(myCastedTask._args));
}
else
{
myCastedTask.returnVal = fun(myCastedTask._args);
}
}
private TaskPool pool;
private bool isScoped; // True if created with scopedTask.
Args _args;
/**
The arguments the function was called with. Changes to $(D out) and
$(D ref) arguments will be visible here.
*/
static if(__traits(isSame, fun, run))
{
alias _args[1..$] args;
}
else
{
alias _args args;
}
// The purpose of this code is to decide whether functions whose
// return values have unshared aliasing can be executed via
// TaskPool from @safe code. See isSafeReturn.
static if(__traits(isSame, fun, run))
{
static if(isFunctionPointer!(_args[0]))
{
private enum bool isPure =
functionAttributes!(Args[0]) & FunctionAttribute.pure_;
}
else
{
// BUG: Should check this for delegates too, but std.traits
// apparently doesn't allow this. isPure is irrelevant
// for delegates, at least for now since shared delegates
// don't work.
private enum bool isPure = false;
}
}
else
{
// We already know that we can't execute aliases in @safe code, so
// just put a dummy value here.
private enum bool isPure = false;
}
/**
The return type of the function called by this $(D Task). This can be
$(D void).
*/
alias typeof(fun(_args)) ReturnType;
static if(!is(ReturnType == void))
{
static if(is(typeof(&fun(_args))))
{
// Ref return.
ReturnType* returnVal;
ref ReturnType fixRef(ReturnType* val)
{
return *val;
}
}
else
{
ReturnType returnVal;
ref ReturnType fixRef(ref ReturnType val)
{
return val;
}
}
}
private void enforcePool()
{
enforce(this.pool !is null, "Job not submitted yet.");
}
private this(Args args)
{
static if(args.length > 0)
{
_args = args;
}
}
// Work around DMD bug 6588, allow immutable elements.
static if(allSatisfy!(isAssignable, Args))
{
typeof(this) opAssign(typeof(this) rhs)
{
foreach(i, Type; typeof(this.tupleof))
{
this.tupleof[i] = rhs.tupleof[i];
}
return this;
}
}
else
{
@disable typeof(this) opAssign(typeof(this) rhs)
{
assert(0);
}
}
/**
If the $(D Task) isn't started yet, execute it in the current thread.
If it's done, return its return value, if any. If it's in progress,
busy spin until it's done, then return the return value. If it threw
an exception, rethrow that exception.
This function should be used when you expect the result of the
$(D Task) to be available on a timescale shorter than that of an OS
context switch.
*/
@property ref ReturnType spinForce() @trusted
{
enforcePool();
this.pool.tryDeleteExecute(basePtr);
while(atomicReadUbyte(this.taskStatus) != TaskStatus.done) {}
if(exception)
{
throw exception;
}
static if(!is(ReturnType == void))
{
return fixRef(this.returnVal);
}
}
/**
If the $(D Task) isn't started yet, execute it in the current thread.
If it's done, return its return value, if any. If it's in progress,
wait on a condition variable. If it threw an exception, rethrow that
exception.
This function should be used for expensive functions, as waiting on a
condition variable introduces latency, but avoids wasted CPU cycles.
*/
@property ref ReturnType yieldForce() @trusted
{
enforcePool();
this.pool.tryDeleteExecute(basePtr);
if(done)
{
static if(is(ReturnType == void))
{
return;
}
else
{
return fixRef(this.returnVal);
}
}
pool.waiterLock();
scope(exit) pool.waiterUnlock();
while(atomicReadUbyte(this.taskStatus) != TaskStatus.done)
{
pool.waitUntilCompletion();
}
if(exception)
{
throw exception;
}
static if(!is(ReturnType == void))
{
return fixRef(this.returnVal);
}
}
/**
If this $(D Task) was not started yet, execute it in the current
thread. If it is finished, return its result. If it is in progress,
execute any other $(D Task) from the $(D TaskPool) instance that
this $(D Task) was submitted to until this one
is finished. If it threw an exception, rethrow that exception.
If no other tasks are available or this $(D Task) was executed using
$(D executeInNewThread), wait on a condition variable.
*/
@property ref ReturnType workForce() @trusted
{
enforcePool();
this.pool.tryDeleteExecute(basePtr);
while(true)
{
if(done) // done() implicitly checks for exceptions.
{
static if(is(ReturnType == void))
{
return;
}
else
{
return fixRef(this.returnVal);
}
}
AbstractTask* job;
{
// Locking explicitly and calling popNoSync() because
// pop() waits on a condition variable if there are no Tasks
// in the queue.
pool.queueLock();
scope(exit) pool.queueUnlock();
job = pool.popNoSync();
}
if(job !is null)
{
version(verboseUnittest)
{
stderr.writeln("Doing workForce work.");
}
pool.doJob(job);
if(done)
{
static if(is(ReturnType == void))
{
return;
}
else
{
return fixRef(this.returnVal);
}
}
}
else
{
version(verboseUnittest)
{
stderr.writeln("Yield from workForce.");
}
return yieldForce;
}
}
}
/**
Returns $(D true) if the $(D Task) is finished executing.
Throws: Rethrows any exception thrown during the execution of the
$(D Task).
*/
@property bool done() @trusted
{
// Explicitly forwarded for documentation purposes.
return base.done;
}
/**
Create a new thread for executing this $(D Task), execute it in the
newly created thread, then terminate the thread. This can be used for
future/promise parallelism. An explicit priority may be given
to the $(D Task). If one is provided, its value is forwarded to
$(D core.thread.Thread.priority). See $(XREF parallelism, task) for
usage example.
*/
void executeInNewThread() @trusted
{
pool = new TaskPool(basePtr);
}
/// Ditto
void executeInNewThread(int priority) @trusted
{
pool = new TaskPool(basePtr, priority);
}
@safe ~this()
{
if(isScoped && pool !is null && taskStatus != TaskStatus.done)
{
yieldForce;
}
}
// When this is uncommented, it somehow gets called on returning from
// scopedTask even though the struct shouldn't be getting copied.
//@disable this(this) {}
}
// Calls $(D fpOrDelegate) with $(D args). This is an
// adapter that makes $(D Task) work with delegates, function pointers and
// functors instead of just aliases.
ReturnType!F run(F, Args...)(F fpOrDelegate, ref Args args)
{
return fpOrDelegate(args);
}
/**
Creates a $(D Task) on the GC heap that calls an alias. This may be executed
via $(D Task.executeInNewThread) or by submitting to a
$(XREF parallelism, TaskPool). A globally accessible instance of
$(D TaskPool) is provided by $(XREF parallelism, taskPool).
Returns: A pointer to the $(D Task).
Examples:
---
// Read two files into memory at the same time.
import std.file;
void main()
{
// Create and execute a Task for reading
// foo.txt.
auto file1Task = task!read("foo.txt");
file1Task.executeInNewThread();
// Read bar.txt in parallel.
auto file2Data = read("bar.txt");
// Get the results of reading foo.txt.
auto file1Data = file1Task.yieldForce;
}
---
---
// Sorts an array using a parallel quick sort algorithm.
// The first partition is done serially. Both recursion
// branches are then executed in parallel.
//
// Timings for sorting an array of 1,000,000 doubles on
// an Athlon 64 X2 dual core machine:
//
// This implementation: 176 milliseconds.
// Equivalent serial implementation: 280 milliseconds
void parallelSort(T)(T[] data)
{
// Sort small subarrays serially.
if(data.length < 100)
{
std.algorithm.sort(data);
return;
}
// Partition the array.
swap(data[$ / 2], data[$ - 1]);
auto pivot = data[$ - 1];
bool lessThanPivot(T elem) { return elem < pivot; }
auto greaterEqual = partition!lessThanPivot(data[0..$ - 1]);
swap(data[$ - greaterEqual.length - 1], data[$ - 1]);
auto less = data[0..$ - greaterEqual.length - 1];
greaterEqual = data[$ - greaterEqual.length..$];
// Execute both recursion branches in parallel.
auto recurseTask = task!parallelSort(greaterEqual);
taskPool.put(recurseTask);
parallelSort(less);
recurseTask.yieldForce;
}
---
*/
auto task(alias fun, Args...)(Args args)
{
return new Task!(fun, Args)(args);
}
/**
Creates a $(D Task) on the GC heap that calls a function pointer, delegate, or
class/struct with overloaded opCall.
Examples:
---
// Read two files in at the same time again,
// but this time use a function pointer instead
// of an alias to represent std.file.read.
import std.file;
void main()
{
// Create and execute a Task for reading
// foo.txt.
auto file1Task = task(&read, "foo.txt");
file1Task.executeInNewThread();
// Read bar.txt in parallel.
auto file2Data = read("bar.txt");
// Get the results of reading foo.txt.
auto file1Data = file1Task.yieldForce;
}
---
Notes: This function takes a non-scope delegate, meaning it can be
used with closures. If you can't allocate a closure due to objects
on the stack that have scoped destruction, see $(D scopedTask), which
takes a scope delegate.
*/
auto task(F, Args...)(F delegateOrFp, Args args)
if(is(typeof(delegateOrFp(args))) && !isSafeTask!F)
{
return new Task!(run, F, Args)(delegateOrFp, args);
}
/**
Version of $(D task) usable from $(D @safe) code. Usage mechanics are
identical to the non-@safe case, but safety introduces some restrictions:
1. $(D fun) must be @safe or @trusted.
2. $(D F) must not have any unshared aliasing as defined by
$(XREF traits, hasUnsharedAliasing). This means it
may not be an unshared delegate or a non-shared class or struct
with overloaded $(D opCall). This also precludes accepting template
alias parameters.
3. $(D Args) must not have unshared aliasing.
4. $(D fun) must not return by reference.
5. The return type must not have unshared aliasing unless $(D fun) is
$(D pure) or the $(D Task) is executed via $(D executeInNewThread) instead
of using a $(D TaskPool).
*/
@trusted auto task(F, Args...)(F fun, Args args)
if(is(typeof(fun(args))) && isSafeTask!F)
{
return new Task!(run, F, Args)(fun, args);
}
/**
These functions allow the creation of $(D Task) objects on the stack rather
than the GC heap. The lifetime of a $(D Task) created by $(D scopedTask)
cannot exceed the lifetime of the scope it was created in.
$(D scopedTask) might be preferred over $(D task):
1. When a $(D Task) that calls a delegate is being created and a closure
cannot be allocated due to objects on the stack that have scoped
destruction. The delegate overload of $(D scopedTask) takes a $(D scope)
delegate.
2. As a micro-optimization, to avoid the heap allocation associated with
$(D task) or with the creation of a closure.
Usage is otherwise identical to $(D task).
Notes: $(D Task) objects created using $(D scopedTask) will automatically
call $(D Task.yieldForce) in their destructor if necessary to ensure
the $(D Task) is complete before the stack frame they reside on is destroyed.
*/
auto scopedTask(alias fun, Args...)(Args args)
{
auto ret = Task!(fun, Args)(args);
ret.isScoped = true;
return ret;
}
/// Ditto
auto scopedTask(F, Args...)(scope F delegateOrFp, Args args)
if(is(typeof(delegateOrFp(args))) && !isSafeTask!F)
{
auto ret = Task!(run, F, Args)(delegateOrFp, args);
ret.isScoped = true;
return ret;
}
/// Ditto
@trusted auto scopedTask(F, Args...)(F fun, Args args)
if(is(typeof(fun(args))) && isSafeTask!F)
{
auto ret = Task!(run, F, Args)(fun, args);
ret.isScoped = true;
return ret;
}
/**
The total number of CPU cores available on the current machine, as reported by
the operating system.
*/
immutable uint totalCPUs;
/*
This class serves two purposes:
1. It distinguishes std.parallelism threads from other threads so that
the std.parallelism daemon threads can be terminated.
2. It adds a reference to the pool that the thread is a member of,
which is also necessary to allow the daemon threads to be properly
terminated.
*/
private final class ParallelismThread : Thread
{
this(void delegate() dg)
{
super(dg);
}
TaskPool pool;
}
// Kill daemon threads.
shared static ~this()
{
auto allThreads = Thread.getAll();
foreach(thread; allThreads)
{
auto pthread = cast(ParallelismThread) thread;
if(pthread is null) continue;
auto pool = pthread.pool;
if(!pool.isDaemon) continue;
pool.stop();
pthread.join();
}
}
/**
This class encapsulates a task queue and a set of worker threads. Its purpose
is to efficiently map a large number of $(D Task)s onto a smaller number of
threads. A task queue is a FIFO queue of $(D Task) objects that have been
submitted to the $(D TaskPool) and are awaiting execution. A worker thread is a
thread that executes the $(D Task) at the front of the queue when one is
available and sleeps when the queue is empty.
This class should usually be used via the global instantiation
available via the $(XREF parallelism, taskPool) property.
Occasionally it is useful to explicitly instantiate a $(D TaskPool):
1. When you want $(D TaskPool) instances with multiple priorities, for example
a low priority pool and a high priority pool.
2. When the threads in the global task pool are waiting on a synchronization
primitive (for example a mutex), and you want to parallelize the code that
needs to run before these threads can be resumed.
*/
final class TaskPool
{
private:
// A pool can either be a regular pool or a single-task pool. A
// single-task pool is a dummy pool that's fired up for
// Task.executeInNewThread().
bool isSingleTask;
ParallelismThread[] pool;
Thread singleTaskThread;
AbstractTask* head;
AbstractTask* tail;
PoolState status = PoolState.running;
Condition workerCondition;
Condition waiterCondition;
Mutex queueMutex;
Mutex waiterMutex; // For waiterCondition
// The instanceStartIndex of the next instance that will be created.
__gshared static size_t nextInstanceIndex = 1;
// The index of the current thread.
static size_t threadIndex;
// The index of the first thread in this instance.
immutable size_t instanceStartIndex;
// The index that the next thread to be initialized in this pool will have.
size_t nextThreadIndex;
enum PoolState : ubyte
{
running,
finishing,
stopNow
}
void doJob(AbstractTask* job)
{
assert(job.taskStatus == TaskStatus.inProgress);
assert(job.next is null);
assert(job.prev is null);
scope(exit)
{
if(!isSingleTask)
{
waiterLock();
scope(exit) waiterUnlock();
notifyWaiters();
}
}
try
{
job.job();
}
catch(Throwable e)
{
job.exception = e;
}
atomicSetUbyte(job.taskStatus, TaskStatus.done);
}
// This function is used for dummy pools created by Task.executeInNewThread().
void doSingleTask()
{
// No synchronization. Pool is guaranteed to only have one thread,
// and the queue is submitted to before this thread is created.
assert(head);
auto t = head;
t.next = t.prev = head = null;
doJob(t);
}
// This function performs initialization for each thread that affects
// thread local storage and therefore must be done from within the
// worker thread. It then calls executeWorkLoop().
void startWorkLoop()
{
// Initialize thread index.
{
queueLock();
scope(exit) queueUnlock();
threadIndex = nextThreadIndex;
nextThreadIndex++;
}
executeWorkLoop();
}
// This is the main work loop that worker threads spend their time in
// until they terminate. It's also entered by non-worker threads when
// finish() is called with the blocking variable set to true.
void executeWorkLoop()
{
while(atomicReadUbyte(status) != PoolState.stopNow)
{
AbstractTask* task = pop();
if (task is null)
{
if(atomicReadUbyte(status) == PoolState.finishing)
{
atomicSetUbyte(status, PoolState.stopNow);
return;
}
}
else
{
doJob(task);
}
}
}
// Pop a task off the queue.
AbstractTask* pop()
{
queueLock();
scope(exit) queueUnlock();
auto ret = popNoSync();
while(ret is null && status == PoolState.running)
{
wait();
ret = popNoSync();
}
return ret;
}
AbstractTask* popNoSync()
out(returned)
{
/* If task.prev and task.next aren't null, then another thread
* can try to delete this task from the pool after it's
* alreadly been deleted/popped.
*/
if(returned !is null)
{
assert(returned.next is null);
assert(returned.prev is null);
}
}
body
{
if(isSingleTask) return null;
AbstractTask* returned = head;
if (head !is null)
{
head = head.next;
returned.prev = null;
returned.next = null;
returned.taskStatus = TaskStatus.inProgress;
}
if(head !is null)
{
head.prev = null;
}
return returned;
}
// Push a task onto the queue.
void abstractPut(AbstractTask* task)
{
queueLock();
scope(exit) queueUnlock();
abstractPutNoSync(task);
}
void abstractPutNoSync(AbstractTask* task)
in
{
assert(task);
}
out
{
assert(tail.prev !is tail);
assert(tail.next is null, text(tail.prev, '\t', tail.next));
if(tail.prev !is null)
{
assert(tail.prev.next is tail, text(tail.prev, '\t', tail.next));
}
}
body
{
// Not using enforce() to save on function call overhead since this
// is a performance critical function.
if(status != PoolState.running)
{
throw new Error(
"Cannot submit a new task to a pool after calling " ~
"finish() or stop()."
);
}
task.next = null;
if (head is null) //Queue is empty.
{
head = task;
tail = task;
tail.prev = null;
}
else {
assert(tail);
task.prev = tail;
tail.next = task;
tail = task;
}
notify();
}
void abstractPutGroupNoSync(AbstractTask* h, AbstractTask* t)
{
if(status != PoolState.running)
{
throw new Error(
"Cannot submit a new task to a pool after calling " ~
"finish() or stop()."
);
}
if(head is null)
{
head = h;
tail = t;
}
else
{
h.prev = tail;
tail.next = h;
tail = t;
}
notifyAll();
}
void tryDeleteExecute(AbstractTask* toExecute)
{
if(isSingleTask) return;
if( !deleteItem(toExecute) )
{
return;
}
try
{
toExecute.job();
}
catch(Exception e)
{
toExecute.exception = e;
}
atomicSetUbyte(toExecute.taskStatus, TaskStatus.done);
}
bool deleteItem(AbstractTask* item)
{
queueLock();
scope(exit) queueUnlock();
return deleteItemNoSync(item);
}
bool deleteItemNoSync(AbstractTask* item)
{
if(item.taskStatus != TaskStatus.notStarted)
{
return false;
}
item.taskStatus = TaskStatus.inProgress;
if(item is head)
{
// Make sure head gets set properly.
popNoSync();
return true;
}
if(item is tail)
{
tail = tail.prev;
if(tail !is null)
{
tail.next = null;
}
item.next = null;
item.prev = null;
return true;
}
if(item.next !is null)
{
assert(item.next.prev is item); // Check queue consistency.
item.next.prev = item.prev;
}
if(item.prev !is null)
{
assert(item.prev.next is item); // Check queue consistency.
item.prev.next = item.next;
}
item.next = null;
item.prev = null;
return true;
}
void queueLock()
{
assert(queueMutex);
if(!isSingleTask) queueMutex.lock();
}
void queueUnlock()
{
assert(queueMutex);
if(!isSingleTask) queueMutex.unlock();
}
void waiterLock()
{
if(!isSingleTask) waiterMutex.lock();
}
void waiterUnlock()
{
if(!isSingleTask) waiterMutex.unlock();
}
void wait()
{
if(!isSingleTask) workerCondition.wait();
}
void notify()
{
if(!isSingleTask) workerCondition.notify();
}
void notifyAll()
{
if(!isSingleTask) workerCondition.notifyAll();
}
void waitUntilCompletion()
{
if(isSingleTask)
{
singleTaskThread.join();
}
else
{
waiterCondition.wait();
}
}
void notifyWaiters()
{
if(!isSingleTask) waiterCondition.notifyAll();
}
// Private constructor for creating dummy pools that only have one thread,
// only execute one Task, and then terminate. This is used for
// Task.executeInNewThread().
this(AbstractTask* task, int priority = int.max)
{
assert(task);
// Dummy value, not used.
instanceStartIndex = 0;
this.isSingleTask = true;
task.taskStatus = TaskStatus.inProgress;
this.head = task;
singleTaskThread = new Thread(&doSingleTask);
singleTaskThread.start();
if(priority != int.max)
{
singleTaskThread.priority = priority;
}
}
public:
// This is used in parallel_algorithm but is too unstable to document
// as public API.
size_t defaultWorkUnitSize(size_t rangeLen) const pure nothrow @safe
{
if(this.size == 0)
{
return rangeLen;
}
immutable size_t eightSize = 4 * (this.size + 1);
auto ret = (rangeLen / eightSize) + ((rangeLen % eightSize == 0) ? 0 : 1);
return max(ret, 1);
}
/**
Default constructor that initializes a $(D TaskPool) with
$(D totalCPUs) - 1 worker threads. The minus 1 is included because the
main thread will also be available to do work.
Note: On single-core machines, the primitives provided by $(D TaskPool)
operate transparently in single-threaded mode.
*/
this() @trusted
{
this(totalCPUs - 1);
}
/**
Allows for custom number of worker threads.
*/
this(size_t nWorkers) @trusted
{
synchronized(TaskPool.classinfo)
{
instanceStartIndex = nextInstanceIndex;
// The first worker thread to be initialized will have this index,
// and will increment it. The second worker to be initialized will
// have this index plus 1.
nextThreadIndex = instanceStartIndex;
nextInstanceIndex += nWorkers;
}
queueMutex = new Mutex(this);
waiterMutex = new Mutex();
workerCondition = new Condition(queueMutex);
waiterCondition = new Condition(waiterMutex);
pool = new ParallelismThread[nWorkers];
foreach(ref poolThread; pool)
{
poolThread = new ParallelismThread(&startWorkLoop);
poolThread.pool = this;
poolThread.start();
}
}
/**
Implements a parallel foreach loop over a range. This works by implicitly
creating and submitting one $(D Task) to the $(D TaskPool) for each worker
thread. A work unit is a set of consecutive elements of $(D range) to
be processed by a worker thread between communication with any other
thread. The number of elements processed per work unit is controlled by the
$(D workUnitSize) parameter. Smaller work units provide better load
balancing, but larger work units avoid the overhead of communicating
with other threads frequently to fetch the next work unit. Large work
units also avoid false sharing in cases where the range is being modified.
The less time a single iteration of the loop takes, the larger
$(D workUnitSize) should be. For very expensive loop bodies,
$(D workUnitSize) should be 1. An overload that chooses a default work
unit size is also available.
Examples:
---
// Find the logarithm of every number from 1 to
// 10_000_000 in parallel.
auto logs = new double[10_000_000];
// Parallel foreach works with or without an index
// variable. It can be iterate by ref if range.front
// returns by ref.
// Iterate over logs using work units of size 100.
foreach(i, ref elem; taskPool.parallel(logs, 100))
{
elem = log(i + 1.0);
}
// Same thing, but use the default work unit size.
//
// Timings on an Athlon 64 X2 dual core machine:
//
// Parallel foreach: 388 milliseconds
// Regular foreach: 619 milliseconds
foreach(i, ref elem; taskPool.parallel(logs))
{
elem = log(i + 1.0);
}
---
Notes:
The memory usage of this implementation is guaranteed to be constant
in $(D range.length).
Breaking from a parallel foreach loop via a break, labeled break,
labeled continue, return or goto statement throws a
$(D ParallelForeachError).
In the case of non-random access ranges, parallel foreach buffers lazily
to an array of size $(D workUnitSize) before executing the parallel portion
of the loop. The exception is that, if a parallel foreach is executed
over a range returned by $(D asyncBuf) or $(D map), the copying is elided
and the buffers are simply swapped. In this case $(D workUnitSize) is
ignored and the work unit size is set to the buffer size of $(D range).
A memory barrier is guaranteed to be executed on exit from the loop,
so that results produced by all threads are visible in the calling thread.
$(B Exception Handling):
When at least one exception is thrown from inside a parallel foreach loop,
the submission of additional $(D Task) objects is terminated as soon as
possible, in a non-deterministic manner. All executing or
enqueued work units are allowed to complete. Then, all exceptions that
were thrown by any work unit are chained using $(D Throwable.next) and
rethrown. The order of the exception chaining is non-deterministic.
*/
ParallelForeach!R parallel(R)(R range, size_t workUnitSize)
{
enforce(workUnitSize > 0, "workUnitSize must be > 0.");
alias ParallelForeach!R RetType;
return RetType(this, range, workUnitSize);
}
/// Ditto
ParallelForeach!R parallel(R)(R range)
{
static if(hasLength!R)
{
// Default work unit size is such that we would use 4x as many
// slots as are in this thread pool.
size_t workUnitSize = defaultWorkUnitSize(range.length);
return parallel(range, workUnitSize);
}
else
{
// Just use a really, really dumb guess if the user is too lazy to
// specify.
return parallel(range, 512);
}
}
/**
Eager parallel map. The eagerness of this function means it has less
overhead than the lazily evaluated $(D TaskPool.map) and should be
preferred where the memory requirements of eagerness are acceptable.
$(D functions) are the functions to be evaluated, passed as template alias
parameters in a style similar to $(XREF algorithm, map). The first
argument must be a random access range.
---
auto numbers = iota(100_000_000.0);
// Find the square roots of numbers.
//
// Timings on an Athlon 64 X2 dual core machine:
//
// Parallel eager map: 0.802 s
// Equivalent serial implementation: 1.768 s
auto squareRoots = taskPool.amap!sqrt(numbers);
---
Immediately after the range argument, an optional work unit size argument
may be provided. Work units as used by $(D amap) are identical to those
defined for parallel foreach. If no work unit size is provided, the
default work unit size is used.
---
// Same thing, but make work unit size 100.
auto squareRoots = taskPool.amap!sqrt(numbers, 100);
---
An output range for returning the results may be provided as the last
argument. If one is not provided, an array of the proper type will be
allocated on the garbage collected heap. If one is provided, it must be a
random access range with assignable elements, must have reference
semantics with respect to assignment to its elements, and must have the
same length as the input range. Writing to adjacent elements from
different threads must be safe.
---
// Same thing, but explicitly allocate an array
// to return the results in. The element type
// of the array may be either the exact type
// returned by functions or an implicit conversion
// target.
auto squareRoots = new float[numbers.length];
taskPool.amap!sqrt(numbers, squareRoots);
// Multiple functions, explicit output range, and
// explicit work unit size.
auto results = new Tuple!(float, real)[numbers.length];
taskPool.amap!(sqrt, log)(numbers, 100, results);
---
Note:
A memory barrier is guaranteed to be executed after all results are written
but before returning so that results produced by all threads are visible
in the calling thread.
Tips:
To perform the mapping operation in place, provide the same range for the
input and output range.
To parallelize the copying of a range with expensive to evaluate elements
to an array, pass an identity function (a function that just returns
whatever argument is provided to it) to $(D amap).
$(B Exception Handling):
When at least one exception is thrown from inside the map functions,
the submission of additional $(D Task) objects is terminated as soon as
possible, in a non-deterministic manner. All currently executing or
enqueued work units are allowed to complete. Then, all exceptions that
were thrown from any work unit are chained using $(D Throwable.next) and
rethrown. The order of the exception chaining is non-deterministic.
*/
template amap(functions...)
{
///
auto amap(Args...)(Args args)
if(isRandomAccessRange!(Args[0]))
{
static if(functions.length == 1)
{
alias unaryFun!(functions[0]) fun;
}
else
{
alias adjoin!(staticMap!(unaryFun, functions)) fun;
}
alias args[0] range;
immutable len = range.length;
static if(
Args.length > 1 &&
randAssignable!(Args[$ - 1]) &&
is(MapType!(Args[0], functions) : ElementType!(Args[$ - 1]))
)
{
alias args[$ - 1] buf;
alias args[0..$ - 1] args2;
alias Args[0..$ - 1] Args2;
enforce(buf.length == len,
text("Can't use a user supplied buffer that's the wrong "
"size. (Expected :", len, " Got: ", buf.length));
}
else static if(randAssignable!(Args[$ - 1]) && Args.length > 1)
{
static assert(0, "Wrong buffer type.");
}
else
{
auto buf = uninitializedArray!(MapType!(Args[0], functions)[])(len);
alias args args2;
alias Args Args2;
}
if(!len) return buf;
static if(isIntegral!(Args2[$ - 1]))
{
static assert(args2.length == 2);
auto workUnitSize = cast(size_t) args2[1];
}
else
{
static assert(args2.length == 1, Args);
auto workUnitSize = defaultWorkUnitSize(range.length);
}
alias typeof(range) R;
if(workUnitSize > len)
{
workUnitSize = len;
}
// Handle as a special case:
if(size == 0)
{
size_t index = 0;
foreach(elem; range)
{
buf[index++] = fun(elem);
}
return buf;
}
// Effectively -1: chunkIndex + 1 == 0:
shared size_t workUnitIndex = size_t.max;
shared bool shouldContinue = true;
void doIt()
{
scope(failure)
{
// If an exception is thrown, all threads should bail.
atomicStore(shouldContinue, false);
}
while(atomicLoad(shouldContinue))
{
immutable myUnitIndex = atomicOp!"+="(workUnitIndex, 1);
immutable start = workUnitSize * myUnitIndex;
if(start >= len)
{
atomicStore(shouldContinue, false);
break;
}
immutable end = min(len, start + workUnitSize);
foreach(i; start..end)
{
buf[i] = fun(range[i]);
}
}
}
submitAndExecute(this, &doIt);
return buf;
}
}
/**
A semi-lazy parallel map that can be used for pipelining. The map
functions are evaluated for the first $(D bufSize) elements and stored in a
buffer and made available to $(D popFront). Meanwhile, in the
background a second buffer of the same size is filled. When the first
buffer is exhausted, it is swapped with the second buffer and filled while
the values from what was originally the second buffer are read. This
implementation allows for elements to be written to the buffer without
the need for atomic operations or synchronization for each write, and
enables the mapping function to be evaluated efficiently in parallel.
$(D map) has more overhead than the simpler procedure used by $(D amap)
but avoids the need to keep all results in memory simultaneously and works
with non-random access ranges.
Params:
source = The input range to be mapped. If $(D source) is not random
access it will be lazily buffered to an array of size $(D bufSize) before
the map function is evaluated. (For an exception to this rule, see Notes.)
bufSize = The size of the buffer to store the evaluated elements.
workUnitSize = The number of elements to evaluate in a single
$(D Task). Must be less than or equal to $(D bufSize), and
should be a fraction of $(D bufSize) such that all worker threads can be
used. If the default of size_t.max is used, workUnitSize will be set to
the pool-wide default.
Returns: An input range representing the results of the map. This range
has a length iff $(D source) has a length.
Notes:
If a range returned by $(D map) or $(D asyncBuf) is used as an input to
$(D map), then as an optimization the copying from the output buffer
of the first range to the input buffer of the second range is elided, even
though the ranges returned by $(D map) and $(D asyncBuf) are non-random
access ranges. This means that the $(D bufSize) parameter passed to the
current call to $(D map) will be ignored and the size of the buffer
will be the buffer size of $(D source).
Examples:
---
// Pipeline reading a file, converting each line
// to a number, taking the logarithms of the numbers,
// and performing the additions necessary to find
// the sum of the logarithms.
auto lineRange = File("numberList.txt").byLine();
auto dupedLines = std.algorithm.map!"a.idup"(lineRange);
auto nums = taskPool.map!(to!double)(dupedLines);
auto logs = taskPool.map!log10(nums);
double sum = 0;
foreach(elem; logs)
{
sum += elem;
}
---
$(B Exception Handling):
Any exceptions thrown while iterating over $(D source)
or computing the map function are re-thrown on a call to $(D popFront) or,
if thrown during construction, are simply allowed to propagate to the
caller. In the case of exceptions thrown while computing the map function,
the exceptions are chained as in $(D TaskPool.amap).
*/
template map(functions...)
{
///
auto
map(S)(S source, size_t bufSize = 100, size_t workUnitSize = size_t.max)
if(isInputRange!S)
{
enforce(workUnitSize == size_t.max || workUnitSize <= bufSize,
"Work unit size must be smaller than buffer size.");
static if(functions.length == 1)
{
alias unaryFun!(functions[0]) fun;
}
else
{
alias adjoin!(staticMap!(unaryFun, functions)) fun;
}
static final class Map
{
// This is a class because the task needs to be located on the
// heap and in the non-random access case source needs to be on
// the heap, too.
private:
enum bufferTrick = is(typeof(source.buf1)) &&
is(typeof(source.bufPos)) &&
is(typeof(source.doBufSwap()));
alias MapType!(S, functions) E;
E[] buf1, buf2;
S source;
TaskPool pool;
Task!(run, E[] delegate(E[]), E[]) nextBufTask;
size_t workUnitSize;
size_t bufPos;
bool lastTaskWaited;
static if(isRandomAccessRange!S)
{
alias S FromType;
void popSource()
{
static if(__traits(compiles, source[0..source.length]))
{
source = source[min(buf1.length, source.length)..source.length];
}
else static if(__traits(compiles, source[0..$]))
{
source = source[min(buf1.length, source.length)..$];
}
else
{
static assert(0, "S must have slicing for Map."
~ " " ~ S.stringof ~ " doesn't.");
}
}
}
else static if(bufferTrick)
{
// Make sure we don't have the buffer recycling overload of
// asyncBuf.
static if(
is(typeof(source.source)) &&
isRoundRobin!(typeof(source.source))
)
{
static assert(0, "Cannot execute a parallel map on " ~
"the buffer recycling overload of asyncBuf."
);
}
alias typeof(source.buf1) FromType;
FromType from;
// Just swap our input buffer with source's output buffer.
// No need to copy element by element.
FromType dumpToFrom()
{
assert(source.buf1.length <= from.length);
from.length = source.buf1.length;
swap(source.buf1, from);
// Just in case this source has been popped before
// being sent to map:
from = from[source.bufPos..$];
static if(is(typeof(source._length)))
{
source._length -= (from.length - source.bufPos);
}
source.doBufSwap();
return from;
}
}
else
{
alias ElementType!S[] FromType;
// The temporary array that data is copied to before being
// mapped.
FromType from;
FromType dumpToFrom()
{
assert(from !is null);
size_t i;
for(; !source.empty && i < from.length; source.popFront())
{
from[i++] = source.front;
}
from = from[0..i];
return from;
}
}
static if(hasLength!S)
{
size_t _length;
public @property size_t length() const pure nothrow @safe
{
return _length;
}
}
this(S source, size_t bufSize, size_t workUnitSize, TaskPool pool)
{
static if(bufferTrick)
{
bufSize = source.buf1.length;
}
buf1.length = bufSize;
buf2.length = bufSize;
static if(!isRandomAccessRange!S)
{
from.length = bufSize;
}
this.workUnitSize = (workUnitSize == size_t.max) ?
pool.defaultWorkUnitSize(bufSize) : workUnitSize;
this.source = source;
this.pool = pool;
static if(hasLength!S)
{
_length = source.length;
}
buf1 = fillBuf(buf1);
submitBuf2();
}
// The from parameter is a dummy and ignored in the random access
// case.
E[] fillBuf(E[] buf)
{
static if(isRandomAccessRange!S)
{
auto toMap = take(source, buf.length);
scope(success) popSource();
}
else
{
auto toMap = dumpToFrom();
}
buf = buf[0..min(buf.length, toMap.length)];
// Handle as a special case:
if(pool.size == 0)
{
size_t index = 0;
foreach(elem; toMap)
{
buf[index++] = fun(elem);
}
return buf;
}
pool.amap!functions(toMap, workUnitSize, buf);
return buf;
}
void submitBuf2()
in
{
assert(nextBufTask.prev is null);
assert(nextBufTask.next is null);
} body
{
// Hack to reuse the task object.
nextBufTask = typeof(nextBufTask).init;
nextBufTask._args[0] = &fillBuf;
nextBufTask._args[1] = buf2;
pool.put(nextBufTask);
}
void doBufSwap()
{
if(lastTaskWaited)
{
// Then the source is empty. Signal it here.
buf1 = null;
buf2 = null;
static if(!isRandomAccessRange!S)
{
from = null;
}
return;
}
buf2 = buf1;
buf1 = nextBufTask.yieldForce;
bufPos = 0;
if(source.empty)
{
lastTaskWaited = true;
}
else
{
submitBuf2();
}
}
public:
@property auto front()
{
return buf1[bufPos];
}
void popFront()
{
static if(hasLength!S)
{
_length--;
}
bufPos++;
if(bufPos >= buf1.length)
{
doBufSwap();
}
}
static if(std.range.isInfinite!S)
{
enum bool empty = false;
}
else
{
bool empty() @property
{
// popFront() sets this when source is empty
return buf1.length == 0;
}
}
}
return new Map(source, bufSize, workUnitSize, this);
}
}
/**
Given a $(D source) range that is expensive to iterate over, returns an
input range that asynchronously buffers the contents of
$(D source) into a buffer of $(D bufSize) elements in a worker thread,
while making prevously buffered elements from a second buffer, also of size
$(D bufSize), available via the range interface of the returned
object. The returned range has a length iff $(D hasLength!S).
$(D asyncBuf) is useful, for example, when performing expensive operations
on the elements of ranges that represent data on a disk or network.
Examples:
---
import std.conv, std.stdio;
void main()
{
// Fetch lines of a file in a background thread
// while processing prevously fetched lines,
// dealing with byLine's buffer recycling by
// eagerly duplicating every line.
auto lines = File("foo.txt").byLine();
auto duped = std.algorithm.map!"a.idup"(lines);
// Fetch more lines in the background while we
// process the lines already read into memory
// into a matrix of doubles.
double[][] matrix;
auto asyncReader = taskPool.asyncBuf(duped);
foreach(line; asyncReader)
{
auto ls = line.split("\t");
matrix ~= to!(double[])(ls);
}
}
---
$(B Exception Handling):
Any exceptions thrown while iterating over $(D source) are re-thrown on a
call to $(D popFront) or, if thrown during construction, simply
allowed to propagate to the caller.
*/
auto asyncBuf(S)(S source, size_t bufSize = 100) if(isInputRange!S)
{
static final class AsyncBuf
{
// This is a class because the task and source both need to be on
// the heap.
// The element type of S.
alias ElementType!S E; // Needs to be here b/c of forward ref bugs.
private:
E[] buf1, buf2;
S source;
TaskPool pool;
Task!(run, E[] delegate(E[]), E[]) nextBufTask;
size_t bufPos;
bool lastTaskWaited;
static if(hasLength!S)
{
size_t _length;
// Available if hasLength!S.
public @property size_t length() const pure nothrow @safe
{
return _length;
}
}
this(S source, size_t bufSize, TaskPool pool)
{
buf1.length = bufSize;
buf2.length = bufSize;
this.source = source;
this.pool = pool;
static if(hasLength!S)
{
_length = source.length;
}
buf1 = fillBuf(buf1);
submitBuf2();
}
E[] fillBuf(E[] buf)
{
assert(buf !is null);
size_t i;
for(; !source.empty && i < buf.length; source.popFront())
{
buf[i++] = source.front;
}
buf = buf[0..i];
return buf;
}
void submitBuf2()
in
{
assert(nextBufTask.prev is null);
assert(nextBufTask.next is null);
} body
{
// Hack to reuse the task object.
nextBufTask = typeof(nextBufTask).init;
nextBufTask._args[0] = &fillBuf;
nextBufTask._args[1] = buf2;
pool.put(nextBufTask);
}
void doBufSwap()
{
if(lastTaskWaited)
{
// Then source is empty. Signal it here.
buf1 = null;
buf2 = null;
return;
}
buf2 = buf1;
buf1 = nextBufTask.yieldForce;
bufPos = 0;
if(source.empty)
{
lastTaskWaited = true;
}
else
{
submitBuf2();
}
}
public:
E front() @property
{
return buf1[bufPos];
}
void popFront()
{
static if(hasLength!S)
{
_length--;
}
bufPos++;
if(bufPos >= buf1.length)
{
doBufSwap();
}
}
static if(std.range.isInfinite!S)
{
enum bool empty = false;
}
else
{
///
bool empty() @property
{
// popFront() sets this when source is empty:
return buf1.length == 0;
}
}
}
return new AsyncBuf(source, bufSize, this);
}
/**
Given a callable object $(D next) that writes to a user-provided buffer and
a second callable object $(D empty) that determines whether more data is
available to write via $(D next), returns an input range that
asynchronously calls $(D next) with a set of size $(D nBuffers) of buffers
and makes the results available in the order they were obtained via the
input range interface of the returned object. Similarly to the
input range overload of $(D asyncBuf), the first half of the buffers
are made available via the range interface while the second half are
filled and vice-versa.
Params:
next = A callable object that takes a single argument that must be an array
with mutable elements. When called, $(D next) writes data to
the array provided by the caller.
empty = A callable object that takes no arguments and returns a type
implicitly convertible to $(D bool). This is used to signify
that no more data is available to be obtained by calling $(D next).
initialBufSize = The initial size of each buffer. If $(D next) takes its
array by reference, it may resize the buffers.
nBuffers = The number of buffers to cycle through when calling $(D next).
Examples:
---
// Fetch lines of a file in a background
// thread while processing prevously fetched
// lines, without duplicating any lines.
auto file = File("foo.txt");
void next(ref char[] buf)
{
file.readln(buf);
}
// Fetch more lines in the background while we
// process the lines already read into memory
// into a matrix of doubles.
double[][] matrix;
auto asyncReader = taskPool.asyncBuf(&next, &file.eof);
foreach(line; asyncReader)
{
auto ls = line.split("\t");
matrix ~= to!(double[])(ls);
}
---
$(B Exception Handling):
Any exceptions thrown while iterating over $(D range) are re-thrown on a
call to $(D popFront).
Warning:
Using the range returned by this function in a parallel foreach loop
will not work because buffers may be overwritten while the task that
processes them is in queue. This is checked for at compile time
and will result in a static assertion failure.
*/
auto asyncBuf(C1, C2)(C1 next, C2 empty, size_t initialBufSize = 0, size_t nBuffers = 100)
if(is(typeof(C2.init()) : bool) &&
ParameterTypeTuple!C1.length == 1 &&
ParameterTypeTuple!C2.length == 0 &&
isArray!(ParameterTypeTuple!C1[0])
) {
auto roundRobin = RoundRobinBuffer!(C1, C2)(next, empty, initialBufSize, nBuffers);
return asyncBuf(roundRobin, nBuffers / 2);
}
/**
Parallel reduce on a random access range. Except as otherwise noted, usage
is similar to $(XREF algorithm, _reduce). This function works by splitting
the range to be reduced into work units, which are slices to be reduced in
parallel. Once the results from all work units are computed, a final serial
reduction is performed on these results to compute the final answer.
Therefore, care must be taken to choose the seed value appropriately.
Because the reduction is being performed in parallel,
$(D functions) must be associative. For notational simplicity, let # be an
infix operator representing $(D functions). Then, (a # b) # c must equal
a # (b # c). Floating point addition is not associative
even though addition in exact arithmetic is. Summing floating
point numbers using this function may give different results than summing
serially. However, for many practical purposes floating point addition
can be treated as associative.
Note that, since $(D functions) are assumed to be associative, additional
optimizations are made to the serial portion of the reduction algorithm.
These take advantage of the instruction level parallelism of modern CPUs,
in addition to the thread-level parallelism that the rest of this
module exploits. This can lead to better than linear speedups relative
to $(XREF algorithm, _reduce), especially for fine-grained benchmarks
like dot products.
An explicit seed may be provided as the first argument. If
provided, it is used as the seed for all work units and for the final
reduction of results from all work units. Therefore, if it is not the
identity value for the operation being performed, results may differ from
those generated by $(XREF algorithm, _reduce) or depending on how many work
units are used. The next argument must be the range to be reduced.
---
// Find the sum of squares of a range in parallel, using
// an explicit seed.
//
// Timings on an Athlon 64 X2 dual core machine:
//
// Parallel reduce: 72 milliseconds
// Using std.algorithm.reduce instead: 181 milliseconds
auto nums = iota(10_000_000.0f);
auto sumSquares = taskPool.reduce!"a + b"(
0.0, std.algorithm.map!"a * a"(nums)
);
---
If no explicit seed is provided, the first element of each work unit
is used as a seed. For the final reduction, the result from the first
work unit is used as the seed.
---
// Find the sum of a range in parallel, using the first
// element of each work unit as the seed.
auto sum = taskPool.reduce!"a + b"(nums);
---
An explicit work unit size may be specified as the last argument.
Specifying too small a work unit size will effectively serialize the
reduction, as the final reduction of the result of each work unit will
dominate computation time. If $(D TaskPool.size) for this instance
is zero, this parameter is ignored and one work unit is used.
---
// Use a work unit size of 100.
auto sum2 = taskPool.reduce!"a + b"(nums, 100);
// Work unit size of 100 and explicit seed.
auto sum3 = taskPool.reduce!"a + b"(0.0, nums, 100);
---
Parallel reduce supports multiple functions, like
$(D std.algorithm.reduce).
---
// Find both the min and max of nums.
auto minMax = taskPool.reduce!(min, max)(nums);
assert(minMax[0] == reduce!min(nums));
assert(minMax[1] == reduce!max(nums));
---
$(B Exception Handling):
After this function is finished executing, any exceptions thrown
are chained together via $(D Throwable.next) and rethrown. The chaining
order is non-deterministic.
*/
template reduce(functions...)
{
///
auto reduce(Args...)(Args args)
{
alias reduceAdjoin!functions fun;
alias reduceFinish!functions finishFun;
static if(isIntegral!(Args[$ - 1]))
{
size_t workUnitSize = cast(size_t) args[$ - 1];
alias args[0..$ - 1] args2;
alias Args[0..$ - 1] Args2;
}
else
{
alias args args2;
alias Args Args2;
}
auto makeStartValue(Type)(Type e)
{
static if(functions.length == 1)
{
return e;
}
else
{
typeof(adjoin!(staticMap!(binaryFun, functions))(e, e)) seed = void;
foreach (i, T; seed.Types)
{
auto p = (cast(void*) &seed.expand[i])
[0 .. seed.expand[i].sizeof];
emplace!T(p, e);
}
return seed;
}
}
static if(args2.length == 2)
{
static assert(isInputRange!(Args2[1]));
alias args2[1] range;
alias args2[0] seed;
enum explicitSeed = true;
static if(!is(typeof(workUnitSize)))
{
size_t workUnitSize = defaultWorkUnitSize(range.length);
}
}
else
{
static assert(args2.length == 1);
alias args2[0] range;
static if(!is(typeof(workUnitSize)))
{
size_t workUnitSize = defaultWorkUnitSize(range.length);
}
enforce(!range.empty,
"Cannot reduce an empty range with first element as start value.");
auto seed = makeStartValue(range.front);
enum explicitSeed = false;
range.popFront();
}
alias typeof(seed) E;
alias typeof(range) R;
E reduceOnRange(R range, size_t lowerBound, size_t upperBound)
{
// This is for exploiting instruction level parallelism by
// using multiple accumulator variables within each thread,
// since we're assuming functions are associative anyhow.
// This is so that loops can be unrolled automatically.
enum ilpTuple = TypeTuple!(0, 1, 2, 3, 4, 5);
enum nILP = ilpTuple.length;
immutable subSize = (upperBound - lowerBound) / nILP;
if(subSize <= 1)
{
// Handle as a special case.
static if(explicitSeed)
{
E result = seed;
}
else
{
E result = makeStartValue(range[lowerBound]);
lowerBound++;
}
foreach(i; lowerBound..upperBound)
{
result = fun(result, range[i]);
}
return result;
}
assert(subSize > 1);
E[nILP] results;
size_t[nILP] offsets;
foreach(i; ilpTuple)
{
offsets[i] = lowerBound + subSize * i;
static if(explicitSeed)
{
results[i] = seed;
}
else
{
results[i] = makeStartValue(range[offsets[i]]);
offsets[i]++;
}
}
immutable nLoop = subSize - (!explicitSeed);
foreach(i; 0..nLoop)
{
foreach(j; ilpTuple)
{
results[j] = fun(results[j], range[offsets[j]]);
offsets[j]++;
}
}
// Finish the remainder.
foreach(i; nILP * subSize + lowerBound..upperBound)
{
results[$ - 1] = fun(results[$ - 1], range[i]);
}
foreach(i; ilpTuple[1..$])
{
results[0] = finishFun(results[0], results[i]);
}
return results[0];
}
immutable len = range.length;
if(len == 0)
{
return seed;
}
if(this.size == 0)
{
return finishFun(seed, reduceOnRange(range, 0, len));
}
// Unlike the rest of the functions here, I can't use the Task object
// recycling trick here because this has to work on non-commutative
// operations. After all the tasks are done executing, fun() has to
// be applied on the results of these to get a final result, but
// it can't be evaluated out of order.
if(workUnitSize > len)
{
workUnitSize = len;
}
immutable size_t nWorkUnits = (len / workUnitSize) + ((len % workUnitSize == 0) ? 0 : 1);
assert(nWorkUnits * workUnitSize >= len);
alias Task!(run, typeof(&reduceOnRange), R, size_t, size_t) RTask;
RTask[] tasks;
// Can't use alloca() due to Bug 3753. Use a fixed buffer
// backed by malloc().
enum maxStack = 2_048;
byte[maxStack] buf = void;
immutable size_t nBytesNeeded = nWorkUnits * RTask.sizeof;
import core.stdc.stdlib;
if(nBytesNeeded < maxStack)
{
tasks = (cast(RTask*) buf.ptr)[0..nWorkUnits];
}
else
{
auto ptr = cast(RTask*) malloc(nBytesNeeded);
if(!ptr)
{
throw new OutOfMemoryError(
"Out of memory in std.parallelism."
);
}
tasks = ptr[0..nWorkUnits];
}
scope(exit)
{
if(nBytesNeeded > maxStack)
{
free(tasks.ptr);
}
}
tasks[] = RTask.init;
// Hack to take the address of a nested function w/o
// making a closure.
static auto scopedAddress(D)(scope D del)
{
return del;
}
size_t curPos = 0;
void useTask(ref RTask task)
{
task.pool = this;
task._args[0] = scopedAddress(&reduceOnRange);
task._args[3] = min(len, curPos + workUnitSize); // upper bound.
task._args[1] = range; // range
task._args[2] = curPos; // lower bound.
curPos += workUnitSize;
}
foreach(ref task; tasks)
{
useTask(task);
}
foreach(i; 1..tasks.length - 1)
{
tasks[i].next = tasks[i + 1].basePtr;
tasks[i + 1].prev = tasks[i].basePtr;
}
if(tasks.length > 1)
{
queueLock();
scope(exit) queueUnlock();
abstractPutGroupNoSync(
tasks[1].basePtr,
tasks[$ - 1].basePtr
);
}
if(tasks.length > 0)
{
try
{
tasks[0].job();
}
catch(Throwable e)
{
tasks[0].exception = e;
}
tasks[0].taskStatus = TaskStatus.done;
// Try to execute each of these in the current thread
foreach(ref task; tasks[1..$])
{
tryDeleteExecute(task.basePtr);
}
}
// Now that we've tried to execute every task, they're all either
// done or in progress. Force all of them.
E result = seed;
Throwable firstException, lastException;
foreach(ref task; tasks)
{
try
{
task.yieldForce;
}
catch(Throwable e)
{
addToChain(e, firstException, lastException);
continue;
}
if(!firstException) result = finishFun(result, task.returnVal);
}
if(firstException) throw firstException;
return result;
}
}
/**
Gets the index of the current thread relative to this $(D TaskPool). Any
thread not in this pool will receive an index of 0. The worker threads in
this pool receive unique indices of 1 through $(D this.size).
This function is useful for maintaining worker-local resources.
Examples:
---
// Execute a loop that computes the greatest common
// divisor of every number from 0 through 999 with
// 42 in parallel. Write the results out to
// a set of files, one for each thread. This allows
// results to be written out without any synchronization.
import std.conv, std.range, std.numeric, std.stdio;
void main()
{
auto filesHandles = new File[taskPool.size + 1];
scope(exit) {
foreach(ref handle; fileHandles) {
handle.close();
}
}
foreach(i, ref handle; fileHandles)
{
handle = File("workerResults" ~ to!string(i) ~ ".txt");
}
foreach(num; parallel(iota(1_000)))
{
auto outHandle = fileHandles[taskPool.workerIndex];
outHandle.writeln(num, '\t', gcd(num, 42));
}
}
---
*/
size_t workerIndex() @property @safe const nothrow
{
immutable rawInd = threadIndex;
return (rawInd >= instanceStartIndex && rawInd < instanceStartIndex + size) ?
(rawInd - instanceStartIndex + 1) : 0;
}
/**
Struct for creating worker-local storage. Worker-local storage is
thread-local storage that exists only for worker threads in a given
$(D TaskPool) plus a single thread outside the pool. It is allocated on the
garbage collected heap in a way that avoids _false sharing, and doesn't
necessarily have global scope within any thread. It can be accessed from
any worker thread in the $(D TaskPool) that created it, and one thread
outside this $(D TaskPool). All threads outside the pool that created a
given instance of worker-local storage share a single slot.
Since the underlying data for this struct is heap-allocated, this struct
has reference semantics when passed between functions.
The main uses cases for $(D WorkerLocalStorageStorage) are:
1. Performing parallel reductions with an imperative, as opposed to
functional, programming style. In this case, it's useful to treat
$(D WorkerLocalStorageStorage) as local to each thread for only the parallel
portion of an algorithm.
2. Recycling temporary buffers across iterations of a parallel foreach loop.
Examples:
---
// Calculate pi as in our synopsis example, but
// use an imperative instead of a functional style.
immutable n = 1_000_000_000;
immutable delta = 1.0L / n;
auto sums = taskPool.workerLocalStorage(0.0L);
foreach(i; parallel(iota(n)))
{
immutable x = ( i - 0.5L ) * delta;
immutable toAdd = delta / ( 1.0 + x * x );
sums.get += toAdd;
}
// Add up the results from each worker thread.
real pi = 0;
foreach(threadResult; sums.toRange)
{
pi += 4.0L * threadResult;
}
---
*/
static struct WorkerLocalStorage(T)
{
private:
TaskPool pool;
size_t size;
static immutable size_t cacheLineSize;
size_t elemSize;
bool* stillThreadLocal;
shared static this()
{
size_t lineSize = 0;
foreach(cachelevel; datacache)
{
if(cachelevel.lineSize > lineSize && cachelevel.lineSize < uint.max)
{
lineSize = cachelevel.lineSize;
}
}
cacheLineSize = lineSize;
}
static size_t roundToLine(size_t num) pure nothrow
{
if(num % cacheLineSize == 0)
{
return num;
}
else {
return ((num / cacheLineSize) + 1) * cacheLineSize;
}
}
void* data;
void initialize(TaskPool pool)
{
this.pool = pool;
size = pool.size + 1;
stillThreadLocal = new bool;
*stillThreadLocal = true;
// Determines whether the GC should scan the array.
auto blkInfo = (typeid(T).flags & 1) ?
cast(GC.BlkAttr) 0 :
GC.BlkAttr.NO_SCAN;
immutable nElem = pool.size + 1;
elemSize = roundToLine(T.sizeof);
// The + 3 is to pad one full cache line worth of space on either side
// of the data structure to make sure false sharing with completely
// unrelated heap data is prevented, and to provide enough padding to
// make sure that data is cache line-aligned.
data = GC.malloc(elemSize * (nElem + 3), blkInfo) + elemSize;
// Cache line align data ptr.
data = cast(void*) roundToLine(cast(size_t) data);
foreach(i; 0..nElem)
{
this.opIndex(i) = T.init;
}
}
ref T opIndex(size_t index)
{
assert(index < size, text(index, '\t', uint.max));
return *(cast(T*) (data + elemSize * index));
}
void opIndexAssign(T val, size_t index)
{
assert(index < size);
*(cast(T*) (data + elemSize * index)) = val;
}
public:
/**
Get the current thread's instance. Returns by ref.
Note that calling $(D get) from any thread
outside the $(D TaskPool) that created this instance will return the
same reference, so an instance of worker-local storage should only be
accessed from one thread outside the pool that created it. If this
rule is violated, undefined behavior will result.
If assertions are enabled and $(D toRange) has been called, then this
WorkerLocalStorage instance is no longer worker-local and an assertion
failure will result when calling this method. This is not checked
when assertions are disabled for performance reasons.
*/
ref T get() @property
{
assert(*stillThreadLocal,
"Cannot call get() on this instance of WorkerLocalStorage " ~
"because it is no longer worker-local."
);
return opIndex(pool.workerIndex);
}
/**
Assign a value to the current thread's instance. This function has
the same caveats as its overload.
*/
void get(T val) @property
{
assert(*stillThreadLocal,
"Cannot call get() on this instance of WorkerLocalStorage " ~
"because it is no longer worker-local."
);
opIndexAssign(val, pool.workerIndex);
}
/**
Returns a range view of the values for all threads, which can be used
to further process the results of each thread after running the parallel
part of your algorithm. Do not use this method in the parallel portion
of your algorithm.
Calling this function sets a flag indicating that this struct is no
longer worker-local, and attempting to use the $(D get) method again
will result in an assertion failure if assertions are enabled.
*/
WorkerLocalStorageRange!T toRange() @property
{
if(*stillThreadLocal)
{
*stillThreadLocal = false;
// Make absolutely sure results are visible to all threads.
// This is probably not necessary since some other
// synchronization primitive will be used to signal that the
// parallel part of the algorithm is done, but the
// performance impact should be negligible, so it's better
// to be safe.
ubyte barrierDummy;
atomicSetUbyte(barrierDummy, 1);
}
return WorkerLocalStorageRange!T(this);
}
}
/**
Range primitives for worker-local storage. The purpose of this is to
access results produced by each worker thread from a single thread once you
are no longer using the worker-local storage from multiple threads.
Do not use this struct in the parallel portion of your algorithm.
The proper way to instantiate this object is to call
$(D WorkerLocalStorage.toRange). Once instantiated, this object behaves
as a finite random-access range with assignable, lvalue elemends and
a length equal to the number of worker threads in the $(D TaskPool) that
created it plus 1.
*/
static struct WorkerLocalStorageRange(T)
{
private:
WorkerLocalStorage!T workerLocalStorage;
size_t _length;
size_t beginOffset;
this(WorkerLocalStorage!T wl)
{
this.workerLocalStorage = wl;
_length = wl.size;
}
public:
ref T front() @property
{
return this[0];
}
ref T back() @property
{
return this[_length - 1];
}
void popFront()
{
if(_length > 0)
{
beginOffset++;
_length--;
}
}
void popBack()
{
if(_length > 0)
{
_length--;
}
}
typeof(this) save() @property
{
return this;
}
ref T opIndex(size_t index)
{
assert(index < _length);
return workerLocalStorage[index + beginOffset];
}
void opIndexAssign(T val, size_t index)
{
assert(index < _length);
workerLocalStorage[index] = val;
}
typeof(this) opSlice(size_t lower, size_t upper)
{
assert(upper <= _length);
auto newWl = this.workerLocalStorage;
newWl.data += lower * newWl.elemSize;
newWl.size = upper - lower;
return typeof(this)(newWl);
}
bool empty() @property
{
return length == 0;
}
size_t length() @property
{
return _length;
}
}
/**
Creates an instance of worker-local storage, initialized with a given
value. The value is $(D lazy) so that you can, for example, easily
create one instance of a class for each worker. For usage example,
see the $(D WorkerLocalStorage) struct.
*/
WorkerLocalStorage!T workerLocalStorage(T)(lazy T initialVal = T.init)
{
WorkerLocalStorage!T ret;
ret.initialize(this);
foreach(i; 0..size + 1)
{
ret[i] = initialVal;
}
// Memory barrier to make absolutely sure that what we wrote is
// visible to worker threads.
ubyte barrierDummy;
atomicSetUbyte(barrierDummy, 0);
return ret;
}
/**
Signals to all worker threads to terminate as soon as they are finished
with their current $(D Task), or immediately if they are not executing a
$(D Task). $(D Task)s that were in queue will not be executed unless
a call to $(D Task.workForce), $(D Task.yieldForce) or $(D Task.spinForce)
causes them to be executed.
Use only if you have waitied on every $(D Task) and therefore know the
queue is empty, or if you speculatively executed some tasks and no longer
need the results.
*/
void stop() @trusted
{
queueLock();
scope(exit) queueUnlock();
atomicSetUbyte(status, PoolState.stopNow);
notifyAll();
}
/**
Signals worker threads to terminate when the queue becomes empty.
If blocking argument is true, wait for all worker threads to terminate
before returning. This option might be used in applications where
task results are never consumed-- e.g. when $(D TaskPool) is employed as a
rudimentary scheduler for tasks which communicate by means other than
return values.
Warning: Calling this function with $(D blocking = true) from a worker
thread that is a member of the same $(D TaskPool) that
$(D finish) is being called on will result in a deadlock.
*/
void finish(bool blocking = false) @trusted
{
{
queueLock();
scope(exit) queueUnlock();
atomicCasUbyte(status, PoolState.running, PoolState.finishing);
notifyAll();
}
if (blocking)
{
// Use this thread as a worker until everything is finished.
executeWorkLoop();
foreach(t; pool)
{
// Maybe there should be something here to prevent a thread
// from calling join() on itself if this function is called
// from a worker thread in the same pool, but:
//
// 1. Using an if statement to skip join() would result in
// finish() returning without all tasks being finished.
//
// 2. If an exception were thrown, it would bubble up to the
// Task from which finish() was called and likely be
// swallowed.
t.join();
}
}
}
/// Returns the number of worker threads in the pool.
@property size_t size() @safe const pure nothrow
{
return pool.length;
}
/**
Put a $(D Task) object on the back of the task queue. The $(D Task)
object may be passed by pointer or reference.
Example:
---
import std.file;
// Create a task.
auto t = task!read("foo.txt");
// Add it to the queue to be executed.
taskPool.put(t);
---
Notes:
@trusted overloads of this function are called for $(D Task)s if
$(XREF traits, hasUnsharedAliasing) is false for the $(D Task)'s
return type or the function the $(D Task) executes is $(D pure).
$(D Task) objects that meet all other requirements specified in the
$(D @trusted) overloads of $(D task) and $(D scopedTask) may be created
and executed from $(D @safe) code via $(D Task.executeInNewThread) but
not via $(D TaskPool).
While this function takes the address of variables that may
be on the stack, some overloads are marked as @trusted.
$(D Task) includes a destructor that waits for the task to complete
before destroying the stack frame it is allocated on. Therefore,
it is impossible for the stack frame to be destroyed before the task is
complete and no longer referenced by a $(D TaskPool).
*/
void put(alias fun, Args...)(ref Task!(fun, Args) task)
if(!isSafeReturn!(typeof(task)))
{
task.pool = this;
abstractPut(task.basePtr);
}
/// Ditto
void put(alias fun, Args...)(Task!(fun, Args)* task)
if(!isSafeReturn!(typeof(*task)))
{
enforce(task !is null, "Cannot put a null Task on a TaskPool queue.");
put(*task);
}
@trusted void put(alias fun, Args...)(ref Task!(fun, Args) task)
if(isSafeReturn!(typeof(task)))
{
task.pool = this;
abstractPut(task.basePtr);
}
@trusted void put(alias fun, Args...)(Task!(fun, Args)* task)
if(isSafeReturn!(typeof(*task)))
{
enforce(task !is null, "Cannot put a null Task on a TaskPool queue.");
put(*task);
}
/**
These properties control whether the worker threads are daemon threads.
A daemon thread is automatically terminated when all non-daemon threads
have terminated. A non-daemon thread will prevent a program from
terminating as long as it has not terminated.
If any $(D TaskPool) with non-daemon threads is active, either $(D stop)
or $(D finish) must be called on it before the program can terminate.
The worker treads in the $(D TaskPool) instance returned by the
$(D taskPool) property are daemon by default. The worker threads of
manually instantiated task pools are non-daemon by default.
Note: For a size zero pool, the getter arbitrarily returns true and the
setter has no effect.
*/
bool isDaemon() @property @trusted
{
queueLock();
scope(exit) queueUnlock();
return (size == 0) ? true : pool[0].isDaemon;
}
/// Ditto
void isDaemon(bool newVal) @property @trusted
{
queueLock();
scope(exit) queueUnlock();
foreach(thread; pool)
{
thread.isDaemon = newVal;
}
}
/**
These functions allow getting and setting the OS scheduling priority of
the worker threads in this $(D TaskPool). They forward to
$(D core.thread.Thread.priority), so a given priority value here means the
same thing as an identical priority value in $(D core.thread).
Note: For a size zero pool, the getter arbitrarily returns
$(D core.thread.Thread.PRIORITY_MIN) and the setter has no effect.
*/
int priority() @property @trusted
{
return (size == 0) ? core.thread.Thread.PRIORITY_MIN :
pool[0].priority;
}
/// Ditto
void priority(int newPriority) @property @trusted
{
if(size > 0)
{
foreach(t; pool)
{
t.priority = newPriority;
}
}
}
}
/**
Returns a lazily initialized global instantiation of $(D TaskPool).
This function can safely be called concurrently from multiple non-worker
threads. The worker threads in this pool are daemon threads, meaning that it
is not necessary to call $(D TaskPool.stop) or $(D TaskPool.finish) before
terminating the main thread.
*/
@property TaskPool taskPool() @trusted
{
static bool initialized;
__gshared static TaskPool pool;
if(!initialized)
{
synchronized(TaskPool.classinfo)
{
if(!pool)
{
pool = new TaskPool(defaultPoolThreads);
pool.isDaemon = true;
}
}
initialized = true;
}
return pool;
}
private shared uint _defaultPoolThreads;
shared static this()
{
atomicStore(_defaultPoolThreads, totalCPUs - 1);
}
/**
These properties get and set the number of worker threads in the $(D TaskPool)
instance returned by $(D taskPool). The default value is $(D totalCPUs) - 1.
Calling the setter after the first call to $(D taskPool) does not changes
number of worker threads in the instance returned by $(D taskPool).
*/
@property uint defaultPoolThreads() @trusted
{
return atomicLoad(_defaultPoolThreads);
}
/// Ditto
@property void defaultPoolThreads(uint newVal) @trusted
{
atomicStore(_defaultPoolThreads, newVal);
}
/**
Convenience functions that forwards to $(D taskPool.parallel). The
purpose of these is to make parallel foreach less verbose and more
readable.
Example:
---
// Find the logarithm of every number from
// 1 to 1_000_000 in parallel, using the
// default TaskPool instance.
auto logs = new double[1_000_000];
foreach(i, ref elem; parallel(logs)) {
elem = log(i + 1.0);
}
---
*/
ParallelForeach!R parallel(R)(R range)
{
return taskPool.parallel(range);
}
/// Ditto
ParallelForeach!R parallel(R)(R range, size_t workUnitSize)
{
return taskPool.parallel(range, workUnitSize);
}
// Thrown when a parallel foreach loop is broken from.
class ParallelForeachError : Error
{
this()
{
super("Cannot break from a parallel foreach loop using break, return, "
~ "labeled break/continue or goto statements.");
}
}
/*------Structs that implement opApply for parallel foreach.------------------*/
private template randLen(R)
{
enum randLen = isRandomAccessRange!R && hasLength!R;
}
private void submitAndExecute(
TaskPool pool,
scope void delegate() doIt
)
{
immutable nThreads = pool.size + 1;
alias typeof(scopedTask(doIt)) PTask;
import core.stdc.stdlib;
import core.stdc.string : memcpy;
// The logical thing to do would be to just use alloca() here, but that
// causes problems on Windows for reasons that I don't understand
// (tentatively a compiler bug) and definitely doesn't work on Posix due
// to Bug 3753. Therefore, allocate a fixed buffer and fall back to
// malloc() if someone's using a ridiculous amount of threads. Also,
// the using a byte array instead of a PTask array as the fixed buffer
// is to prevent d'tors from being called on uninitialized excess PTask
// instances.
enum nBuf = 64;
byte[nBuf * PTask.sizeof] buf = void;
PTask[] tasks;
if(nThreads <= nBuf)
{
tasks = (cast(PTask*) buf.ptr)[0..nThreads];
}
else
{
auto ptr = cast(PTask*) malloc(nThreads * PTask.sizeof);
if(!ptr) throw new OutOfMemoryError("Out of memory in std.parallelism.");
tasks = ptr[0..nThreads];
}
scope(exit)
{
if(nThreads > nBuf)
{
free(tasks.ptr);
}
}
foreach(ref t; tasks)
{
// This silly looking code is necessary to prevent d'tors from being
// called on uninitialized objects.
auto temp = scopedTask(doIt);
core.stdc.string.memcpy(&t, &temp, PTask.sizeof);
// This has to be done to t after copying, not temp before copying.
// Otherwise, temp's destructor will sit here and wait for the
// task to finish.
t.pool = pool;
}
foreach(i; 1..tasks.length - 1)
{
tasks[i].next = tasks[i + 1].basePtr;
tasks[i + 1].prev = tasks[i].basePtr;
}
if(tasks.length > 1)
{
pool.queueLock();
scope(exit) pool.queueUnlock();
pool.abstractPutGroupNoSync(
tasks[1].basePtr,
tasks[$ - 1].basePtr
);
}
if(tasks.length > 0)
{
try
{
tasks[0].job();
}
catch(Throwable e)
{
tasks[0].exception = e;
}
tasks[0].taskStatus = TaskStatus.done;
// Try to execute each of these in the current thread
foreach(ref task; tasks[1..$])
{
pool.tryDeleteExecute(task.basePtr);
}
}
Throwable firstException, lastException;
foreach(i, ref task; tasks)
{
try
{
task.yieldForce;
}
catch(Throwable e)
{
addToChain(e, firstException, lastException);
continue;
}
}
if(firstException) throw firstException;
}
void foreachErr()
{
throw new ParallelForeachError();
}
int doSizeZeroCase(R, Delegate)(ref ParallelForeach!R p, Delegate dg)
{
with(p)
{
int res = 0;
size_t index = 0;
// The explicit ElementType!R in the foreach loops is necessary for
// correct behavior when iterating over strings.
static if(hasLvalueElements!R)
{
foreach(ref ElementType!R elem; range)
{
static if(ParameterTypeTuple!dg.length == 2)
{
res = dg(index, elem);
}
else
{
res = dg(elem);
}
if(res) foreachErr();
index++;
}
}
else
{
foreach(ElementType!R elem; range)
{
static if(ParameterTypeTuple!dg.length == 2)
{
res = dg(index, elem);
}
else
{
res = dg(elem);
}
if(res) foreachErr();
index++;
}
}
return res;
}
}
private enum string parallelApplyMixinRandomAccess = q{
// Handle empty thread pool as special case.
if(pool.size == 0)
{
return doSizeZeroCase(this, dg);
}
// Whether iteration is with or without an index variable.
enum withIndex = ParameterTypeTuple!(typeof(dg)).length == 2;
shared size_t workUnitIndex = size_t.max; // Effectively -1: chunkIndex + 1 == 0
immutable len = range.length;
if(!len) return 0;
shared bool shouldContinue = true;
void doIt()
{
scope(failure)
{
// If an exception is thrown, all threads should bail.
atomicStore(shouldContinue, false);
}
while(atomicLoad(shouldContinue))
{
immutable myUnitIndex = atomicOp!"+="(workUnitIndex, 1);
immutable start = workUnitSize * myUnitIndex;
if(start >= len)
{
atomicStore(shouldContinue, false);
break;
}
immutable end = min(len, start + workUnitSize);
foreach(i; start..end)
{
static if(withIndex)
{
if(dg(i, range[i])) foreachErr();
}
else
{
if(dg(range[i])) foreachErr();
}
}
}
}
submitAndExecute(pool, &doIt);
return 0;
};
enum string parallelApplyMixinInputRange = q{
// Handle empty thread pool as special case.
if(pool.size == 0)
{
return doSizeZeroCase(this, dg);
}
// Whether iteration is with or without an index variable.
enum withIndex = ParameterTypeTuple!(typeof(dg)).length == 2;
// This protects the range while copying it.
auto rangeMutex = new Mutex();
shared bool shouldContinue = true;
// The total number of elements that have been popped off range.
// This is updated only while protected by rangeMutex;
size_t nPopped = 0;
static if(
is(typeof(range.buf1)) &&
is(typeof(range.bufPos)) &&
is(typeof(range.doBufSwap()))
)
{
// Make sure we don't have the buffer recycling overload of
// asyncBuf.
static if(
is(typeof(range.source)) &&
isRoundRobin!(typeof(range.source))
)
{
static assert(0, "Cannot execute a parallel foreach loop on " ~
"the buffer recycling overload of asyncBuf.");
}
enum bool bufferTrick = true;
}
else
{
enum bool bufferTrick = false;
}
void doIt()
{
scope(failure)
{
// If an exception is thrown, all threads should bail.
atomicStore(shouldContinue, false);
}
static if(hasLvalueElements!R)
{
alias ElementType!R*[] Temp;
Temp temp;
// Returns: The previous value of nPopped.
size_t makeTemp()
{
if(temp is null)
{
temp = uninitializedArray!Temp(workUnitSize);
}
rangeMutex.lock();
scope(exit) rangeMutex.unlock();
size_t i = 0;
for(; i < workUnitSize && !range.empty; range.popFront(), i++)
{
temp[i] = addressOf(range.front);
}
temp = temp[0..i];
auto ret = nPopped;
nPopped += temp.length;
return ret;
}
}
else
{
alias ElementType!R[] Temp;
Temp temp;
// Returns: The previous value of nPopped.
static if(!bufferTrick) size_t makeTemp()
{
if(temp is null)
{
temp = uninitializedArray!Temp(workUnitSize);
}
rangeMutex.lock();
scope(exit) rangeMutex.unlock();
size_t i = 0;
for(; i < workUnitSize && !range.empty; range.popFront(), i++)
{
temp[i] = range.front;
}
temp = temp[0..i];
auto ret = nPopped;
nPopped += temp.length;
return ret;
}
static if(bufferTrick) size_t makeTemp()
{
rangeMutex.lock();
scope(exit) rangeMutex.unlock();
// Elide copying by just swapping buffers.
temp.length = range.buf1.length;
swap(range.buf1, temp);
// This is necessary in case popFront() has been called on
// range before entering the parallel foreach loop.
temp = temp[range.bufPos..$];
static if(is(typeof(range._length)))
{
range._length -= (temp.length - range.bufPos);
}
range.doBufSwap();
auto ret = nPopped;
nPopped += temp.length;
return ret;
}
}
while(atomicLoad(shouldContinue))
{
auto overallIndex = makeTemp();
if(temp.empty)
{
atomicStore(shouldContinue, false);
break;
}
foreach(i; 0..temp.length)
{
scope(success) overallIndex++;
static if(hasLvalueElements!R)
{
static if(withIndex)
{
if(dg(overallIndex, *temp[i])) foreachErr();
}
else
{
if(dg(*temp[i])) foreachErr();
}
}
else
{
static if(withIndex)
{
if(dg(overallIndex, temp[i])) foreachErr();
}
else
{
if(dg(temp[i])) foreachErr();
}
}
}
}
}
submitAndExecute(pool, &doIt);
return 0;
};
// Calls e.next until the end of the chain is found.
private Throwable findLastException(Throwable e) pure nothrow
{
if(e is null) return null;
while(e.next)
{
e = e.next;
}
return e;
}
// Adds e to the exception chain.
private void addToChain(
Throwable e,
ref Throwable firstException,
ref Throwable lastException
) pure nothrow
{
if(firstException)
{
assert(lastException);
lastException.next = e;
lastException = findLastException(e);
}
else
{
firstException = e;
lastException = findLastException(e);
}
}
private struct ParallelForeach(R)
{
TaskPool pool;
R range;
size_t workUnitSize;
alias ElementType!R E;
static if(hasLvalueElements!R)
{
alias int delegate(ref E) NoIndexDg;
alias int delegate(size_t, ref E) IndexDg;
}
else
{
alias int delegate(E) NoIndexDg;
alias int delegate(size_t, E) IndexDg;
}
int opApply(scope NoIndexDg dg)
{
static if(randLen!R)
{
mixin(parallelApplyMixinRandomAccess);
}
else
{
mixin(parallelApplyMixinInputRange);
}
}
int opApply(scope IndexDg dg)
{
static if(randLen!R)
{
mixin(parallelApplyMixinRandomAccess);
}
else
{
mixin(parallelApplyMixinInputRange);
}
}
}
/*
This struct buffers the output of a callable that outputs data into a
user-supplied buffer into a set of buffers of some fixed size. It allows these
buffers to be accessed with an input range interface. This is used internally
in the buffer-recycling overload of TaskPool.asyncBuf, which creates an
instance and forwards it to the input range overload of asyncBuf.
*/
private struct RoundRobinBuffer(C1, C2)
{
// No need for constraints because they're already checked for in asyncBuf.
alias ParameterTypeTuple!(C1.init)[0] Array;
alias typeof(Array.init[0]) T;
T[][] bufs;
size_t index;
C1 nextDel;
C2 emptyDel;
bool _empty;
bool primed;
this(
C1 nextDel,
C2 emptyDel,
size_t initialBufSize,
size_t nBuffers
) {
this.nextDel = nextDel;
this.emptyDel = emptyDel;
bufs.length = nBuffers;
foreach(ref buf; bufs)
{
buf.length = initialBufSize;
}
}
void prime()
in
{
assert(!empty);
}
body
{
scope(success) primed = true;
nextDel(bufs[index]);
}
T[] front() @property
in
{
assert(!empty);
}
body
{
if(!primed) prime();
return bufs[index];
}
void popFront()
{
if(empty || emptyDel())
{
_empty = true;
return;
}
index = (index + 1) % bufs.length;
primed = false;
}
bool empty() @property const pure nothrow @safe
{
return _empty;
}
}
version(unittest)
{
// This was the only way I could get nested maps to work.
__gshared TaskPool poolInstance;
import std.stdio;
}
// These test basic functionality but don't stress test for threading bugs.
// These are the tests that should be run every time Phobos is compiled.
unittest
{
poolInstance = new TaskPool(2);
scope(exit) poolInstance.stop();
// The only way this can be verified is manually.
stderr.writeln("totalCPUs = ", totalCPUs);
auto oldPriority = poolInstance.priority;
poolInstance.priority = Thread.PRIORITY_MAX;
assert(poolInstance.priority == Thread.PRIORITY_MAX);
poolInstance.priority = Thread.PRIORITY_MIN;
assert(poolInstance.priority == Thread.PRIORITY_MIN);
poolInstance.priority = oldPriority;
assert(poolInstance.priority == oldPriority);
static void refFun(ref uint num)
{
num++;
}
uint x;
// Test task().
auto t = task!refFun(x);
poolInstance.put(t);
t.yieldForce;
assert(t.args[0] == 1);
auto t2 = task(&refFun, x);
poolInstance.put(t2);
t2.yieldForce;
assert(t2.args[0] == 1);
// Test scopedTask().
auto st = scopedTask!refFun(x);
poolInstance.put(st);
st.yieldForce;
assert(st.args[0] == 1);
auto st2 = scopedTask(&refFun, x);
poolInstance.put(st2);
st2.yieldForce;
assert(st2.args[0] == 1);
// Test executeInNewThread().
auto ct = scopedTask!refFun(x);
ct.executeInNewThread(Thread.PRIORITY_MAX);
ct.yieldForce;
assert(ct.args[0] == 1);
// Test ref return.
uint toInc = 0;
static ref T makeRef(T)(ref T num)
{
return num;
}
auto t3 = task!makeRef(toInc);
taskPool.put(t3);
assert(t3.args[0] == 0);
t3.spinForce++;
assert(t3.args[0] == 1);
static void testSafe() @safe {
static int bump(int num)
{
return num + 1;
}
auto safePool = new TaskPool(0);
auto t = task(&bump, 1);
taskPool.put(t);
assert(t.yieldForce == 2);
auto st = scopedTask(&bump, 1);
taskPool.put(st);
assert(st.yieldForce == 2);
safePool.stop();
}
auto arr = [1,2,3,4,5];
auto nums = new uint[5];
auto nums2 = new uint[5];
foreach(i, ref elem; poolInstance.parallel(arr))
{
elem++;
nums[i] = cast(uint) i + 2;
nums2[i] = elem;
}
assert(nums == [2,3,4,5,6], text(nums));
assert(nums2 == nums, text(nums2));
assert(arr == nums, text(arr));
// Test const/immutable arguments.
static int add(int lhs, int rhs)
{
return lhs + rhs;
}
immutable addLhs = 1;
immutable addRhs = 2;
auto addTask = task(&add, addLhs, addRhs);
auto addScopedTask = scopedTask(&add, addLhs, addRhs);
poolInstance.put(addTask);
poolInstance.put(addScopedTask);
assert(addTask.yieldForce == 3);
assert(addScopedTask.yieldForce == 3);
// Test parallel foreach with non-random access range.
auto range = filter!"a != 666"([0, 1, 2, 3, 4]);
foreach(i, elem; poolInstance.parallel(range))
{
nums[i] = cast(uint) i;
}
assert(nums == [0,1,2,3,4]);
auto logs = new double[1_000_000];
foreach(i, ref elem; poolInstance.parallel(logs))
{
elem = log(i + 1.0);
}
foreach(i, elem; logs)
{
assert(approxEqual(elem, cast(double) log(i + 1)));
}
assert(poolInstance.amap!"a * a"([1,2,3,4,5]) == [1,4,9,16,25]);
assert(poolInstance.amap!"a * a"([1,2,3,4,5], new long[5]) == [1,4,9,16,25]);
assert(poolInstance.amap!("a * a", "-a")([1,2,3]) ==
[tuple(1, -1), tuple(4, -2), tuple(9, -3)]);
auto tupleBuf = new Tuple!(int, int)[3];
poolInstance.amap!("a * a", "-a")([1,2,3], tupleBuf);
assert(tupleBuf == [tuple(1, -1), tuple(4, -2), tuple(9, -3)]);
poolInstance.amap!("a * a", "-a")([1,2,3], 5, tupleBuf);
assert(tupleBuf == [tuple(1, -1), tuple(4, -2), tuple(9, -3)]);
// Test amap with a non-array buffer.
auto toIndex = new int[5];
auto indexed = std.range.indexed(toIndex, [3, 1, 4, 0, 2]);
poolInstance.amap!"a * 2"([1, 2, 3, 4, 5], indexed);
assert(equal(indexed, [2, 4, 6, 8, 10]));
assert(equal(toIndex, [8, 4, 10, 2, 6]));
poolInstance.amap!"a / 2"(indexed, indexed);
assert(equal(indexed, [1, 2, 3, 4, 5]));
assert(equal(toIndex, [4, 2, 5, 1, 3]));
auto buf = new int[5];
poolInstance.amap!"a * a"([1,2,3,4,5], buf);
assert(buf == [1,4,9,16,25]);
poolInstance.amap!"a * a"([1,2,3,4,5], 4, buf);
assert(buf == [1,4,9,16,25]);
assert(poolInstance.reduce!"a + b"([1]) == 1);
assert(poolInstance.reduce!"a + b"([1,2,3,4]) == 10);
assert(poolInstance.reduce!"a + b"(0.0, [1,2,3,4]) == 10);
assert(poolInstance.reduce!"a + b"(0.0, [1,2,3,4], 1) == 10);
assert(poolInstance.reduce!(min, max)([1,2,3,4]) == tuple(1, 4));
assert(poolInstance.reduce!("a + b", "a * b")(tuple(0, 1), [1,2,3,4]) ==
tuple(10, 24));
immutable serialAns = std.algorithm.reduce!"a + b"(iota(1000));
assert(poolInstance.reduce!"a + b"(0, iota(1000)) == serialAns);
assert(poolInstance.reduce!"a + b"(iota(1000)) == serialAns);
// Test worker-local storage.
auto wl = poolInstance.workerLocalStorage(0);
foreach(i; poolInstance.parallel(iota(1000), 1))
{
wl.get = wl.get + i;
}
auto wlRange = wl.toRange;
auto parallelSum = poolInstance.reduce!"a + b"(wlRange);
assert(parallelSum == 499500);
assert(wlRange[0..1][0] == wlRange[0]);
assert(wlRange[1..2][0] == wlRange[1]);
// Test finish()
{
static void slowFun() { Thread.sleep(dur!"msecs"(1)); }
auto pool1 = new TaskPool();
auto tSlow = task!slowFun();
pool1.put(tSlow);
pool1.finish();
tSlow.yieldForce();
// Can't assert that pool1.status == PoolState.stopNow because status
// doesn't change until after the "done" flag is set and the waiting
// thread is woken up.
auto pool2 = new TaskPool();
auto tSlow2 = task!slowFun();
pool2.put(tSlow2);
pool2.finish(true); // blocking
assert(tSlow2.done);
// Test fix for Bug 8582 by making pool size zero.
auto pool3 = new TaskPool(0);
auto tSlow3 = task!slowFun();
pool3.put(tSlow3);
pool3.finish(true); // blocking
assert(tSlow3.done);
// This is correct because no thread will terminate unless pool2.status
// and pool3.status have already been set to stopNow.
assert(pool2.status == TaskPool.PoolState.stopNow);
assert(pool3.status == TaskPool.PoolState.stopNow);
}
// Test default pool stuff.
assert(taskPool.size == totalCPUs - 1);
nums = new uint[1000];
foreach(i; parallel(iota(1000)))
{
nums[i] = cast(uint) i;
}
assert(equal(nums, iota(1000)));
assert(equal(
poolInstance.map!"a * a"(iota(30_000_001), 10_000),
std.algorithm.map!"a * a"(iota(30_000_001))
));
// The filter is to kill random access and test the non-random access
// branch.
assert(equal(
poolInstance.map!"a * a"(
filter!"a == a"(iota(30_000_001)
), 10_000, 1000),
std.algorithm.map!"a * a"(iota(30_000_001))
));
assert(
reduce!"a + b"(0UL,
poolInstance.map!"a * a"(iota(3_000_001), 10_000)
) ==
reduce!"a + b"(0UL,
std.algorithm.map!"a * a"(iota(3_000_001))
)
);
assert(equal(
iota(1_000_002),
poolInstance.asyncBuf(filter!"a == a"(iota(1_000_002)))
));
{
auto file = File("tempDelMe.txt", "wb");
scope(exit)
{
file.close();
import std.file;
remove("tempDelMe.txt");
}
auto written = [[1.0, 2, 3], [4.0, 5, 6], [7.0, 8, 9]];
foreach(row; written)
{
file.writeln(join(to!(string[])(row), "\t"));
}
file = File("tempDelMe.txt");
void next(ref char[] buf)
{
file.readln(buf);
import std.string;
buf = chomp(buf);
}
double[][] read;
auto asyncReader = taskPool.asyncBuf(&next, &file.eof);
foreach(line; asyncReader)
{
if(line.length == 0) continue;
auto ls = line.split("\t");
read ~= to!(double[])(ls);
}
assert(read == written);
file.close();
}
// Test Map/AsyncBuf chaining.
auto abuf = poolInstance.asyncBuf(iota(-1.0, 3_000_000), 100);
auto temp = poolInstance.map!sqrt(
abuf, 100, 5
);
auto lmchain = poolInstance.map!"a * a"(temp, 100, 5);
lmchain.popFront();
int ii;
foreach( elem; (lmchain))
{
if(!approxEqual(elem, ii))
{
stderr.writeln(ii, '\t', elem);
}
ii++;
}
// Test buffer trick in parallel foreach.
abuf = poolInstance.asyncBuf(iota(-1.0, 1_000_000), 100);
abuf.popFront();
auto bufTrickTest = new size_t[abuf.length];
foreach(i, elem; parallel(abuf))
{
bufTrickTest[i] = i;
}
assert(equal(iota(1_000_000), bufTrickTest));
auto myTask = task!(std.math.abs)(-1);
taskPool.put(myTask);
assert(myTask.spinForce == 1);
// Test that worker local storage from one pool receives an index of 0
// when the index is queried w.r.t. another pool. The only way to do this
// is non-deterministically.
foreach(i; parallel(iota(1000), 1))
{
assert(poolInstance.workerIndex == 0);
}
foreach(i; poolInstance.parallel(iota(1000), 1))
{
assert(taskPool.workerIndex == 0);
}
// Test exception handling.
static void parallelForeachThrow()
{
foreach(elem; parallel(iota(10)))
{
throw new Exception("");
}
}
assertThrown!Exception(parallelForeachThrow());
static int reduceException(int a, int b)
{
throw new Exception("");
}
assertThrown!Exception(
poolInstance.reduce!reduceException(iota(3))
);
static int mapException(int a)
{
throw new Exception("");
}
assertThrown!Exception(
poolInstance.amap!mapException(iota(3))
);
static void mapThrow()
{
auto m = poolInstance.map!mapException(iota(3));
m.popFront();
}
assertThrown!Exception(mapThrow());
struct ThrowingRange
{
@property int front()
{
return 1;
}
void popFront()
{
throw new Exception("");
}
enum bool empty = false;
}
assertThrown!Exception(poolInstance.asyncBuf(ThrowingRange.init));
}
//version = parallelismStressTest;
// These are more like stress tests than real unit tests. They print out
// tons of stuff and should not be run every time make unittest is run.
version(parallelismStressTest)
{
unittest
{
size_t attempt;
for(; attempt < 10; attempt++)
foreach(poolSize; [0, 4])
{
poolInstance = new TaskPool(poolSize);
uint[] numbers = new uint[1_000];
foreach(i; poolInstance.parallel( iota(0, numbers.length)) )
{
numbers[i] = cast(uint) i;
}
// Make sure it works.
foreach(i; 0..numbers.length)
{
assert(numbers[i] == i);
}
stderr.writeln("Done creating nums.");
auto myNumbers = filter!"a % 7 > 0"( iota(0, 1000));
foreach(num; poolInstance.parallel(myNumbers))
{
assert(num % 7 > 0 && num < 1000);
}
stderr.writeln("Done modulus test.");
uint[] squares = poolInstance.amap!"a * a"(numbers, 100);
assert(squares.length == numbers.length);
foreach(i, number; numbers)
{
assert(squares[i] == number * number);
}
stderr.writeln("Done squares.");
auto sumFuture = task!( reduce!"a + b" )(numbers);
poolInstance.put(sumFuture);
ulong sumSquares = 0;
foreach(elem; numbers)
{
sumSquares += elem * elem;
}
uint mySum = sumFuture.spinForce();
assert(mySum == 999 * 1000 / 2);
auto mySumParallel = poolInstance.reduce!"a + b"(numbers);
assert(mySum == mySumParallel);
stderr.writeln("Done sums.");
auto myTask = task(
{
synchronized writeln("Our lives are parallel...Our lives are parallel.");
});
poolInstance.put(myTask);
auto nestedOuter = "abcd";
auto nestedInner = iota(0, 10, 2);
foreach(i, letter; poolInstance.parallel(nestedOuter, 1))
{
foreach(j, number; poolInstance.parallel(nestedInner, 1))
{
synchronized writeln(i, ": ", letter, " ", j, ": ", number);
}
}
poolInstance.stop();
}
assert(attempt == 10);
writeln("Press enter to go to next round of unittests.");
readln();
}
// These unittests are intended more for actual testing and not so much
// as examples.
unittest
{
foreach(attempt; 0..10)
foreach(poolSize; [0, 4])
{
poolInstance = new TaskPool(poolSize);
// Test indexing.
stderr.writeln("Creator Raw Index: ", poolInstance.threadIndex);
assert(poolInstance.workerIndex() == 0);
// Test worker-local storage.
auto workerLocalStorage = poolInstance.workerLocalStorage!uint(1);
foreach(i; poolInstance.parallel(iota(0U, 1_000_000)))
{
workerLocalStorage.get++;
}
assert(reduce!"a + b"(workerLocalStorage.toRange) ==
1_000_000 + poolInstance.size + 1);
// Make sure work is reasonably balanced among threads. This test is
// non-deterministic and is more of a sanity check than something that
// has an absolute pass/fail.
shared(uint)[void*] nJobsByThread;
foreach(thread; poolInstance.pool)
{
nJobsByThread[cast(void*) thread] = 0;
}
nJobsByThread[ cast(void*) Thread.getThis()] = 0;
foreach(i; poolInstance.parallel( iota(0, 1_000_000), 100 ))
{
atomicOp!"+="( nJobsByThread[ cast(void*) Thread.getThis() ], 1);
}
stderr.writeln("\nCurrent thread is: ",
cast(void*) Thread.getThis());
stderr.writeln("Workload distribution: ");
foreach(k, v; nJobsByThread)
{
stderr.writeln(k, '\t', v);
}
// Test whether amap can be nested.
real[][] matrix = new real[][](1000, 1000);
foreach(i; poolInstance.parallel( iota(0, matrix.length) ))
{
foreach(j; poolInstance.parallel( iota(0, matrix[0].length) ))
{
matrix[i][j] = i * j;
}
}
// Get around weird bugs having to do w/ sqrt being an intrinsic:
static real mySqrt(real num)
{
return sqrt(num);
}
static real[] parallelSqrt(real[] nums)
{
return poolInstance.amap!mySqrt(nums);
}
real[][] sqrtMatrix = poolInstance.amap!parallelSqrt(matrix);
foreach(i, row; sqrtMatrix)
{
foreach(j, elem; row)
{
real shouldBe = sqrt( cast(real) i * j);
assert(approxEqual(shouldBe, elem));
sqrtMatrix[i][j] = shouldBe;
}
}
auto saySuccess = task(
{
stderr.writeln(
"Success doing matrix stuff that involves nested pool use.");
});
poolInstance.put(saySuccess);
saySuccess.workForce();
// A more thorough test of amap, reduce: Find the sum of the square roots of
// matrix.
static real parallelSum(real[] input)
{
return poolInstance.reduce!"a + b"(input);
}
auto sumSqrt = poolInstance.reduce!"a + b"(
poolInstance.amap!parallelSum(
sqrtMatrix
)
);
assert(approxEqual(sumSqrt, 4.437e8));
stderr.writeln("Done sum of square roots.");
// Test whether tasks work with function pointers.
auto nanTask = task(&isNaN, 1.0L);
poolInstance.put(nanTask);
assert(nanTask.spinForce == false);
if(poolInstance.size > 0)
{
// Test work waiting.
static void uselessFun()
{
foreach(i; 0..1_000_000) {}
}
auto uselessTasks = new typeof(task(&uselessFun))[1000];
foreach(ref uselessTask; uselessTasks)
{
uselessTask = task(&uselessFun);
}
foreach(ref uselessTask; uselessTasks)
{
poolInstance.put(uselessTask);
}
foreach(ref uselessTask; uselessTasks)
{
uselessTask.workForce();
}
}
// Test the case of non-random access + ref returns.
int[] nums = [1,2,3,4,5];
static struct RemoveRandom
{
int[] arr;
ref int front()
{
return arr.front;
}
void popFront()
{
arr.popFront();
}
bool empty()
{
return arr.empty;
}
}
auto refRange = RemoveRandom(nums);
foreach(ref elem; poolInstance.parallel(refRange))
{
elem++;
}
assert(nums == [2,3,4,5,6], text(nums));
stderr.writeln("Nums: ", nums);
poolInstance.stop();
}
}
}
| D |
module parser.nodes.node;
import lexer.token;
import semantic.info;
public import semantic.environment;
public import semantic.exception;
public import semantic.type;
public import semantic.value;
import std.stdio;
/**
* Represents a node of the AST.
*/
class Node
{
///The location of the node
TokenLocation location;
///Semantic info about the node
SemanticInfo semInfo;
/**
* Constructs the node.
*/
this()
{
semInfo = new SemanticInfo;
}
/**
* Writes anything with the correct number of tabs
*/
void writeTabs(T)(T arg, int tabs = 0)
{
while(tabs--)
{
write("\t");
}
write(arg);
}
/**
* Prints out a representation of a node.
* Used in debugging to make sure that precedence was matched correctly.
*/
void print(int tabs=0)
{
}
/**
* Calls a function on each node in the AST.
*/
void each(void function(ref Node) action)
{
}
/**
* Determines if a node is a Null node.
*/
bool isNull()
{
return false;
}
/*
* The following method deal with semantic stuff:
* void analyzeVariables() -- does semantic analysis on variables
* bool isLvalue() -- determines if a node is an lvalue
* void addUse() -- increments the times the variable is used
*/
/**
* Analyzes variables for semantic correctness.
* See semantic analyzer for more details.
*/
void analyzeVariables(Environment e)
{
}
/**
* Determines if a node is an lvalue.
*/
bool isLvalue()
{
return false;
}
/**
* Increments the number of times a node is used.
* Used for local variables.
*/
void addUse(Environment e)
{
}
/*
* The following methods deal with optimizing stuff
* isStatic() -- determines if a node's value can be known
* at compile time
* hasEffect() -- determines whether a node has any effect
*/
/**
* Determines if a node's value can be computed at compile time.
*/
bool isStatic()
{
return false;
}
/**
* Computes the value of a node if known at compile time.
* Returns a node that can be used to replace the node being analyzed.
* Example: AddNode(NumNode, NumNode) --> SemanticValue.value.num
*/
SemanticValue computeStaticValue()
{
return null;
}
/**
* Determines if a node will have any effect.
* For example, these statements have no effect:
* 5 + 5 * 5 / 5;
* if(0) { writeln("Hello, world!"); }
*/
bool hasEffect()
{
return true;
}
} | D |
import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.typecons;
const input = [
28, 82, 77, 88, 95, 55, 62, 21, 99, 14, 30, 9, 97, 92, 94, 3, 60, 22, 18,
86,
78, 71, 61, 43, 79, 33, 65, 81, 26, 49, 47, 51, 0, 89, 57, 75, 42, 35, 80,
1,
46, 83, 39, 53, 40, 36, 54, 70, 76, 38, 50, 23, 67, 2, 20, 87, 37, 66, 84,
24,
98, 4, 7, 12, 44, 10, 29, 5, 48, 59, 32, 41, 90, 17, 56, 85, 96, 93, 27,
74,
45, 25, 15, 6, 69, 16, 19, 8, 31, 13, 64, 63, 34, 73, 58, 91, 11, 68, 72,
52
];
void main()
{
File file = File("day04.in", "r");
Board[] boards;
while (!file.eof)
{
int[][] read;
foreach (line; file.byLine().take(5))
{
read ~= line.split.map!(to!int).array;
}
boards ~= Board(read);
file.readln();
}
// Part A
playGame(input, boards.dup).writeln;
// Part B
playUntilLastGame(input, boards.dup).writeln;
}
struct Board
{
Tuple!(int, "number", bool, "marked")[5][5] board;
bool won = false;
this(int[][] input)
{
foreach (y, row; input)
{
foreach (x, cell; row)
{
this.board[y][x] = tuple(cell, false);
}
}
}
void playDrawn(int drawn)
{
foreach (y, ref row; board)
{
foreach (x, ref cell; row)
{
if (cell.number == drawn)
cell.marked = true;
}
}
}
unittest
{
Board b = Board([
[22, 13, 17, 11, 0],
[8, 2, 23, 4, 24],
[21, 9, 14, 16, 7],
[6, 10, 3, 18, 5],
[1, 12, 20, 15, 19]
]);
b.playDrawn(7);
assert(b.board[2][4].marked);
}
bool checkForWin()
{
bool result = false;
// Check for rows
foreach (row; board)
{
bool marked = true;
foreach (cell; row)
{
marked &= cell.marked;
}
if (marked)
{
result = true;
}
}
// Check columns
foreach (col; 0 .. 5)
{
bool marked = true;
foreach (row; 0 .. 5)
{
marked &= board[row][col].marked;
}
if (marked)
{
result = true;
}
}
if (result)
won = true;
return result;
}
unittest
{
Board b = Board([
[14, 21, 17, 24, 4],
[10, 16, 15, 9, 19],
[18, 8, 23, 26, 20],
[22, 11, 13, 6, 5],
[2, 0, 12, 3, 7],
]);
foreach (drawn; [7, 4, 9, 5, 11, 17, 23, 2, 0, 14, 21, 24])
{
b.playDrawn(drawn);
}
assert(b.checkForWin);
}
unittest
{
Board b = Board([
[14, 10, 18, 22, 2],
[21, 16, 8, 11, 0],
[17, 15, 23, 13, 12],
[24, 9, 26, 6, 3,],
[4, 19, 20, 5, 7]
]);
foreach (drawn; [7, 4, 9, 5, 11, 17, 23, 2, 0, 14, 21, 24])
{
b.playDrawn(drawn);
}
assert(b.checkForWin);
}
int score(int drawn)
{
int sum = 0;
foreach (row; board)
{
foreach (cell; row)
{
if (!cell.marked)
sum += cell.number;
}
}
return sum * drawn;
}
unittest
{
Board b = Board([
[14, 21, 17, 24, 4],
[10, 16, 15, 9, 19],
[18, 8, 23, 26, 20],
[22, 11, 13, 6, 5],
[2, 0, 12, 3, 7],
]);
foreach (drawn; [7, 4, 9, 5, 11, 17, 23, 2, 0, 14, 21, 24])
{
b.playDrawn(drawn);
}
assert(b.score(24) == 4512);
}
string toString() const
{
import std.string : format;
string print = "[\n";
foreach (row; board)
{
foreach (cell; row)
{
print ~= format!"%.2s%s "(cell.number, cell.marked ? 'T' : 'F');
}
print ~= "\n";
}
print ~= ']';
return print;
}
}
alias Result = Tuple!(int, "score", int, "drawn");
int playRound(int drawn, ref Board[] boards)
{
foreach (ref board; boards)
{
if (board.won)
continue;
board.playDrawn(drawn);
if (board.checkForWin())
{
return board.score(drawn);
}
}
return 0;
}
Result playGame(in int[] numbers, Board[] boards)
{
int score = 0;
foreach (drawn; numbers)
{
score = playRound(drawn, boards);
if (score)
return Result(score, drawn);
}
return Result(0, 0);
}
unittest
{
Board[] boards = [
Board([
[22, 13, 17, 11, 0],
[8, 2, 23, 4, 24],
[21, 9, 14, 16, 7],
[6, 10, 3, 18, 5],
[1, 12, 20, 15, 19]
]),
Board([
[3, 15, 0, 2, 22],
[9, 18, 13, 17, 5],
[19, 8, 7, 25, 23],
[20, 11, 10, 24, 4],
[14, 21, 16, 12, 6],
]),
Board([
[14, 21, 17, 24, 4],
[10, 16, 15, 9, 19],
[18, 8, 23, 26, 20],
[22, 11, 13, 6, 5],
[2, 0, 12, 3, 7],
])
];
const result = playGame([
7, 4, 9, 5, 11, 17, 23, 2, 0, 14, 21, 24, 10, 16, 13, 6, 15, 25, 12,
22, 18, 20, 8, 19, 3, 26, 1
], boards);
import std.string : format;
assert(result.drawn == 24, format!"Expected 4512, received: %s"(result.drawn));
assert(result.score == 4512, format!"Expected 4512, received: %s"(result.score));
}
Result playUntilLastGame(in int[] numbers, Board[] boards)
{
ulong countWon = boards.length;
foreach (drawn; numbers)
{
foreach (ref board; boards)
{
if (board.won)
continue;
board.playDrawn(drawn);
if (board.checkForWin())
{
--countWon;
if (countWon == 0)
return Result(board.score(drawn), drawn);
}
}
}
return Result(0, 0);
}
unittest
{
Board[] boards = [
Board([
[22, 13, 17, 11, 0],
[8, 2, 23, 4, 24],
[21, 9, 14, 16, 7],
[6, 10, 3, 18, 5],
[1, 12, 20, 15, 19]
]),
Board([
[3, 15, 0, 2, 22],
[9, 18, 13, 17, 5],
[19, 8, 7, 25, 23],
[20, 11, 10, 24, 4],
[14, 21, 16, 12, 6],
]),
Board([
[14, 21, 17, 24, 4],
[10, 16, 15, 9, 19],
[18, 8, 23, 26, 20],
[22, 11, 13, 6, 5],
[2, 0, 12, 3, 7],
])
];
const result = playUntilLastGame([
7, 4, 9, 5, 11, 17, 23, 2, 0, 14, 21, 24, 10, 16, 13, 6, 15, 25, 12, 22,
18, 20, 8, 19, 3, 26, 1
], boards);
import std.string : format;
assert(result.drawn == 13, format!"Expected 13, received: %s"(result.drawn));
assert(result.score == 1924, format!"Expected 1924, received: %s"(result.score));
}
| D |
CSYTRI (F07NWE) Example Program Data
4 :Value of N
'L' :Value of UPLO
(-0.39,-0.71)
( 5.14,-0.64) ( 8.86, 1.81)
(-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12) :End of matrix A
| D |
/Users/darius/Documents/xcode/Uzduotis/build/Uzduotis.build/Debug-iphonesimulator/Uzduotis.build/Objects-normal/x86_64/AppDelegate.o : /Users/darius/Documents/xcode/Uzduotis/Uzduotis/Seniunijos+CoreDataProperties.swift /Users/darius/Documents/xcode/Uzduotis/Uzduotis/DataTableViewController.swift /Users/darius/Documents/xcode/Uzduotis/Uzduotis/Seniunijos.swift /Users/darius/Documents/xcode/Uzduotis/Uzduotis/Duomenys.swift /Users/darius/Documents/xcode/Uzduotis/Uzduotis/Duomenys+CoreDataProperties.swift /Users/darius/Documents/xcode/Uzduotis/Uzduotis/AppDelegate.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreData.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule
/Users/darius/Documents/xcode/Uzduotis/build/Uzduotis.build/Debug-iphonesimulator/Uzduotis.build/Objects-normal/x86_64/AppDelegate~partial.swiftmodule : /Users/darius/Documents/xcode/Uzduotis/Uzduotis/Seniunijos+CoreDataProperties.swift /Users/darius/Documents/xcode/Uzduotis/Uzduotis/DataTableViewController.swift /Users/darius/Documents/xcode/Uzduotis/Uzduotis/Seniunijos.swift /Users/darius/Documents/xcode/Uzduotis/Uzduotis/Duomenys.swift /Users/darius/Documents/xcode/Uzduotis/Uzduotis/Duomenys+CoreDataProperties.swift /Users/darius/Documents/xcode/Uzduotis/Uzduotis/AppDelegate.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreData.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule
/Users/darius/Documents/xcode/Uzduotis/build/Uzduotis.build/Debug-iphonesimulator/Uzduotis.build/Objects-normal/x86_64/AppDelegate~partial.swiftdoc : /Users/darius/Documents/xcode/Uzduotis/Uzduotis/Seniunijos+CoreDataProperties.swift /Users/darius/Documents/xcode/Uzduotis/Uzduotis/DataTableViewController.swift /Users/darius/Documents/xcode/Uzduotis/Uzduotis/Seniunijos.swift /Users/darius/Documents/xcode/Uzduotis/Uzduotis/Duomenys.swift /Users/darius/Documents/xcode/Uzduotis/Uzduotis/Duomenys+CoreDataProperties.swift /Users/darius/Documents/xcode/Uzduotis/Uzduotis/AppDelegate.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreData.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule
| D |
module android.java.android.view.View_OnContextClickListener;
public import android.java.android.view.View_OnContextClickListener_d_interface;
import arsd.jni : ImportExportImpl;
mixin ImportExportImpl!View_OnContextClickListener;
import import1 = android.java.java.lang.Class;
| D |
// **************************************
// EXIT
// **************************************
instance DIA_Bartholo_Exit (C_INFO)
{
npc = EBR_106_Bartholo;
nr = 999;
condition = DIA_Bartholo_Exit_Condition;
information = DIA_Bartholo_Exit_Info;
permanent = 1;
description = DIALOG_ENDE;
};
FUNC int DIA_Bartholo_Exit_Condition()
{
return 1;
};
FUNC VOID DIA_Bartholo_Exit_Info()
{
AI_StopProcessInfos (self);
};
// ************************************************************
// HAllo
// ************************************************************
INSTANCE Info_Bartholo_HAllo (C_INFO)
{
npc = EBR_106_Bartholo;
nr = 4;
condition = Info_Bartholo_HAllo_Condition;
information = Info_Bartholo_HAllo_Info;
permanent = 0;
description = "Wer bist du?";
};
FUNC INT Info_Bartholo_HAllo_Condition()
{
return 1;
};
FUNC VOID Info_Bartholo_HAllo_Info()
{
AI_Output (other, self,"Info_Bartholo_HAllo_15_00"); //Wer bist du?
AI_Output (self, other,"Info_Bartholo_HAllo_12_01"); //Ich bin Bartholo. Ich kümmere mich um die Versorgung der Erzbarone.
AI_Output (self, other,"Info_Bartholo_HAllo_12_02"); //Ich regele alles - von Krautlieferungen, über Essen bis hin zur Versorgung der Frauen.
AI_Output (self, other,"Info_Bartholo_HAllo_12_03"); //Außerdem sorge ich dafür, dass die beiden idiotischen Köche ihre Arbeit gut machen.
AI_Output (self, other,"Info_Bartholo_HAllo_12_04"); //Sie sollten mir dafür dankbar sein. Gomez lässt sich nicht jeden Fraß gefallen. Die letzten beiden hat er an die Snapper im Fluss verfüttert.
};
// ************************************************************
// PERM TRADE
// ************************************************************
INSTANCE Info_Bartholo_PERM (C_INFO)
{
npc = EBR_106_Bartholo;
nr = 4;
condition = Info_Bartholo_PERM_Condition;
information = Info_Bartholo_PERM_Info;
permanent = 0;
description = "Ich will mit dir handeln.";
Trade = 1;
};
FUNC INT Info_Bartholo_PERM_Condition()
{
//SN: Problematisch, da Bartholo auch einen wichtigen Schlüssel hat!
// if (Npc_KnowsInfo(hero, Info_Bartholo_Hallo))
// {
// return 1;
// };
};
FUNC VOID Info_Bartholo_PERM_Info()
{
AI_Output (other, self,"Info_Bartholo_PERM_15_00"); //Ich will mit dir handeln.
AI_Output (self, other,"Info_Bartholo_PERM_12_01"); //Ich habe einiges da - wenn du genug Erz hast.
};
// ************************************************************
// KRAUTBOTE von Kalom
// ************************************************************
INSTANCE Info_Bartholo_Krautbote (C_INFO)
{
npc = EBR_106_Bartholo;
nr = 4;
condition = Info_Bartholo_Krautbote_Condition;
information = Info_Bartholo_Krautbote_Info;
permanent = 1;
description = "Ich habe ne Ladung Kraut von Cor Kalom für Gomez.";
};
FUNC INT Info_Bartholo_Krautbote_Condition()
{
if (Kalom_Krautbote == LOG_RUNNING)
{
return 1;
};
};
FUNC VOID Info_Bartholo_Krautbote_Info()
{
AI_Output (other, self,"Info_Bartholo_Krautbote_15_00"); //Ich habe 'ne Ladung Kraut von Cor Kalom für Gomez.
AI_Output (self, other,"Info_Bartholo_Krautbote_12_01"); //Zeig her!
if (Npc_HasItems(other, itmijoint_3) >= 30)
{
AI_Output (self, other,"Info_Bartholo_Krautbote_12_02"); //Hmmmmmmm ...
AI_Output (self, other,"Info_Bartholo_Krautbote_12_03"); //Gut! Gomez ist beinahe ungeduldig geworden. Sei froh, dass du es heute noch abgeliefert hast!
AI_Output (other, self,"Info_Bartholo_Krautbote_15_04"); //Was ist mit der Bezahlung?
AI_Output (self, other,"Info_Bartholo_Krautbote_12_05"); //Nicht so eilig ... Hier, nimm. 500 Erz waren abgemacht.
B_GiveInvItems (other, self, itmijoint_3, 30);
CreateInvItems (self, itminugget, 500);
B_GiveInvItems (self, other, itminugget, 500);
Kalom_DeliveredWeed = TRUE;
B_LogEntry (CH1_KrautBote, "Bartholo hat mir 500 Erz für die Krautlieferung gegeben.");
B_GiveXP (XP_WeedShipmentDelivered);
Info_Bartholo_Krautbote.permanent = 0;
}
else
{
AI_Output (self, other,"Info_Bartholo_Krautbote_NoKraut_12_00"); //Du hast zu wenig Kraut für einen Boten! Ich will für dich nicht hoffen, dass du das Zeug verscherbelt hast! Komm wieder, wenn du die richtige Menge dabei hast!
};
};
// **************************************************************************
// Wartet auf den SC
// **************************************************************************
instance DIA_EBR_106_Bartholo_Wait4SC (C_INFO)
{
npc = EBR_106_Bartholo;
condition = DIA_EBR_106_Bartholo_Wait4SC_Condition;
information = DIA_EBR_106_Bartholo_Wait4SC_Info;
important = 1;
permanent = 0;
};
FUNC int DIA_EBR_106_Bartholo_Wait4SC_Condition()
{
if ExploreSunkenTower
{
return TRUE;
};
};
FUNC void DIA_EBR_106_Bartholo_Wait4SC_Info()
{
AI_SetWalkmode (self, NPC_WALK);
AI_GotoNpc (self, other);
AI_Output (self, other,"Info_Bartholo_12_01"); //Ich hatte mir fast gedacht, dass es jemand durch das Pentagramm versuchen würde!
AI_Output (self, other,"Info_Bartholo_12_02"); //Aber im Gegensatz zu diesem verräterischen Schmied Stone brauchen wir dich nicht mehr!
AI_Output (other, self,"Info_Bartholo_15_03"); //Wo ist Stone?
AI_Output (self, other,"Info_Bartholo_12_04"); //Hinter Gittern! Aber dafür wirst du gleich unter der Erde liegen!
AI_Output (self, other,"Info_Bartholo_12_05"); //Schnappt ihn euch, Jungs, und macht ihn kalt!
AI_StopProcessInfos (self);
self.guild = GIL_EBR;
Npc_SetTrueGuild (self, GIL_EBR);
};
| D |
@compute(CompileFor.hostAndDevice) module dcompute.std.index;
import ldc.attributes;
import dcompute.reflect;
private import ocl = dcompute.std.opencl.index;
private import cuda = dcompute.std.cuda.index;
/*
Index Terminology
DCompute CUDA OpenCL
GlobalDimension.xyz gridDim*blockDim get_global_size()
GlobalIndex.xyz blockDim*blockIdx+threadIdx get_global_id()
GroupDimension.zyx gridDim get_num_groups()
GroupIndex.xyz blockIdx get_group_id()
SharedDimension.xyz blockDim get_local_size()
SharedIndex.xyz threadIdx get_local_id()
GlobalIndex.linear A nasty calcualion get_global_linear_id()
SharedIndex.linear Ditto get_local_linear_id()
Notes:
*Index.{x,y,z} are bounded by *Dimension.{x,y,z}
Use SharedIndex's to index Shared Memory and GlobalIndex's to index Global Memory
A Group is the ratio of Global to Shared. GroupDimension is NOT the size of a single
group, (thats SharedDimension) rather it is the number of groups along e.g
the x dimension. Similarly GroupIndex is how many units of the SharedDimension along
a given dimension is.
By default *Index.linear is the linearisation of 3D memory. Use *Index.linear!N where
N is 1, 2 or 3 to use a linearisation of ND memory (for e.g. efficiency/documentation).
*/
pure: nothrow: @nogc:
struct GlobalDimension
{
pragma(inline,true);
@property static size_t x()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_global_size(0);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.ntid_x()*cuda.nctaid_x();
else
assert(0);
}
pragma(inline,true);
@property static size_t y()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_global_size(1);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.ntid_y()*cuda.nctaid_y();
else
assert(0);
}
pragma(inline,true);
@property static size_t z()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_global_size(2);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.ntid_z()*cuda.nctaid_z();
else
assert(0);
}
}
struct GlobalIndex
{
pragma(inline,true);
@property static size_t x()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_global_id(0);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.ctaid_x()*cuda.ntid_x() + cuda.tid_x();
else
assert(0);
}
pragma(inline,true);
@property static size_t y()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_global_id(1);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.ctaid_y()*cuda.ntid_y() + cuda.tid_y();
else
assert(0);
}
pragma(inline,true);
@property static size_t z()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_global_id(2);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.ctaid_z()*cuda.ntid_z() + cuda.tid_z();
else
assert(0);
}
pragma(inline,true);
@property static size_t linearImpl(int dim = 3)()
if(dim >= 1 && dim <= 3)
{
static if (dim == 3)
return (z * GlobalDimension.y * GlobalDimension.x) +
(y * GlobalDimension.x) + x;
else static if (dim == 2)
return (y * GlobalDimension.x) + x;
else
return x;
}
pragma(inline,true);
@property static size_t linear(int dim = 3)() if(dim >= 1 && dim <= 3)
{
//Foward to the intrinsic to help memoisation for the comsumer.
if(__dcompute_reflect(target.OpenCL,200))
return ocl.get_global_linear_id();
else if(__dcompute_reflect(target.OpenCL,210))
return ocl.get_global_linear_id();
else if(__dcompute_reflect(target.OpenCL,220))
return ocl.get_global_linear_id();
else
return linearImpl!dim;
}
}
struct GroupDimension
{
pragma(inline,true);
@property static size_t x()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_num_groups(0);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.nctaid_x();
else
assert(0);
}
pragma(inline,true);
@property static size_t y()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_num_groups(1);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.nctaid_y();
else
assert(0);
}
pragma(inline,true);
@property static size_t z()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_num_groups(2);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.nctaid_z();
else
assert(0);
}
}
struct GroupIndex
{
pragma(inline,true);
@property static size_t x()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_group_id(0);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.ntid_x();
else
assert(0);
}
pragma(inline,true);
@property static size_t y()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_group_id(1);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.ntid_y();
else
assert(0);
}
pragma(inline,true);
@property static size_t z()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_group_id(2);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.ntid_z();
else
assert(0);
}
}
struct SharedDimension
{
pragma(inline,true);
@property static size_t x()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_local_size(0);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.ntid_x();
else
assert(0);
}
pragma(inline,true);
@property static size_t y()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_local_size(1);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.ntid_y();
else
assert(0);
}
pragma(inline,true);
@property static size_t z()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_local_size(2);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.ntid_z();
else
assert(0);
}
}
struct SharedIndex
{
pragma(inline,true);
@property static size_t x()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_local_id(0);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.tid_x();
else
assert(0);
}
pragma(inline,true);
@property static size_t y()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_local_id(1);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.tid_y();
else
assert(0);
}
pragma(inline,true);
@property static size_t z()()
{
if(__dcompute_reflect(ReflectTarget.OpenCL,0))
return ocl.get_local_id(2);
else if(__dcompute_reflect(ReflectTarget.CUDA,0))
return cuda.tid_z();
else
assert(0);
}
pragma(inline,true);
@property static size_t linearImpl(int dim = 3)()
if(dim >= 1 && dim <= 3)
{
static if (dim == 3)
return (z * SharedDimension.y * SharedDimension.x) +
(y * SharedDimension.x) + x;
else static if (dim == 2)
return (y * SharedDimension.x) + x;
else
return x;
}
pragma(inline,true);
@property static size_t linear(int dim = 3)() if(dim >= 1 && dim <= 3)
{
//Foward to the intrinsic to help memoisation for the comsumer.
if(__dcompute_reflect(ReflectTarget.OpenCL,200))
return ocl.get_local_linear_id();
else if(__dcompute_reflect(ReflectTarget.OpenCL,210))
return ocl.get_local_linear_id();
else if(__dcompute_reflect(ReflectTarget.OpenCL,220))
return ocl.get_local_linear_id();
else
return linearImpl!dim;
}
}
| D |
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Port to the D programming language:
* Frank Benoit <benoit@tionex.de>
*******************************************************************************/
module dwt.internal.SerializableCompatibility;
//import java.io.Serializable;
///PORTING_TYPE
interface Serializable{}
/**
* This interface is the cross-platform version of the
* java.io.Serializable interface.
* <p>
* It is part of our effort to provide support for both J2SE
* and J2ME platforms. Under this scheme, classes need to
* implement SerializableCompatibility instead of
* java.io.Serializable.
* </p>
* <p>
* Note: java.io.Serializable is not part of CLDC.
* </p>
*/
public interface SerializableCompatibility :
Serializable
{
}
| D |
/*
* Copyright (c) 2004-2008 Derelict Developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the names 'Derelict', 'DerelictGL', nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
module derelict.opengl.extension.ati.pn_triangles;
private
{
import derelict.opengl.gltypes;
import derelict.opengl.gl;
import derelict.opengl.extension.loader;
import derelict.util.wrapper;
}
private bool enabled = false;
struct ATIPnTriangles
{
static bool load(char[] extString)
{
if(extString.findStr("GL_ATI_pn_triangles") == -1)
return false;
if(!glBindExtFunc(cast(void**)&glPNTrianglesiATI, "glPNTrianglesiATI"))
return false;
if(!glBindExtFunc(cast(void**)&glPNTrianglesfATI, "glPNTrianglesfATI"))
return false;
enabled = true;
return true;
}
static bool isEnabled()
{
return enabled;
}
}
version(DerelictGL_NoExtensionLoaders)
{
}
else
{
static this()
{
DerelictGL.registerExtensionLoader(&ATIPnTriangles.load);
}
}
enum : GLenum
{
GL_PN_TRIANGLES_ATI = 0x87F0,
GL_MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATI = 0x87F1,
GL_PN_TRIANGLES_POINT_MODE_ATI = 0x87F2,
GL_PN_TRIANGLES_NORMAL_MODE_ATI = 0x87F3,
GL_PN_TRIANGLES_TESSELATION_LEVEL_ATI = 0x87F4,
GL_PN_TRIANGLES_POINT_MODE_LINEAR_ATI = 0x87F5,
GL_PN_TRIANGLES_POINT_MODE_CUBIC_ATI = 0x87F6,
GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI = 0x87F7,
GL_PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATI = 0x87F8,
}
extern(System):
typedef void function(GLenum, GLint) pfglPNTrianglesiATI;
typedef void function(GLenum, GLfloat) pfglPNTrianglesfATI;
pfglPNTrianglesiATI glPNTrianglesiATI;
pfglPNTrianglesfATI glPNTrianglesfATI;
| D |
module ttgl.graphics.window;
import core.memory: GC;
import std.array;
import std.conv;
import std.signals;
import std.stdio;
import std.string : chop, _0 = toStringz, format;
import std.traits;
import glfw.glfw3;
import derelict.opengl3.gl3;
version(Posix) {
import
X11.Xutil,
glfw.glfw3native;
}
import ttgl.global;
class Window
{
enum CursorMode {
NORMAL = GLFW_CURSOR_NORMAL,
HIDDEN = GLFW_CURSOR_HIDDEN,
DISABLED = GLFW_CURSOR_DISABLED
}
struct Size {
int width, height;
}
struct Config {
bool resizable = true;
bool visible = true;
bool decorated = true;
struct Bits {
int
red = 8,
green = 8,
blue = 8,
alpha = 8;
int
depth = 24,
stencil = 8;
};
Bits bits;
int auxBuffers;
int samples;
int refreshRate;
Version GLversion = { major:1, minor:0 };
enum Robustness {
NONE,
NO_RESET_NOTIFICATION = GLFW_NO_RESET_NOTIFICATION,
LOSE_CONTEXT_ON_RESET = GLFW_LOSE_CONTEXT_ON_RESET
};
Robustness GLrobustness = Robustness.NONE;
enum Profile {
ANY,
CORE = GLFW_OPENGL_CORE_PROFILE,
COMPAT = GLFW_OPENGL_COMPAT_PROFILE
}
Profile GLprofile = Profile.ANY;
bool forwarded = false;
bool debuging = false;
CursorMode cursorMode = CursorMode.DISABLED;
}
this(int width, int height, in string title, in Config cfg = Config()) {
Size s = { width, height };
this(s, title, cfg);
}
this(in Size size, in string title, in Config cfg = Config()) {
if(!windows) {
if(!glfwInit()) {
throw new WindowException(error.msg, null);
}
}
this.title = title;
this.size = size;
this.cfg = cfg;
// You stay where you are!
GC.setAttr(cast(void*)this, GC.BlkAttr.NO_MOVE);
windows++;
}
~this() {
close();
GC.clrAttr(cast(void*)this, GC.BlkAttr.NO_MOVE);
if(--windows == 0) glfwTerminate();
}
@property {
void title(in string title) {
if(!window) return;
title_ = title;
glfwSetWindowTitle(window, title._0);
}
string title() {
return title_;
}
}
@property {
bool visible() {
return window && glfwGetWindowAttrib(window, GLFW_VISIBLE);
}
void visible(bool flag) {
cfg.visible = flag;
if(!window) return;
if(flag)
glfwShowWindow(window);
else
glfwHideWindow(window);
}
}
@property {
CursorMode cursorMode() {
return cast(CursorMode) glfwGetInputMode(window, GLFW_CURSOR);
}
void cursorMode(CursorMode mode) {
glfwSetInputMode(window, GLFW_CURSOR, mode);
}
}
void open(bool fullscreen = false) {
setHints(cfg);
GLFWmonitor* primary = null;
if(fullscreen)
primary = glfwGetPrimaryMonitor();
// Just getting some living space here
window = glfwCreateWindow(size.width, size.height, title._0, primary, null);
if(!window)
throw new WindowException(error.msg, null); //TODO: Build some kind of recovery
glfwSetWindowUserPointer(window, cast(void*)this);
glfwSetWindowSizeCallback(window, &winSizeCB);
glfwSetKeyCallback(window, &keyCB);
glfwSetMouseButtonCallback(window, &mouseBtnCB);
glfwSetCursorPosCallback(window, &cursorPosCB);
// Set X class hint
{
version(Posix) {
XClassHint xch = {
res_name: "gl", // aka instance
res_class: APPNAME
};
XSetClassHint(glfwGetX11Display(), glfwGetX11Window(window), &xch);
}
}
// OpenGL = on
bindContext();
// Catch cursor
cursorMode = cfg.cursorMode;
}
bool isOpen() {
return window && !glfwWindowShouldClose(window);
}
void close() {
if(window) {
glfwSetWindowUserPointer(window, null);
glfwDestroyWindow(window);
window = null;
}
}
void bindContext() {
glfwMakeContextCurrent(window);
}
void present() {
glfwSwapBuffers(window);
}
@property
void presentInterval(int iv) {
glfwSwapInterval(iv);
}
Size getSize() {
Size size;
glfwGetWindowSize(window, &size.width, &size.height);
return size;
}
static void pollEvents() {
glfwPollEvents();
}
void delegate(int,int) onWindowMove;
void delegate(int,int) onWindowResize;
void delegate() onWindowClose;
void delegate() onWindowRefresh;
void delegate(bool) onWindowFocus;
void delegate(bool) onWindowIconify;
void delegate(int,int) onFramebufferResize;
void delegate(int,int,int) onMouseButton;
void delegate(double,double) onCursorMove;
void delegate(int) onCursorEnter;
void delegate(double,double) onScroll;
void delegate(int,int,int,int) onKey;
void delegate(dchar) onChar;
void delegate(int) onMonitorStatus;
private:
GLFWwindow* window;
string title_;
Size size;
Config cfg;
static this() {
glfwSetErrorCallback(&glfwError_cb);
// Getting current OpenGL version for a more precise window creation
if(!glfwInit()) {
throw new WindowException(error.msg, null);
}
scope(exit) glfwTerminate();
// Spawn our silent spy!
glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
GLFWwindow* test = glfwCreateWindow(13, 37, (APPNAME ~ " - GL Test!")._0, null, null);
if(!test) throw new WindowException(error.msg, null);
glfwDefaultWindowHints();
scope(exit) glfwDestroyWindow(test);
// Lets load all default symbols
DerelictGL3.load();
// OpenGL = on
glfwMakeContextCurrent(test);
// Sometimes loading everything is just not enough
DerelictGL3.reload();
}
static GLFWError error;
static uint windows;
}
class WindowException : Exception {
const Window window;
@safe pure nothrow
this(string msg, Window win, string file = __FILE__, size_t line = __LINE__) {
this(msg, win, null, file, line);
}
@safe pure nothrow
this(string msg, Window win, Throwable next, string file = __FILE__, size_t line = __LINE__) {
super(msg, file, line, next);
window = win;
}
}
private:
struct GLFWError {
int code;
string msg;
}
extern(C)
void glfwError_cb(int code, const(char)* msg) nothrow {
import core.runtime;
try {
Window.error = GLFWError(code, text(msg));
stderr.writeln(Window.error);
stderr.writeln("Stack trace:");
stderr.writeln(defaultTraceHandler());
stderr.flush();
} catch(Throwable e) {}
}
void setHints(in Window.Config cfg) {
// Back to daylight
glfwWindowHint(GLFW_VISIBLE, cfg.visible);
glfwWindowHint(GLFW_RESIZABLE, cfg.resizable);
// Setting the correct context
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, cfg.GLversion.major);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, cfg.GLversion.minor);
glfwWindowHint(GLFW_OPENGL_PROFILE, cfg.GLprofile);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, cfg.forwarded);
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, cfg.debuging);
glfwWindowHint(GLFW_RED_BITS, cfg.bits.red);
glfwWindowHint(GLFW_GREEN_BITS, cfg.bits.green);
glfwWindowHint(GLFW_BLUE_BITS, cfg.bits.blue);
glfwWindowHint(GLFW_ALPHA_BITS, cfg.bits.alpha);
// Setting the accuracy of the buffers
glfwWindowHint(GLFW_DEPTH_BITS, cfg.bits.depth);
glfwWindowHint(GLFW_STENCIL_BITS, cfg.bits.stencil);
glfwWindowHint(GLFW_SAMPLES, cfg.samples);
}
Window get(GLFWwindow* w) { return cast(Window) glfwGetWindowUserPointer(w); }
extern(C) nothrow {
void keyCB(GLFWwindow* gw, int key, int scancode, int action, int mod) {
try {
Window w = get(gw);
if(w !is null && w.onKey !is null)
w.onKey(key, scancode, action, mod);
} catch (Throwable e) {}
};
void winSizeCB(GLFWwindow* gw, int width, int height) {
try {
Window w = get(gw);
if(w !is null && w.onWindowResize !is null) {
// w.width = width;
// TODO w.height = height;
w.onWindowResize(width, height);
}
} catch (Throwable e) {}
}
void cursorPosCB(GLFWwindow* gw, double x, double y) {
try {
Window w = get(gw);
if(w !is null && w.onCursorMove !is null) w.onCursorMove(x, y);
} catch (Throwable e) {}
}
void mouseBtnCB(GLFWwindow* gw, int button, int action, int mod) {
try {
Window w = get(gw);
if(w !is null && w.onMouseButton !is null) w.onMouseButton(button, action, mod);
} catch (Throwable e) {}
}
} | D |
/// vkdgen Vulkan bindings.
/// See https://github.com/rtbo/vkdgen
module vkd;
public import vkd.loader;
public import vkd.vk;
@nogc nothrow pure
{
/// Make a Vulkan version identifier
uint VK_MAKE_VERSION( uint major, uint minor, uint patch ) {
return ( major << 22 ) | ( minor << 12 ) | ( patch );
}
/// Make Vulkan-1.0 identifier
uint VK_API_VERSION_1_0() { return VK_MAKE_VERSION( 1, 0, 0 ); }
/// Make Vulkan-1.1 identifier
uint VK_API_VERSION_1_1() { return VK_MAKE_VERSION( 1, 1, 0 ); }
/// Extract major version from a Vulkan version identifier
uint VK_VERSION_MAJOR( uint ver ) { return ver >> 22; }
/// Extract minor version from a Vulkan version identifier
uint VK_VERSION_MINOR( uint ver ) { return ( ver >> 12 ) & 0x3ff; }
/// Extract patch version from a Vulkan version identifier
uint VK_VERSION_PATCH( uint ver ) { return ver & 0xfff; }
}
/// Vulkan null handle
enum VK_NULL_HANDLE = null;
version(X86_64) {
/// Vulkan non-dispatchable null handle
enum VK_NULL_ND_HANDLE = null;
}
else {
/// Vulkan non-dispatchable null handle
enum VK_NULL_ND_HANDLE = 0;
}
| D |
/home/zzy/Project/os/target/debug/deps/librustversion-229c625bef490f9d.so: /home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/lib.rs /home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/attr.rs /home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/bound.rs /home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/date.rs /home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/expr.rs /home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/time.rs /home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/version.rs /home/zzy/Project/os/target/debug/build/rustversion-364d55f376da15d5/out/version.rs
/home/zzy/Project/os/target/debug/deps/rustversion-229c625bef490f9d.d: /home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/lib.rs /home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/attr.rs /home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/bound.rs /home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/date.rs /home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/expr.rs /home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/time.rs /home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/version.rs /home/zzy/Project/os/target/debug/build/rustversion-364d55f376da15d5/out/version.rs
/home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/lib.rs:
/home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/attr.rs:
/home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/bound.rs:
/home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/date.rs:
/home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/expr.rs:
/home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/time.rs:
/home/zzy/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/rustversion-1.0.3/src/version.rs:
/home/zzy/Project/os/target/debug/build/rustversion-364d55f376da15d5/out/version.rs:
# env-dep:OUT_DIR=/home/zzy/Project/os/target/debug/build/rustversion-364d55f376da15d5/out
| D |
const int VALUE_SHELL_01 = 30;
const int VALUE_SHELL_02 = 60;
var int shell_opener;
func void b_openshell()
{
var int shellomizer;
shellomizer = Hlp_Random(100);
SHELL_OPENER = SHELL_OPENER + 1;
if(SHELL_OPENER == 1)
{
b_playerfinditem(itmi_addon_whitepearl,1);
}
else if(SHELL_OPENER == 25)
{
b_playerfinditem(itmi_darkpearl,1);
}
else if(shellomizer >= 80)
{
b_playerfinditem(itmi_addon_whitepearl,1);
}
else if(shellomizer >= 55)
{
b_playerfinditem(itfo_addon_shellflesh,1);
}
else if(shellomizer >= 50)
{
b_playerfinditem(itmi_aquamarine,1);
}
else if(shellomizer >= 40)
{
b_playerfinditem(itmi_quartz,1);
}
else if(shellomizer >= 35)
{
b_playerfinditem(itmi_rockcrystal,1);
}
else if(shellomizer >= 25)
{
b_playerfinditem(itmi_sulfur,1);
}
else
{
b_say_overlay(self,self,"$NOTHINGTOGET02");
AI_PrintScreen(PRINT_NOTHINGTOGET02,-1,YPOS_ITEMGIVEN,FONT_SCREENSMALL,2);
};
};
instance ITMI_ADDON_SHELL_01(C_ITEM)
{
name = "Škeble";
mainflag = ITEM_KAT_NONE;
flags = ITEM_MULTI;
value = VALUE_SHELL_01;
visual = "ItMi_Shell_01.3ds";
material = MAT_STONE;
scemename = "MAPSEALED";
on_state[0] = use_shell_01;
description = name;
text[5] = NAME_VALUE;
count[5] = value;
inv_zbias = INVCAM_ENTF_MISC2_STANDARD;
};
func void use_shell_01()
{
b_openshell();
};
instance ITMI_ADDON_SHELL_02(C_ITEM)
{
name = "Mušle ve tvaru rohu";
mainflag = ITEM_KAT_NONE;
flags = ITEM_MULTI;
value = VALUE_SHELL_02;
visual = "ItMi_Shell_02.3ds";
material = MAT_STONE;
scemename = "MAPSEALED";
on_state[0] = use_shell_02;
description = name;
text[5] = NAME_VALUE;
count[5] = value;
inv_zbias = INVCAM_ENTF_MISC2_STANDARD;
};
func void use_shell_02()
{
b_openshell();
};
| D |
<?xml version="1.0" encoding="ASCII" standalone="no"?>
<di:SashWindowsMngr xmlns:di="http://www.eclipse.org/papyrus/0.7.0/sashdi" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmi:version="2.0">
<pageList>
<availablePage>
<emfPageIdentifier href="VAR_20_BeT-5688974759.notation#_copSALmGEeKQQp7P9cQvNQ"/>
</availablePage>
</pageList>
<sashModel currentSelection="//@sashModel/@windows.0/@children.0">
<windows>
<children xsi:type="di:TabFolder">
<children>
<emfPageIdentifier href="VAR_20_BeT-5688974759.notation#_copSALmGEeKQQp7P9cQvNQ"/>
</children>
</children>
</windows>
</sashModel>
</di:SashWindowsMngr>
| D |
/Users/cassoutlaw/Projects/rust/TheRustProgrammingLanguage/ch4/borrowing_and_references/target/rls/debug/deps/borrowing_and_references-4579eff6b9ccdcb6.rmeta: src/main.rs
/Users/cassoutlaw/Projects/rust/TheRustProgrammingLanguage/ch4/borrowing_and_references/target/rls/debug/deps/borrowing_and_references-4579eff6b9ccdcb6.d: src/main.rs
src/main.rs:
| D |
module diesel.gl.drawable;
import std.exception;
import diesel.vec;
import diesel.gl.core;
import diesel.gl.buffer;
import diesel.gl.program;
struct Globals
{
@property static ref T[string] values(T)() {
static T[string] values;
return values;
}
static void set(T)(string name, T value) {
values!(T)[name] = value;
}
static T get(T)(string name) {
if(name in values!(T))
return values!(T)[name];
else
return T.init;
}
};
struct Rectangle {
import std.math;
static Buffer!vec2f buf;
static void draw(Program prog)
{
if(!buf) {
vec2f[] data = [ vec2f(-1, 1), vec2f(0, 0), vec2f(1, 1), vec2f(1, 0), vec2f(-1, -1), vec2f(0, 1), vec2f(1, -1), vec2f(1, 1) ];
for(int i=0; i<data.length; i+=2)
data[i] = data[i] * 0.5f;
buf = Buffer!vec2f(data, GL_ARRAY_BUFFER);
}
buf.bind();
auto uvpos = prog.getAttribLocation("in_uv");
if(uvpos >= 0)
prog.vertexAttribPointer(uvpos, 2, GL_FLOAT, GL_FALSE, 16, 8);
auto vecpos = prog.getAttribLocation("in_pos");
if(vecpos >= 0)
prog.vertexAttribPointer(vecpos, 2, GL_FLOAT, GL_FALSE, 16, 0);
check!glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
}
static void draw(SHAPE, int N)(float[N][N] matrix, Program prog = Program.basic2d)
{
enforce(.viewPort[0] >= 0);
prog.use();
prog.setUniform("in_mat", matrix);
auto color = Globals.get!uint("drawColor");
prog.setUniform("drawColor", vec4f(color));
SHAPE.draw(prog);
}
static void draw(SHAPE, int N)(SHAPE shape, float[N][N] matrix, Program prog = Program.basic2d)
{
enforce(.viewPort[0] >= 0);
prog.use();
prog.setUniform("in_mat", matrix);
prog.setUniform("drawColor", vec4f(1.0, 0.2, 0.2, 1.0));
shape.draw(prog);
}
void renderRectangle(int[2] pos, int[2] size, Program prog = Program.basic2d)
{
vec3f screenScale = vec3f(2.0, 2.0, 1.0) / vec3f(.viewPort[0], .viewPort[1], 1.0);
float[3] npos = [
-viewPort[0]*0.5 + cast(float)pos[0] + size[0]*0.5,
viewPort[1]*0.5 - cast(float)pos[1] - size[1]*0.5,
0];
float[3] nsize = [size[0], -size[1], 1];
auto m = mat4f(1.0);
draw!Rectangle(
make_scale(nsize) *
make_translate(npos) *
// make_rotate!3(rotation) *
make_scale([2.0 / .viewPort[0], 2.0 / .viewPort[1], 1.0]) // Screen scale always last
,prog);
};
| D |
/home/fabian/semasquare/hello_world/target/debug/deps/glutin_egl_sys-7b7a92179df6a53b.rmeta: /home/fabian/.cargo/registry/src/github.com-1ecc6299db9ec823/glutin_egl_sys-0.1.5/src/lib.rs /home/fabian/semasquare/hello_world/target/debug/build/glutin_egl_sys-406f707b55970a51/out/egl_bindings.rs
/home/fabian/semasquare/hello_world/target/debug/deps/libglutin_egl_sys-7b7a92179df6a53b.rlib: /home/fabian/.cargo/registry/src/github.com-1ecc6299db9ec823/glutin_egl_sys-0.1.5/src/lib.rs /home/fabian/semasquare/hello_world/target/debug/build/glutin_egl_sys-406f707b55970a51/out/egl_bindings.rs
/home/fabian/semasquare/hello_world/target/debug/deps/glutin_egl_sys-7b7a92179df6a53b.d: /home/fabian/.cargo/registry/src/github.com-1ecc6299db9ec823/glutin_egl_sys-0.1.5/src/lib.rs /home/fabian/semasquare/hello_world/target/debug/build/glutin_egl_sys-406f707b55970a51/out/egl_bindings.rs
/home/fabian/.cargo/registry/src/github.com-1ecc6299db9ec823/glutin_egl_sys-0.1.5/src/lib.rs:
/home/fabian/semasquare/hello_world/target/debug/build/glutin_egl_sys-406f707b55970a51/out/egl_bindings.rs:
# env-dep:OUT_DIR=/home/fabian/semasquare/hello_world/target/debug/build/glutin_egl_sys-406f707b55970a51/out
| D |
void main() { runSolver(); }
void problem() {
auto H = scan!long;
auto W = scan!long;
auto K = scan!long;
auto S = Point(scan!long, scan!long);
auto G = Point(scan!long, scan!long);
auto solve() {
enum long MOD = 998244353;
auto moves = [
[0, W-1, H-1, 0],
[1, W-2, 0, H-1],
[1, 0, H-2, W-1],
[0, 1, 1, W+H-4]
];
auto dp = new long[][](2, 4);
dp[1][0] = 1;
foreach(p; 0..K) {
swap(dp[1], dp[0]);
dp[1][] = 0;
foreach(i; 0..4) foreach(j; 0..4) {
dp[1][i] += dp[0][j] * moves[i][j];
dp[1][i] %= MOD;
}
}
return S == G ? dp[$ - 1][0] :
S.x == G.x ? dp[$ - 1][1] :
S.y == G.y ? dp[$ - 1][2] :
dp[$ - 1][3];
}
outputForAtCoder(&solve);
}
// ----------------------------------------------
import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) { if (!m) return [[]]; if (s.empty) return []; return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
else static if (is(T == void)) fn();
else static if (is(T == string)) fn().writeln;
else static if (isInputRange!T) {
static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
else foreach(r; fn()) r.writeln;
}
else fn().writeln;
}
void runSolver() {
enum BORDER = "==================================";
debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
else problem();
}
enum YESNO = [true: "Yes", false: "No"];
struct UnionFind {
long[] parent;
long[] sizes;
this(long size) {
parent.length = size;
foreach(i; 0..size) parent[i] = i;
sizes.length = size;
sizes[] = 1;
}
long root(long x) {
if (parent[x] == x) return x;
return parent[x] = root(parent[x]);
}
long unite(long x, long y) {
long rootX = root(x);
long rootY = root(y);
if (rootX == rootY) return rootY;
if (sizes[rootX] < sizes[rootY]) {
sizes[rootY] += sizes[rootX];
return parent[rootY] = rootX;
} else {
sizes[rootX] += sizes[rootY];
return parent[rootX] = rootY;
}
}
bool same(long x, long y) {
long rootX = root(x);
long rootY = root(y);
return rootX == rootY;
}
}
| D |
// PERMUTE_ARGS:
// REQUIRED_ARGS: -D -Ddtest_results/compilable -o-
// POST_SCRIPT: compilable/extra-files/ddocAny-postscript.sh 5446
module ddoc5446;
import ddoc5446a;
private import ddoc5446b;
/** */
alias A_Foo This_Foo;
/** */
alias A_Foo_Alias This_Foo_Alias;
/** */
alias int This_Int;
/** */
alias A_Enum This_Enum;
/** */
deprecated alias ddoc5446b.A_Enum_New A_Enum_New;
struct Nested
{
}
/** */
struct Bar
{
/** */
alias A_Foo Bar_A_Foo;
/** */
alias A_Foo_Alias Bar_A_Foo_Alias;
/** */
alias A_Int Bar_A_Int;
/** */
alias This_Foo Bar_This_Foo;
/** */
alias This_Foo_Alias Bar_This_Foo_Alias;
/** */
alias This_Int Bar_This_Int;
/** */
alias Nested Nested_Alias;
/** */
alias .Nested Fake_Nested;
/** */
struct Nested
{
/** */
alias Bar Bar_Nested_Bar_Alias;
/** */
alias .Bar Bar_Alias;
/** */
struct Bar
{
}
}
}
| D |
PLONG PLAT ED95 KD LOMAGAGE HIMAGAGE SLAT SLONG RESULTNO DP DM WT ROCKTYPE
273 54 4 0 46 48 -33.5 151.300003 1769 6 6 0.703125 intrusives, basalt
264.399994 75 15.6000004 0 2 65 -8.80000019 126.699997 1206 10.3999996 18 0.444444444 extrusives, intrusives
346 61 9 41.2000008 35 100 -31.3999996 138.600006 1170 13 15 0.841346154 sediments
333 45 9 16.5 35 100 -30.3999996 139.399994 1161 17 18 0.902777778 sediments, tillite
317 57 5 200 35 100 -30.5 139.300003 1165 9 10 0.742857143 sediments, redbeds
329 58 25 4.0999999 35 100 -30.2000008 139 1166 41.5999985 45.5999985 0.89047619 sediments, sandstone, tillite
223 26 13 14.8000002 35 100 -30.2999992 139.5 1157 26 26 0.868965517 extrusives
320 63 9 15.5 34 65 -38 145.5 1854 16 16 0.931 extrusives
314 70 6 132 48 50 -33.2999992 151.199997 1844 9 10 0.4 intrusives, basalt
317 63 14 16 23 56 -32.5 151 1840 20 20 0.851351351 extrusives, basalts
302.700012 66.8000031 6.80000019 35 34 65 -38 145.5 1819 10.8000002 12.1000004 0.912592593 extrusives
305 73 17 29 23 56 -42 147 1821 25 29 0.65625 extrusives, basalts
274 66 27.6000004 8.60000038 25 65 -41.2999992 145.899994 1873 39.7999992 46.9000015 0.766666667 intrusives, granite
321 64 6 27.5 25 65 -35.5999985 137.5 1874 10 11 0.935454545 sediments
294 75 11 7 25 65 -41.0999985 146.100006 1871 16.2999992 18.8999996 0.625 sediments, sandstone
315 66 10.5 18 25 65 -41 145.5 1872 18.2000008 19.6000004 0.895833333 extrusives, sediments
298 58.7999992 2.4000001 0 35 65 -27 141.5 1972 3.79999995 3.79999995 0.486486486 sediments, weathered
314 66 5.5999999 161 48 50 -33.2999992 151.199997 1969 8.5 9.80000019 0.4 intrusives, basalt
310.899994 68.5 0 0 40 60 -35 150 1927 5.19999981 5.19999981 0.971419884 extrusives, basalts
278 66 2.0999999 333 48 50 -33.2999992 151.199997 1596 2.5999999 3.29999995 0.464285714 intrusives, basalt
| D |
/*
* This file is part of OpenGrafik.
*
* Copyright (C) 2008 Frederic-Gerald Morcos <fred.morcos@gmail.com>
*
* OpenGrafik is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGrafik is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGrafik. If not, see <http://www.gnu.org/licenses/>.
*/
module ui.DocumentViewport;
private import
gtk.ScrolledWindow,
ui.DiagramCanvas;
class DocumentViewport: ScrolledWindow {
protected:
DiagramCanvas canvas;
bool onScroll (GtkScrollType type, int arg2, ScrolledWindow window) {
canvas.queueDraw;
return true;
}
public:
this () {
super(PolicyType.ALWAYS, PolicyType.ALWAYS);
canvas = new DiagramCanvas;
addWithViewport(canvas);
addOnScrollChild(&onScroll);
showAll;
}
void configureSize (int width, int height) {
canvas.configureSize(width, height);
}
}
| D |
.hd geta$f "fetch arguments for a Fortran program" 02/24/82
integer function geta$f (ap, str, len)
integer ap, len
character str (*)
.sp
Library: vswtlb (standard Subsystem library)
.fs
'Geta$f' fetches an argument from the Subsystem command
line in a format useable by a Fortran program.
The arguments are analogous to those used by 'getarg'.
'Ap' is the number of the argument to be fetched:
0 for the command name, 1 for the first argument, 2 for
the second, etc. 'Str' is a string to receive the argument,
while 'len' is the number of characters allocated to 'str'.
The function return value is either the length of the argument
string actually returned, or EOF (-1) if there is no
argument in that position.
.im
'Geta$f' simply calls 'getarg' with the argument pointer,
and then calls 'ctop' to convert the result into the proper
Fortran format.
.am
str
.ca
ctop (2), getarg (2)
.bu
If 'len' is an odd number, 'geta$f' will return at most
'len - 1' characters of an argument.
.sa
getarg (2), geta$plg (2), geta$p (2)
| D |
/Users/ThiagoBevi/Dev-iOS/WeaponsAndTests/Build/Intermediates/WeaponsAndTests.build/Debug-iphonesimulator/WeaponsAndTestsTests.build/Objects-normal/x86_64/WeaponsAndTestsTests.o : /Users/ThiagoBevi/Dev-iOS/WeaponsAndTests/WeaponsAndTestsTests/WeaponsAndTestsTests.swift /Users/ThiagoBevi/Dev-iOS/WeaponsAndTests/WeaponsAndTestsTests/DetailViewcontrollerTest.swift /Users/ThiagoBevi/Dev-iOS/WeaponsAndTests/Build/Products/Debug-iphonesimulator/WeaponsAndTests.swiftmodule/x86_64.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/XCTest.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Modules/module.modulemap /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/usr/include/objc/ObjectiveC.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/usr/include/Darwin.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTest.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/ThiagoBevi/Dev-iOS/WeaponsAndTests/Build/Intermediates/WeaponsAndTests.build/Debug-iphonesimulator/WeaponsAndTestsTests.build/Objects-normal/x86_64/WeaponsAndTestsTests~partial.swiftmodule : /Users/ThiagoBevi/Dev-iOS/WeaponsAndTests/WeaponsAndTestsTests/WeaponsAndTestsTests.swift /Users/ThiagoBevi/Dev-iOS/WeaponsAndTests/WeaponsAndTestsTests/DetailViewcontrollerTest.swift /Users/ThiagoBevi/Dev-iOS/WeaponsAndTests/Build/Products/Debug-iphonesimulator/WeaponsAndTests.swiftmodule/x86_64.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/XCTest.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Modules/module.modulemap /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/usr/include/objc/ObjectiveC.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/usr/include/Darwin.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTest.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/ThiagoBevi/Dev-iOS/WeaponsAndTests/Build/Intermediates/WeaponsAndTests.build/Debug-iphonesimulator/WeaponsAndTestsTests.build/Objects-normal/x86_64/WeaponsAndTestsTests~partial.swiftdoc : /Users/ThiagoBevi/Dev-iOS/WeaponsAndTests/WeaponsAndTestsTests/WeaponsAndTestsTests.swift /Users/ThiagoBevi/Dev-iOS/WeaponsAndTests/WeaponsAndTestsTests/DetailViewcontrollerTest.swift /Users/ThiagoBevi/Dev-iOS/WeaponsAndTests/Build/Products/Debug-iphonesimulator/WeaponsAndTests.swiftmodule/x86_64.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/XCTest.swiftmodule /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Modules/module.modulemap /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/usr/include/objc/ObjectiveC.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/usr/include/Darwin.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTest.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Users/ThiagoBevi/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
| D |
/*#D*/
// Copyright 2015-2018, Jakob Bornecrantz.
// SPDX-License-Identifier: BSL-1.0
/*!
* DWARF enums and code.
*
* @ingroup backend llvmbackend
*/
module volt.llvm.dwarf;
/*
*
* Dwarf enums.
*
*/
enum DwAte
{
Address = 0x01,
Boolean = 0x02,
ComplexFloat = 0x03,
Float = 0x04,
Signed = 0x05,
SignedChar = 0x06,
Unsigned = 0x07,
UnsignedChar = 0x08,
LoUser = 0x80,
HiUser = 0x81,
}
| D |
/Users/wilsonvinson/Documents/GitHub/RUST01/rust01_01/target/debug/deps/read_color-48622f2bf960f1a3.rmeta: /Users/wilsonvinson/.cargo/registry/src/github.com-1ecc6299db9ec823/read_color-1.0.0/src/lib.rs
/Users/wilsonvinson/Documents/GitHub/RUST01/rust01_01/target/debug/deps/libread_color-48622f2bf960f1a3.rlib: /Users/wilsonvinson/.cargo/registry/src/github.com-1ecc6299db9ec823/read_color-1.0.0/src/lib.rs
/Users/wilsonvinson/Documents/GitHub/RUST01/rust01_01/target/debug/deps/read_color-48622f2bf960f1a3.d: /Users/wilsonvinson/.cargo/registry/src/github.com-1ecc6299db9ec823/read_color-1.0.0/src/lib.rs
/Users/wilsonvinson/.cargo/registry/src/github.com-1ecc6299db9ec823/read_color-1.0.0/src/lib.rs:
| D |
/**
License:
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
Authors:
aermicioi
**/
module aermicioi.aedi_property_reader.arg;
public import aermicioi.aedi_property_reader.arg.accessor;
public import aermicioi.aedi_property_reader.arg.arg;
public import aermicioi.aedi_property_reader.arg.convertor; | D |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtWidgets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QSTYLEFACTORY_H
#define QSTYLEFACTORY_H
public import qt.QtCore.qstringlist;
QT_BEGIN_NAMESPACE
class QStyle;
class Q_WIDGETS_EXPORT QStyleFactory
{
public:
static QStringList keys();
static QStyle *create(ref const(QString));
};
QT_END_NAMESPACE
#endif // QSTYLEFACTORY_H
| D |
the physical condition of blocking or filling a passage with an obstruction
an obstruction in a pipe or tube
the act of blocking
| D |
/Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/build/EggGame.build/Debug-iphonesimulator/EggGame.build/Objects-normal/x86_64/SharedData.o : /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/GameScene.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Level_Two.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/SharedData.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/AssetViewController.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Level_One.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Level_Three.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/GameViewController.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/AppDelegate.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Level_Five.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Level_Four.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/GameSelectionScene.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Constants.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SpriteKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/GLKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/simd.swiftmodule
/Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/build/EggGame.build/Debug-iphonesimulator/EggGame.build/Objects-normal/x86_64/SharedData~partial.swiftmodule : /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/GameScene.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Level_Two.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/SharedData.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/AssetViewController.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Level_One.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Level_Three.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/GameViewController.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/AppDelegate.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Level_Five.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Level_Four.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/GameSelectionScene.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Constants.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SpriteKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/GLKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/simd.swiftmodule
/Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/build/EggGame.build/Debug-iphonesimulator/EggGame.build/Objects-normal/x86_64/SharedData~partial.swiftdoc : /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/GameScene.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Level_Two.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/SharedData.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/AssetViewController.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Level_One.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Level_Three.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/GameViewController.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/AppDelegate.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Level_Five.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Level_Four.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/GameSelectionScene.swift /Users/yuxiangtang1/Documents/Academic/CS526/EggGame_11.28/EggGame/Constants.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SpriteKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/GLKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/simd.swiftmodule
| D |
// Written in the D programming language.
module windows.networkdiagnosticsframework;
public import windows.core;
public import windows.com : HRESULT, IUnknown;
public import windows.networkdrivers : SOCKET_ADDRESS_LIST;
public import windows.security : SID;
public import windows.systemservices : BOOL, PWSTR;
public import windows.windowsandmessaging : HWND;
public import windows.windowsprogramming : FILETIME;
extern(Windows) @nogc nothrow:
// Enums
///The <b>ATTRIBUTE_TYPE</b> enumeration defines possible values for a helper attribute.
alias ATTRIBUTE_TYPE = int;
enum : int
{
///An invalid attribute.
AT_INVALID = 0x00000000,
///A true or false value.
AT_BOOLEAN = 0x00000001,
///An 8-bit signed integer.
AT_INT8 = 0x00000002,
///An 8-bit unsigned integer.
AT_UINT8 = 0x00000003,
///A 16-bit signed integer.
AT_INT16 = 0x00000004,
///A 16-bit unsigned integer.
AT_UINT16 = 0x00000005,
///A 32-bit signed integer.
AT_INT32 = 0x00000006,
///A 32-bit unsigned integer.
AT_UINT32 = 0x00000007,
///A 64-bit signed integer.
AT_INT64 = 0x00000008,
///A 64-bit unsigned integer.
AT_UINT64 = 0x00000009,
///A string.
AT_STRING = 0x0000000a,
///A GUID structure.
AT_GUID = 0x0000000b,
///A LifeTime structure.
AT_LIFE_TIME = 0x0000000c,
///An IPv4 or IPv6 address.
AT_SOCKADDR = 0x0000000d,
AT_OCTET_STRING = 0x0000000e,
}
///The <b>REPAIR_SCOPE</b> enumeration describes the scope of modification for a given repair.
alias REPAIR_SCOPE = int;
enum : int
{
///The repair effect is system-wide.
RS_SYSTEM = 0x00000000,
///The repair effect is user-specific.
RS_USER = 0x00000001,
///The repair effect is application-specific.
RS_APPLICATION = 0x00000002,
RS_PROCESS = 0x00000003,
}
///The <b>REPAIR_RISK</b> enumeration specifies whether repair changes are persistent and whether they can be undone.
alias REPAIR_RISK = int;
enum : int
{
///The repair performs persistent changes that cannot be undone.
RR_NOROLLBACK = 0x00000000,
///The repair performs persistent changes that can be undone.
RR_ROLLBACK = 0x00000001,
RR_NORISK = 0x00000002,
}
///The <b>UI_INFO_TYPE</b> enumeration identifies repairs that perform user interface tasks.
alias UI_INFO_TYPE = int;
enum : int
{
UIT_INVALID = 0x00000000,
///No additional repair interfaces are present.
UIT_NONE = 0x00000001,
///Execute shell command.
UIT_SHELL_COMMAND = 0x00000002,
///Launch help pane.
UIT_HELP_PANE = 0x00000003,
UIT_DUI = 0x00000004,
}
///The <b>DIAGNOSIS_STATUS</b> enumeration describes the result of a hypothesis submitted to a helper class in which the
///health of a component has been determined.
alias DIAGNOSIS_STATUS = int;
enum : int
{
///A helper class is not implemented
DS_NOT_IMPLEMENTED = 0x00000000,
///The helper class has confirmed a problem existing in its component.
DS_CONFIRMED = 0x00000001,
///The helper class has determined that no problem exists.
DS_REJECTED = 0x00000002,
///The helper class is unable to determine whether there is a problem.
DS_INDETERMINATE = 0x00000003,
///The helper class is unable to perform the diagnosis at this time.
DS_DEFERRED = 0x00000004,
DS_PASSTHROUGH = 0x00000005,
}
///The <b>REPAIR_STATUS</b> enumeration describes the result of a helper class attempting a repair option.
alias REPAIR_STATUS = int;
enum : int
{
///The helper class does not have a repair option implemented.
RS_NOT_IMPLEMENTED = 0x00000000,
///The helper class has repaired a problem.
RS_REPAIRED = 0x00000001,
///The helper class has attempted to repair a problem but validation indicates the repair operation has not
///succeeded.
RS_UNREPAIRED = 0x00000002,
///The helper class is unable to perform the repair at this time.
RS_DEFERRED = 0x00000003,
RS_USER_ACTION = 0x00000004,
}
///The <b>PROBLEM_TYPE</b> enumeration describes the type of problem a helper class indicates is present.
alias PROBLEM_TYPE = int;
enum : int
{
PT_INVALID = 0x00000000,
///A low-health problem exists within the component itself. No problems were found within local components on which
///this component depends.
PT_LOW_HEALTH = 0x00000001,
///A low-health problem exists within local components on which this component depends.
PT_LOWER_HEALTH = 0x00000002,
///The low-health problem is in the out-of-box components this component depends on.
PT_DOWN_STREAM_HEALTH = 0x00000004,
///The component's resource is being highly utilized. No high utilization was found within local components on which
///this component depends.
PT_HIGH_UTILIZATION = 0x00000008,
///The causes of the component's high-utilization problem are from local components that depend on it.
PT_HIGHER_UTILIZATION = 0x00000010,
PT_UP_STREAM_UTILIZATION = 0x00000020,
}
// Structs
///The <b>OCTET_STRING</b> structure contains a pointer to a string of byte data.
struct OCTET_STRING
{
///Type: <b>DWORD</b> The length of the data.
uint dwLength;
ubyte* lpValue;
}
///The <b>LIFE_TIME</b> structure contains a start time and an end time.
struct LIFE_TIME
{
///Type: <b>FILETIME</b> The time the problem instance began.
FILETIME startTime;
FILETIME endTime;
}
///The <b>DIAG_SOCKADDR</b> structure stores an Internet Protocol (IP) address for a computer that is participating in a
///Windows Sockets communication.
struct DIAG_SOCKADDR
{
///Type: <b>USHORT</b> Socket address group.
ushort family;
///Type: <b>CHAR[126]</b> The maximum size of all the different socket address structures.
byte[126] data;
}
///The <b>HELPER_ATTRIBUTE</b> structure contains all NDF supported data types.
struct HELPER_ATTRIBUTE
{
///Type: <b>[string] LPWSTR</b> A pointer to a null-terminated string that contains the name of the attribute.
PWSTR pwszName;
///Type: <b>ATTRIBUTE_TYPE</b> The type of helper attribute.
ATTRIBUTE_TYPE type;
union
{
BOOL Boolean;
ubyte Char;
ubyte Byte;
short Short;
ushort Word;
int Int;
uint DWord;
long Int64;
ulong UInt64;
PWSTR PWStr;
GUID Guid;
LIFE_TIME LifeTime;
DIAG_SOCKADDR Address;
OCTET_STRING OctetString;
}
}
///The <b>ShellCommandInfo</b> structure contains data required to launch an additional application for manual repair
///options.
struct ShellCommandInfo
{
///Type: <b>[string] LPWSTR</b> A pointer to a null-terminated string that contains the action to be performed. The
///set of available verbs that specifies the action depends on the particular file or folder. Generally, the actions
///available from an object's shortcut menu are available verbs. For more information, see the Remarks section.
PWSTR pwszOperation;
///Type: <b>[string] LPWSTR</b> A pointer to a null-terminated string that specifies the file or object on which to
///execute the specified verb. To specify a Shell namespace object, pass the fully qualified parse name. Note that
///not all verbs are supported on all objects. For example, not all document types support the "print" verb.
PWSTR pwszFile;
///Type: <b>[string] LPWSTR</b> A pointer to a null-terminated strings that specifies the parameters to be passed to
///the application, only if the <i>pwszFile</i> parameter specifies an executable file. The format of this string is
///determined by the verb that is to be invoked. If <i>pwszFile</i> specifies a document file, <i>pwszParameters</i>
///should be <b>NULL</b>.
PWSTR pwszParameters;
///Type: <b>[string] LPWSTR</b> A pointer to a null-terminated string that specifies the default directory.
PWSTR pwszDirectory;
///Type: <b>ULONG</b> Flags that specify how an application is to be displayed when it is opened. If <i>pwszFile</i>
///specifies a document file, the flag is simply passed to the associated application. It is up to the application
///to decide how to handle it.
uint nShowCmd;
}
///The <b>UiInfo</b> structure is used to display repair messages to the user.
struct UiInfo
{
///Type: <b>UI_INFO_TYPE</b> The type of user interface (UI) to use. This can be one of the values shown in the
///following members.
UI_INFO_TYPE type;
union
{
PWSTR pwzNull;
ShellCommandInfo ShellInfo;
PWSTR pwzHelpUrl;
PWSTR pwzDui;
}
}
///The <b>RepairInfo</b> structure contains data required for a particular repair option.
struct RepairInfo
{
///A unique GUID for this repair.
GUID guid;
///A pointer to a null-terminated string that contains the helper class name in a user-friendly way.
PWSTR pwszClassName;
///A pointer to a null-terminated string that describes the repair in a user friendly way.
PWSTR pwszDescription;
///One of the WELL_KNOWN_SID_TYPE if the repair requires certain user contexts or privileges.
uint sidType;
///The number of seconds required to perform the repair.
int cost;
///Additional information about the repair. <table> <tr> <th>Value</th> <th>Meaning</th> </tr> <tr> <td
///width="40%"><a id="RF_WORKAROUND"></a><a id="rf_workaround"></a><dl> <dt><b>RF_WORKAROUND</b></dt> </dl> </td>
///<td width="60%"> Indicates that the repair is a workaround for the issue. For example, sometimes resetting a
///network interface solves intermittent problems, but does not directly address a specific issue, so it is
///considered a workaround. NDF will show non-workarounds to the user before workarounds. </td> </tr> <tr> <td
///width="40%"><a id="RF_USER_ACTION"></a><a id="rf_user_action"></a><dl> <dt><b>RF_USER_ACTION</b></dt> </dl> </td>
///<td width="60%"> Indicates that the repair prompts the user to perform a manual task outside of NDF. </td> </tr>
///<tr> <td width="40%"><a id="RF_USER_CONFIRMATION"></a><a id="rf_user_confirmation"></a><dl>
///<dt><b>RF_USER_CONFIRMATION</b></dt> </dl> </td> <td width="60%"> Indicates that the repair should not be
///automatically performed. The user is instead prompted to select the repair. </td> </tr> <tr> <td width="40%"><a
///id="RF_INFORMATION_ONLY"></a><a id="rf_information_only"></a><dl> <dt><b>RF_INFORMATION_ONLY</b></dt> </dl> </td>
///<td width="60%"> Indicates that the repair consists of actionable information for the user. Repair and validation
///sessions do not occur for information-only repairs. </td> </tr> <tr> <td width="40%"><a
///id="RF_VALIDATE_HELPTOPIC"></a><a id="rf_validate_helptopic"></a><dl> <dt><b>RF_VALIDATE_HELPTOPIC</b></dt> </dl>
///</td> <td width="60%"> Indicates that the repair provides information to the user as well as a help topic. Unlike
///<b>RF_INFORMATION_ONLY</b> repairs, which cannot be validated, this repair can be executed and validated within a
///diagnostic session. <div class="alert"><b>Note</b> Available only in Windows 7, Windows Server 2008 R2, and
///later.</div> <div> </div> </td> </tr> <tr> <td width="40%"><a id="RF_REPRO"></a><a id="rf_repro"></a><dl>
///<dt><b>RF_REPRO</b></dt> </dl> </td> <td width="60%"> Indicates that the repair prompts the user to reproduce
///their problem. At the same time, the helper class may have enabled more detailed logging or other background
///mechanisms to help detect the failure. <div class="alert"><b>Note</b> Available only in Windows 7, Windows Server
///2008 R2, and later.</div> <div> </div> </td> </tr> <tr> <td width="40%"><a id="RF_CONTACT_ADMIN"></a><a
///id="rf_contact_admin"></a><dl> <dt><b>RF_CONTACT_ADMIN</b></dt> </dl> </td> <td width="60%"> Indicates that the
///repair prompts the user to contact their network administrator in order to resolve the problem. <div
///class="alert"><b>Note</b> Available only in Windows 7, Windows Server 2008 R2, and later.</div> <div> </div>
///</td> </tr> <tr> <td width="40%"><a id="RF_RESERVED"></a><a id="rf_reserved"></a><dl> <dt><b>RF_RESERVED</b></dt>
///</dl> </td> <td width="60%"> Reserved for system use. <div class="alert"><b>Note</b> Available only in Windows 7,
///Windows Server 2008 R2, and later.</div> <div> </div> </td> </tr> <tr> <td width="40%"><a
///id="RF_RESERVED_CA"></a><a id="rf_reserved_ca"></a><dl> <dt><b>RF_RESERVED_CA</b></dt> </dl> </td> <td
///width="60%"> Reserved for system use. <div class="alert"><b>Note</b> Available only in Windows 7, Windows Server
///2008 R2, and later.</div> <div> </div> </td> </tr> <tr> <td width="40%"><a id="RF_RESERVED_LNI"></a><a
///id="rf_reserved_lni"></a><dl> <dt><b>RF_RESERVED_LNI</b></dt> </dl> </td> <td width="60%"> Reserved for system
///use. <div class="alert"><b>Note</b> Available only in Windows 7, Windows Server 2008 R2, and later.</div> <div>
///</div> </td> </tr> </table>
uint flags;
///Reserved for future use.
REPAIR_SCOPE scope_;
///Reserved for future use.
REPAIR_RISK risk;
///A UiInfo structure.
UiInfo UiInfo90;
int rootCauseIndex;
}
///Contains detailed repair information that can be used to help resolve the root cause of an incident.
struct RepairInfoEx
{
///Type: <b>RepairInfo</b> The detailed repair information.
RepairInfo repair;
///Type: <b>USHORT</b> The rank of the repair, relative to other repairs in the RootCauseInfo structure associated
///with the incident. A repair with rank 1 is expected to be more relevant to the problem and thus will be the first
///repair to be attempted. The success of any individual repair is not guaranteed, regardless of its rank.
ushort repairRank;
}
///Contains detailed information about the root cause of an incident.
struct RootCauseInfo
{
///Type: <b>LPWSTR</b> A string that describes the problem that caused the incident.
PWSTR pwszDescription;
///Type: <b>GUID</b> The GUID that corresponds to the problem identified.
GUID rootCauseID;
///Type: <b>DWORD</b> A numeric value that provides more information about the problem. <table> <tr> <th>Value</th>
///<th>Meaning</th> </tr> <tr> <td width="40%"><a id="RCF_ISLEAF"></a><a id="rcf_isleaf"></a><dl>
///<dt><b>RCF_ISLEAF</b></dt> <dt>0x1</dt> </dl> </td> <td width="60%"> The root cause corresponds to a leaf in the
///diagnostics tree. Root causes that are leafs are more likely to be closer to the problem that the user is trying
///to diagnose. </td> </tr> <tr> <td width="40%"><a id="RCF_ISCONFIRMED"></a><a id="rcf_isconfirmed"></a><dl>
///<dt><b>RCF_ISCONFIRMED</b></dt> <dt>0x2</dt> </dl> </td> <td width="60%"> The root cause corresponds to a node
///with a DIAGNOSIS_STATUS value of <b>DS_CONFIRMED</b>. Problems with confirmed low health are more likely to
///correspond to the problem the user is trying to diagnose. </td> </tr> <tr> <td width="40%"><a
///id="RCF_ISTHIRDPARTY"></a><a id="rcf_isthirdparty"></a><dl> <dt><b>RCF_ISTHIRDPARTY</b></dt> <dt>0x4</dt> </dl>
///</td> <td width="60%"> The root cause comes from a third-party helper class extension rather than a native
///Windows helper class. </td> </tr> </table>
uint rootCauseFlags;
///Type: <b>GUID</b> GUID of the network interface on which the problem occurred. If the problem is not
///interface-specific, this value is zero (0).
GUID networkInterfaceID;
///Type: <b>RepairInfoEx*</b> The repairs that are available to try and fix the problem.
RepairInfoEx* pRepairs;
///Type: <b>USHORT</b> The number of repairs available.
ushort repairCount;
}
///The <b>HYPOTHESIS</b> structure contains data used to submit a hypothesis to NDF for another helper class. The name
///of the helper class, the number of parameters that the helper class requires, and the parameters to pass to the
///helper class are contained in this structure.
struct HYPOTHESIS
{
///Type: <b>[string] LPWSTR</b> A pointer to a null-terminated string that contains the name of the helper class.
PWSTR pwszClassName;
///Type: <b>[string] LPWSTR</b> A pointer to a null-terminated string that contains a user-friendly description of
///the data being passed to the helper class..
PWSTR pwszDescription;
///Type: <b>ULONG</b> The count of attributes in this hypothesis.
uint celt;
///Type: <b>[size_is(celt)]PHELPER_ATTRIBUTE[ ]</b> A pointer to an array of HELPER_ATTRIBUTE structures that
///contains key attributes for this hypothesis.
HELPER_ATTRIBUTE* rgAttributes;
}
///The <b>HelperAttributeInfo</b> structure contains the name of the helper attribute and its type.
struct HelperAttributeInfo
{
///Type: <b>[string] LPWSTR</b> Pointer to a null-terminated string that contains the name of the helper attribute.
PWSTR pwszName;
///Type: <b>ATTRIBUTE_TYPE</b> The type of helper attribute.
ATTRIBUTE_TYPE type;
}
///The <b>DiagnosticsInfo</b> structure contains the estimate of diagnosis time, and flags for invocation.
struct DiagnosticsInfo
{
///Type: <b>long</b> The length of time, in seconds, that the diagnosis should take to complete. A value of zero or
///a negative value means the cost is negligible. Any positive value will cause the engine to adjust the overall
///diagnostics process.
int cost;
uint flags;
}
///The <b>HypothesisResult</b> structure contains information about a hypothesis returned from a helper class. The
///hypothesis is obtained via a call to GetLowerHypotheses.
struct HypothesisResult
{
///Type: <b>HYPOTHESIS</b> Information for a specific hypothesis.
HYPOTHESIS hypothesis;
///Type: <b>DIAGNOSIS_STATUS</b> The status of the child helper class and its children. If the hypothesis or any of
///its children indicated <b>DS_CONFIRMED</b> in a call to LowHealth, then this value will be <b>DS_CONFIRMED</b>.
///If no problems exist in such a call, the value will be <b>DS_REJECTED</b>. The value will be
///<b>DS_INDETERMINATE</b> if the health of the component is not clear.
DIAGNOSIS_STATUS pathStatus;
}
// Functions
///The <b>NdfCreateIncident</b> function is used internally by application developers to test the NDF functionality
///incorporated into their application.
///Params:
/// helperClassName = Type: <b>LPCWSTR</b> The name of the helper class to be used in the diagnoses of the incident.
/// celt = Type: <b>ULONG</b> A count of elements in the attributes array.
/// attributes = Type: <b>HELPER_ATTRIBUTE*</b> The applicable HELPER_ATTRIBUTE structure.
/// handle = Type: <b>NDFHANDLE*</b> A handle to the Network Diagnostics Framework incident.
///Returns:
/// Type: <b>HRESULT</b> Possible return values include, but are not limited to, the following. <table> <tr>
/// <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt> </dl> </td> <td
/// width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_OUTOFMEMORY</b></dt> </dl>
/// </td> <td width="60%"> There is not enough memory available to complete this operation. </td> </tr> <tr> <td
/// width="40%"> <dl> <dt><b>NDF_E_BAD_PARAM</b></dt> </dl> </td> <td width="60%"> One or more parameters are
/// invalid. </td> </tr> <tr> <td width="40%"> <dl> <dt><b> NDF_E_NOHELPERCLASS</b></dt> </dl> </td> <td width="60%">
/// <i>helperClassName</i> is <b>NULL</b>. </td> </tr> </table>
///
@DllImport("NDFAPI")
HRESULT NdfCreateIncident(const(PWSTR) helperClassName, uint celt, HELPER_ATTRIBUTE* attributes, void** handle);
///The <b>NdfCreateWinSockIncident</b> function provides access to the Winsock Helper Class provided by Microsoft.
///Params:
/// sock = Type: <b>SOCKET</b> A descriptor identifying a connected socket.
/// host = Type: <b>LPCWSTR</b> A pointer to the local host.
/// port = Type: <b>USHORT</b> The port providing Winsock access.
/// appId = Type: <b>LPCWSTR</b> Unique identifier associated with the application.
/// userId = Type: <b>SID*</b> Unique identifier associated with the user.
/// handle = Type: <b>NDFHANDLE*</b> Handle to the Network Diagnostics Framework incident.
///Returns:
/// Type: <b>HRESULT</b> Possible return values include, but are not limited to, the following. <table> <tr>
/// <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt> </dl> </td> <td
/// width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_OUTOFMEMORY</b></dt> </dl>
/// </td> <td width="60%"> There is not enough memory available to complete this operation. </td> </tr> <tr> <td
/// width="40%"> <dl> <dt><b>NDF_E_BAD_PARAM</b></dt> </dl> </td> <td width="60%"> One or more parameters are
/// invalid. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td width="60%"> One or
/// more parameters are invalid. </td> </tr> </table>
///
@DllImport("NDFAPI")
HRESULT NdfCreateWinSockIncident(size_t sock, const(PWSTR) host, ushort port, const(PWSTR) appId, SID* userId,
void** handle);
///The <b>NdfCreateWebIncident</b> function diagnoses web connectivity problems concerning a specific URL.
///Params:
/// url = Type: <b>LPCWSTR</b> The URL with which there is a connectivity issue.
/// handle = Type: <b>NDFHANDLE*</b> Handle to the Network Diagnostics Framework incident.
@DllImport("NDFAPI")
HRESULT NdfCreateWebIncident(const(PWSTR) url, void** handle);
///The <b>NdfCreateWebIncidentEx</b> function diagnoses web connectivity problems concerning a specific URL. This
///function allows for more control over the underlying diagnosis than the NdfCreateWebIncident function.
///Params:
/// url = Type: <b>LPCWSTR</b> The URL with which there is a connectivity issue.
/// useWinHTTP = Type: <b>BOOL</b> <b>TRUE</b> if diagnosis will be performed using the WinHTTP APIs; <b>FALSE</b> if the WinInet
/// APIs will be used.
/// moduleName = Type: <b>LPWSTR</b> The module name to use when checking against application-specific filtering rules (for
/// example, "C:\Program Files\Internet Explorer\iexplorer.exe"). If <b>NULL</b>, the value is autodetected during
/// the diagnosis.
/// handle = Type: <b>NDFHANDLE*</b> Handle to the Network Diagnostics Framework incident.
///Returns:
/// Type: <b>HRESULT</b> Possible return values include, but are not limited to, the following. <table> <tr>
/// <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt> </dl> </td> <td
/// width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_ABORT</b></dt> </dl> </td>
/// <td width="60%"> The underlying diagnosis or repair operation has been canceled. </td> </tr> <tr> <td
/// width="40%"> <dl> <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available
/// to complete this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>NDF_E_BAD_PARAM</b></dt> </dl> </td>
/// <td width="60%"> One or more parameters are invalid. </td> </tr> </table>
///
@DllImport("NDFAPI")
HRESULT NdfCreateWebIncidentEx(const(PWSTR) url, BOOL useWinHTTP, PWSTR moduleName, void** handle);
///The <b>NdfCreateSharingIncident</b> function diagnoses network problems in accessing a specific network share.
///Params:
/// UNCPath = Type: <b>LPCWSTR</b> The full UNC string (for example, "\\server\folder\file.ext") for the shared asset with
/// which there is a connectivity issue.
/// handle = Type: <b>NDFHANDLE*</b> Handle to the Network Diagnostics Framework incident.
@DllImport("NDFAPI")
HRESULT NdfCreateSharingIncident(const(PWSTR) UNCPath, void** handle);
///The <b>NdfCreateDNSIncident</b> function diagnoses name resolution issues in resolving a specific host name.
///Params:
/// hostname = Type: <b>LPCWSTR</b> The host name with which there is a name resolution issue.
/// queryType = Type: <b>WORD</b> The numeric representation of the type of record that was queried when the issue occurred. For
/// more information and a complete listing of record set types and their numeric representations, see the windns.h
/// header file. This parameter should be set to <b>DNS_TYPE_ZERO</b> for generic DNS resolution diagnosis.
/// handle = Type: <b>NDFHANDLE*</b> Handle to the Network Diagnostics Framework incident.
@DllImport("NDFAPI")
HRESULT NdfCreateDNSIncident(const(PWSTR) hostname, ushort queryType, void** handle);
///The <b>NdfCreateConnectivityIncident</b> function diagnoses generic Internet connectivity problems.
///Params:
/// handle = Type: <b>NDFHANDLE*</b> Handle to the Network Diagnostics Framework incident.
@DllImport("NDFAPI")
HRESULT NdfCreateConnectivityIncident(void** handle);
///The <b>NdfCreateNetConnectionIncident</b> function diagnoses connectivity issues using the NetConnection helper
///class.
///Params:
/// handle = Type: <b>NDFHANDLE*</b> Handle to the Network Diagnostics Framework incident.
/// id = Type: <b>GUID</b> Identifier of the network interface that the caller would like to create the incident for. The
/// NULL GUID {00000000-0000-0000-0000-000000000000} may be used if the caller does not want to specify an interface.
/// The system will attempt to determine the most appropriate interface based on the current state of the system.
@DllImport("NDFAPI")
HRESULT NdfCreateNetConnectionIncident(void** handle, GUID id);
///The <b>NdfCreatePnrpIncident</b> function creates a session to diagnose issues with the Peer Name Resolution Protocol
///(PNRP) service.
///Params:
/// cloudname = Type: <b>LPCWSTR</b> The name of the cloud to be diagnosed.
/// peername = Type: <b>LPCWSTR</b> Optional name of a peer node which PNRP can attempt to resolve. The results will be used to
/// help diagnose any problems.
/// diagnosePublish = Type: <b>BOOL</b> Specifies whether the helper class should verify that the node can publish IDs. If
/// <b>FALSE</b>, this diagnostic step will be skipped.
/// appId = Type: <b>LPCWSTR</b> Application ID for the calling application.
/// handle = Type: <b>NDFHANDLE*</b> Handle to the Network Diagnostics Framework incident.
///Returns:
/// Type: <b>HRESULT</b> Possible return values include, but are not limited to, the following. <table> <tr>
/// <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt> </dl> </td> <td
/// width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>NDF_E_BAD_PARAM</b></dt>
/// </dl> </td> <td width="60%"> One or more parameters has not been provided correctly. </td> </tr> </table>
///
@DllImport("NDFAPI")
HRESULT NdfCreatePnrpIncident(const(PWSTR) cloudname, const(PWSTR) peername, BOOL diagnosePublish,
const(PWSTR) appId, void** handle);
///The <b>NdfCreateGroupingIncident</b> function creates a session to diagnose peer-to-peer grouping functionality
///issues.
///Params:
/// CloudName = Type: <b>LPCWSTR</b> The name of the Peer Name Resolution Protocol (PNRP) cloud where the group is created. If
/// <b>NULL</b>, the session will not attempt to diagnose issues related to PNRP.
/// GroupName = Type: <b>LPCWSTR</b> The name of the group to be diagnosed. If <b>NULL</b>, the session will not attempt to
/// diagnose issues related to group availability.
/// Identity = Type: <b>LPCWSTR</b> The identity that a peer uses to access the group. If <b>NULL</b>, the session will not
/// attempt to diagnose issues related to the group's ability to register in PNRP.
/// Invitation = Type: <b>LPCWSTR</b> An XML invitation granted by another peer. An invitation is created when the inviting peer
/// calls PeerGroupCreateInvitation or PeerGroupIssueCredentials. If this value is present, the invitation will be
/// checked to ensure its format and expiration are valid.
/// Addresses = Type: <b>SOCKET_ADDRESS_LIST*</b> Optional list of addresses of the peers to which the application is trying to
/// connect. If this parameter is used, the helper class will diagnose connectivity to these addresses.
/// appId = Type: <b>LPCWSTR</b> Application ID for the calling application.
/// handle = Type: <b>NDFHANDLE*</b> Handle to the Network Diagnostics Framework incident.
///Returns:
/// Type: <b>HRESULT</b> Possible return values include, but are not limited to, the following. <table> <tr>
/// <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt> </dl> </td> <td
/// width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>NDF_E_BAD_PARAM</b></dt>
/// </dl> </td> <td width="60%"> One or more parameters has not been provided correctly. </td> </tr> </table>
///
@DllImport("NDFAPI")
HRESULT NdfCreateGroupingIncident(const(PWSTR) CloudName, const(PWSTR) GroupName, const(PWSTR) Identity,
const(PWSTR) Invitation, SOCKET_ADDRESS_LIST* Addresses, const(PWSTR) appId,
void** handle);
///The <b>NdfExecuteDiagnosis</b> function is used to diagnose the root cause of the incident that has occurred.
///Params:
/// handle = Type: <b>NDFHANDLE</b> Handle to the Network Diagnostics Framework incident.
/// hwnd = Type: <b>HWND</b> Handle to the window that is intended to display the diagnostic information. If specified, the
/// NDF UI is modal to the window. If <b>NULL</b>, the UI is non-modal.
///Returns:
/// Type: <b>HRESULT</b> Possible return values include, but are not limited to, the following. <table> <tr>
/// <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt> </dl> </td> <td
/// width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_HANDLE</b></dt> </dl> </td>
/// <td width="60%"> <i>handle</i> is invalid. </td> </tr> </table>
///
@DllImport("NDFAPI")
HRESULT NdfExecuteDiagnosis(void* handle, HWND hwnd);
///The <b>NdfCloseIncident</b> function is used to close an Network Diagnostics Framework (NDF) incident following its
///resolution.
///Params:
/// handle = Type: <b>NDFHANDLE</b> Handle to the NDF incident that is being closed.
///Returns:
/// Type: <b>HRESULT</b> Possible return values include, but are not limited to, the following. <table> <tr>
/// <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt> </dl> </td> <td
/// width="60%"> The operation succeeded. </td> </tr> </table>
///
@DllImport("NDFAPI")
HRESULT NdfCloseIncident(void* handle);
///The <b>NdfDiagnoseIncident</b> function diagnoses the root cause of an incident without displaying a user interface.
///Params:
/// Handle = Type: <b>NDFHANDLE</b> A handle to the Network Diagnostics Framework incident.
/// RootCauseCount = Type: <b>ULONG*</b> The number of root causes that could potentially have caused this incident. If diagnosis does
/// not succeed, the contents of this parameter should be ignored.
/// RootCauses = Type: <b>RootCauseInfo**</b> A collection of RootCauseInfo structures that contain a detailed description of the
/// root cause. If diagnosis succeeds, this parameter contains both the leaf root causes identified in the diagnosis
/// session and any non-leaf root causes that have an available repair. If diagnosis does not succeed, the contents
/// of this parameter should be ignored. Memory allocated to these structures should later be freed. For an example
/// of how to do this, see the Microsoft Windows Network Diagnostics Samples.
/// dwWait = Type: <b>DWORD</b> The length of time, in milliseconds, to wait before terminating the diagnostic routine.
/// INFINITE may be passed to this parameter if no time-out is desired.
/// dwFlags = Type: <b>DWORD</b> Possible values: <table> <tr> <th>Value</th> <th>Meaning</th> </tr> <tr> <td width="40%"><a
/// id="NDF_ADD_CAPTURE_TRACE"></a><a id="ndf_add_capture_trace"></a><dl> <dt><b>NDF_ADD_CAPTURE_TRACE</b></dt>
/// <dt>0x0001</dt> </dl> </td> <td width="60%"> Turns on network tracing during diagnosis. Diagnostic results will
/// be included in the Event Trace Log (ETL) file returned by NdfGetTraceFile. </td> </tr> <tr> <td width="40%"><a
/// id="NDF_APPLY_INCLUSION_LIST_FILTER_"></a><a id="ndf_apply_inclusion_list_filter_"></a><dl>
/// <dt><b>NDF_APPLY_INCLUSION_LIST_FILTER </b></dt> <dt>0x0002</dt> </dl> </td> <td width="60%"> Applies filtering
/// to the returned root causes so that they are consistent with the in-box scripted diagnostics behavior. Without
/// this flag, root causes will not be filtered. This flag must be set by the caller, so existing callers will not
/// see a change in behavior unless they explicitly specify this flag. <div class="alert"><b>Note</b> Available only
/// in Windows 8 and Windows Server 2012.</div> <div> </div> </td> </tr> </table>
///Returns:
/// Type: <b>HRESULT</b> Possible return values include, but are not limited to, the following. <table> <tr>
/// <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt> </dl> </td> <td
/// width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_HANDLE</b></dt> </dl> </td>
/// <td width="60%"> The NDF incident handle is not valid. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>WAIT_TIMEOUT</b></dt> </dl> </td> <td width="60%"> The diagnostic routine has terminated because it has
/// taken longer than the time-out specified in dwWait. </td> </tr> </table>
///
@DllImport("NDFAPI")
HRESULT NdfDiagnoseIncident(void* Handle, uint* RootCauseCount, RootCauseInfo** RootCauses, uint dwWait,
uint dwFlags);
///The <b>NdfRepairIncident</b> function repairs an incident without displaying a user interface.
///Params:
/// Handle = Type: <b>NDFHANDLE</b> Handle to the Network Diagnostics Framework incident. This handle should match the handle
/// passed to NdfDiagnoseIncident.
/// RepairEx = Type: <b>RepairInfoEx*</b> A structure (obtained from NdfDiagnoseIncident) which indicates the particular repair
/// to be performed. Memory allocated to these structures should later be freed. For an example of how to do this,
/// see the Microsoft Windows Network Diagnostics Samples.
/// dwWait = Type: <b>DWORD</b> The length of time, in milliseconds, to wait before terminating the diagnostic routine.
/// INFINITE may be passed to this parameter if no timeout is desired.
///Returns:
/// Possible return values include, but are not limited to, the following. <table> <tr> <th>Return code</th>
/// <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt> </dl> </td> <td width="60%"> Repair
/// succeeded. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>NDF_E_VALIDATION</b></dt> </dl> </td> <td width="60%">
/// The repair executed successfully, but NDF validation still found a connectivity problem. If this value is
/// returned, the session should be closed by calling NdfCloseIncident and another session should be created to
/// continue the diagnosis. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_HANDLE</b></dt> </dl> </td> <td
/// width="60%"> The NDF incident handle is not valid. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>WAIT_TIMEOUT</b></dt> </dl> </td> <td width="60%"> The repair operation has terminated because it has
/// taken longer than the time-out specified in dwWait. </td> </tr> </table> Other failure codes are returned if the
/// repair failed to execute. In that case, the client can call <b>NdfRepairIncident</b> again with a different
/// repair.
///
@DllImport("NDFAPI")
HRESULT NdfRepairIncident(void* Handle, RepairInfoEx* RepairEx, uint dwWait);
///The <b>NdfCancelIncident</b> function is used to cancel unneeded functions which have been previously called on an
///existing incident.
///Params:
/// Handle = Type: <b>NDFHANDLE</b> Handle to the Network Diagnostics Framework incident. This handle should match the handle
/// of an existing incident.
///Returns:
/// Type: <b>HRESULT</b> Possible return values include, but are not limited to, the following. <table> <tr>
/// <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt> </dl> </td> <td
/// width="60%"> The operation succeeded. </td> </tr> </table> Any result other than S_OK should be interpreted as an
/// error.
///
@DllImport("NDFAPI")
HRESULT NdfCancelIncident(void* Handle);
///The <b>NdfGetTraceFile</b> function is used to retrieve the path containing an Event Trace Log (ETL) file that
///contains Event Tracing for Windows (ETW) events from a diagnostic session.
///Params:
/// Handle = Type: <b>NDFHANDLE</b> Handle to a Network Diagnostics Framework incident. This handle should match the handle of
/// an existing incident.
/// TraceFileLocation = Type: <b>LPCWSTR*</b> The location of the trace file.
///Returns:
/// Type: <b>HRESULT</b> Possible return values include, but are not limited to, the following. <table> <tr>
/// <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt> </dl> </td> <td
/// width="60%"> The operation succeeded. </td> </tr> </table> Any result other than S_OK should be interpreted as an
/// error.
///
@DllImport("NDFAPI")
HRESULT NdfGetTraceFile(void* Handle, PWSTR* TraceFileLocation);
// Interfaces
///The <b>INetDiagHelper</b> interface provides methods that capture and provide information associated with diagnoses
///and resolution of network-related issues.
@GUID("C0B35746-EBF5-11D8-BBE9-505054503030")
interface INetDiagHelper : IUnknown
{
///The <b>Initialize</b> method passes in attributes to the Helper Class Extension from the hypothesis. The helper
///class should store these parameters for use in the main diagnostics functions. This method must be called before
///any diagnostics function.
///Params:
/// celt = A pointer to a count of elements in <b>HELPER_ATTRIBUTE</b> array.
/// rgAttributes = A reference to the HELPER_ATTRIBUTE array.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td
/// width="60%"> One or more parameters has not been provided correctly. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td width="60%"> The caller does not have sufficient privileges to
/// perform the diagnosis or repair operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_ABORT</b></dt>
/// </dl> </td> <td width="60%"> The diagnosis or repair operation has been canceled. </td> </tr> </table> Helper
/// Class Extensions may return HRESULTS that are specific to the failures encountered in the function.
///
HRESULT Initialize(uint celt, HELPER_ATTRIBUTE* rgAttributes);
///The <b>GetDiagnosticsInfo</b> method enables the Helper Class Extension instance to provide an estimate of how
///long the diagnosis may take.
///Params:
/// ppInfo = A pointer to a pointer to a DiagnosticsInfo structure.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td
/// width="60%"> One or more parameters has not been provided correctly. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td width="60%"> The caller does not have sufficient privileges to
/// perform the diagnosis or repair operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_ABORT</b></dt>
/// </dl> </td> <td width="60%"> The diagnosis or repair operation has been canceled. </td> </tr> </table> Helper
/// Class Extensions may return HRESULTS that are specific to the failures encountered in the function.
///
HRESULT GetDiagnosticsInfo(DiagnosticsInfo** ppInfo);
///The <b>GetKeyAttributes</b> method retrieves the key attributes of the Helper Class Extension.
///Params:
/// pcelt = A pointer to a count of elements in the <b>HELPER_ATTRIBUTE</b> array.
/// pprgAttributes = A pointer to an array of HELPER_ATTRIBUTE structures.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td
/// width="60%"> One or more parameters has not been provided correctly. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_NOTIMPL</b></dt> </dl> </td> <td width="60%"> This optional method is not implemented. </td> </tr>
/// <tr> <td width="40%"> <dl> <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td width="60%"> The caller does not
/// have sufficient privileges to perform the diagnosis or repair operation. </td> </tr> <tr> <td width="40%">
/// <dl> <dt><b>E_ABORT</b></dt> </dl> </td> <td width="60%"> The diagnosis or repair operation has been
/// canceled. </td> </tr> </table> Helper Class Extensions may return HRESULTS that are specific to the failures
/// encountered in the function.
///
HRESULT GetKeyAttributes(uint* pcelt, HELPER_ATTRIBUTE** pprgAttributes);
///The <b>LowHealth</b> method enables the Helper Class Extension to check whether the component being diagnosed is
///healthy.
///Params:
/// pwszInstanceDescription = A pointer to a null-terminated string containing the user-friendly description of the information being
/// diagnosed. For example, if a class were to diagnosis a connectivity issue with an IP address, the
/// <i>pwszInstanceDescription</i> parameter would contain the host name.
/// ppwszDescription = A pointer to a null-terminated string containing the description of the issue found if the component is found
/// to be unhealthy.
/// pDeferredTime = A pointer to the time, in seconds, to be deferred if the diagnosis cannot be started immediately. This is
/// used when the <i>pStatus</i> parameter is set to <b>DS_DEFERRED</b>.
/// pStatus = A pointer to the DIAGNOSIS_STATUS that is returned from the diagnosis.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td
/// width="60%"> One or more parameters has not been provided correctly. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td width="60%"> The caller does not have sufficient privileges to
/// perform the diagnosis or repair operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_ABORT</b></dt>
/// </dl> </td> <td width="60%"> The diagnosis or repair operation has been canceled. </td> </tr> </table> Helper
/// Class Extensions may return HRESULTS that are specific to the failures encountered in the function.
///
HRESULT LowHealth(const(PWSTR) pwszInstanceDescription, PWSTR* ppwszDescription, int* pDeferredTime,
DIAGNOSIS_STATUS* pStatus);
///The <b>HighUtilization</b> method enables the Helper Class Extension to check whether the corresponding component
///is highly utilized.
///Params:
/// pwszInstanceDescription = A pointer to a null-terminated string containing the user-friendly description of the information being
/// diagnosed. For example, if a class were to diagnosis a connectivity issue with an IP address, the
/// <i>pwszInstanceDescription</i> parameter would contain the host name.
/// ppwszDescription = A pointer to a null-terminated string containing the description of high utilization diagnosis result.
/// pDeferredTime = A pointer to the time, in seconds, to be deferred if the diagnosis cannot be started immediately. This is
/// used when the <i>pStatus</i> parameter is set to <b>DS_DEFERRED</b>.
/// pStatus = A pointer to the DIAGNOSIS_STATUS that is returned from the diagnosis.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td
/// width="60%"> One or more parameters has not been provided correctly. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_NOTIMPL</b></dt> </dl> </td> <td width="60%"> This optional method is not implemented. </td> </tr>
/// <tr> <td width="40%"> <dl> <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td width="60%"> The caller does not
/// have sufficient privileges to perform the diagnosis or repair operation. </td> </tr> <tr> <td width="40%">
/// <dl> <dt><b>E_ABORT</b></dt> </dl> </td> <td width="60%"> The diagnosis or repair operation has been
/// canceled. </td> </tr> </table> Helper Class Extensions may return HRESULTS that are specific to the failures
/// encountered in the function.
///
HRESULT HighUtilization(const(PWSTR) pwszInstanceDescription, PWSTR* ppwszDescription, int* pDeferredTime,
DIAGNOSIS_STATUS* pStatus);
///The <b>GetLowerHypotheses</b> method asks the Helper Class Extension to generate hypotheses for possible causes
///of low health in the local components that depend on it.
///Params:
/// pcelt = A pointer to a count of elements in the <b>HYPOTHESIS</b> array.
/// pprgHypotheses = A pointer to a HYPOTHESIS array.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td
/// width="60%"> One or more parameters has not been provided correctly. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_NOTIMPL</b></dt> </dl> </td> <td width="60%"> This optional method is not implemented. </td> </tr>
/// <tr> <td width="40%"> <dl> <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td width="60%"> The caller does not
/// have sufficient privileges to perform the diagnosis or repair operation. </td> </tr> <tr> <td width="40%">
/// <dl> <dt><b>E_ABORT</b></dt> </dl> </td> <td width="60%"> The diagnosis or repair operation has been
/// canceled. </td> </tr> </table> Helper Class Extensions may return HRESULTS that are specific to the failures
/// encountered in the function.
///
HRESULT GetLowerHypotheses(uint* pcelt, HYPOTHESIS** pprgHypotheses);
///The <b>GetDownStreamHypotheses</b> method asks the Helper Class Extension to generate hypotheses for possible
///causes of low health in the downstream network components it depends on.
///Params:
/// pcelt = A pointer to a count of elements in the HYPOTHESIS array.
/// pprgHypotheses = A pointer to an array of HYPOTHESIS structures.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td
/// width="60%"> One or more parameters has not been provided correctly. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_NOTIMPL</b></dt> </dl> </td> <td width="60%"> This optional method is not implemented. </td> </tr>
/// <tr> <td width="40%"> <dl> <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td width="60%"> The caller does not
/// have sufficient privileges to perform the diagnosis or repair operation. </td> </tr> <tr> <td width="40%">
/// <dl> <dt><b>E_ABORT</b></dt> </dl> </td> <td width="60%"> The diagnosis or repair operation has been
/// canceled. </td> </tr> </table> Helper Class Extensions may return HRESULTS that are specific to the failures
/// encountered in the function.
///
HRESULT GetDownStreamHypotheses(uint* pcelt, HYPOTHESIS** pprgHypotheses);
///The <b>GetHigherHypotheses</b> method asks the Helper Class Extension to generate hypotheses for possible causes
///of high utilization in the local components that depend on it.
///Params:
/// pcelt = A pointer to a count of elements in the HYPOTHESIS array.
/// pprgHypotheses = A pointer to an array of HYPOTHESIS structures.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td
/// width="60%"> One or more parameters has not been provided correctly. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_NOTIMPL</b></dt> </dl> </td> <td width="60%"> This optional method is not implemented. </td> </tr>
/// <tr> <td width="40%"> <dl> <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td width="60%"> The caller does not
/// have sufficient privileges to perform the diagnosis or repair operation. </td> </tr> <tr> <td width="40%">
/// <dl> <dt><b>E_ABORT</b></dt> </dl> </td> <td width="60%"> The diagnosis or repair operation has been
/// canceled. </td> </tr> </table> Helper Class Extensions may return HRESULTS that are specific to the failures
/// encountered in the function.
///
HRESULT GetHigherHypotheses(uint* pcelt, HYPOTHESIS** pprgHypotheses);
///The <b>GetUpStreamHypotheses</b> method asks the Helper Class Extension to generate hypotheses for possible
///causes of high utilization in the upstream network components that depend on it.
///Params:
/// pcelt = A pointer to a count of elements in the <b>HYPOTHESIS</b> array.
/// pprgHypotheses = A pointer to a HYPOTHESIS array.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td
/// width="60%"> One or more parameters has not been provided correctly. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_NOTIMPL</b></dt> </dl> </td> <td width="60%"> This optional method is not implemented. </td> </tr>
/// <tr> <td width="40%"> <dl> <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td width="60%"> The caller does not
/// have sufficient privileges to perform the diagnosis or repair operation. </td> </tr> <tr> <td width="40%">
/// <dl> <dt><b>E_ABORT</b></dt> </dl> </td> <td width="60%"> The diagnosis or repair operation has been
/// canceled. </td> </tr> </table> Helper Class Extensions may return HRESULTS that are specific to the failures
/// encountered in the function.
///
HRESULT GetUpStreamHypotheses(uint* pcelt, HYPOTHESIS** pprgHypotheses);
///The <b>Repair</b> method performs a repair specified by the input parameter.
///Params:
/// pInfo = A pointer to a RepairInfo structure.
/// pDeferredTime = A pointer to the time, in seconds, to be deferred if the repair cannot be started immediately. This is only
/// valid when the pStatus parameter is set to <b>DS_DEFERRED</b>.
/// pStatus = A pointer to the REPAIR_STATUS that is returned from the repair.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td
/// width="60%"> One or more parameters has not been provided correctly. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_NOTIMPL</b></dt> </dl> </td> <td width="60%"> This optional method is not implemented. </td> </tr>
/// <tr> <td width="40%"> <dl> <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td width="60%"> The caller does not
/// have sufficient privileges to perform the diagnosis or repair operation. </td> </tr> <tr> <td width="40%">
/// <dl> <dt><b>E_ABORT</b></dt> </dl> </td> <td width="60%"> The diagnosis or repair operation has been
/// canceled. </td> </tr> </table> Helper Class Extensions may return HRESULTS that are specific to the failures
/// encountered in the function.
///
HRESULT Repair(RepairInfo* pInfo, int* pDeferredTime, REPAIR_STATUS* pStatus);
///The <b>Validate</b> method is called by NDF after a repair is successfully completed in order to validate that a
///previously diagnosed problem has been fixed.
///Params:
/// problem = The PROBLEM_TYPE that the helper class has previously diagnosed.
/// pDeferredTime = A pointer to the time to be deferred, in seconds, if the diagnosis cannot be started immediately. This is
/// used only when the pStatus member is set to <b>DS_DEFERRED</b>.
/// pStatus = A pointer to the DIAGNOSIS_STATUS that is returned from the diagnosis.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td
/// width="60%"> One or more parameters has not been provided correctly. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_NOTIMPL</b></dt> </dl> </td> <td width="60%"> This optional method is not implemented. </td> </tr>
/// <tr> <td width="40%"> <dl> <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td width="60%"> The caller does not
/// have sufficient privileges to perform the diagnosis or repair operation. </td> </tr> <tr> <td width="40%">
/// <dl> <dt><b>E_ABORT</b></dt> </dl> </td> <td width="60%"> The diagnosis or repair operation has been
/// canceled. </td> </tr> </table> Helper Class Extensions may return HRESULTS that are specific to the failures
/// encountered in the function.
///
HRESULT Validate(PROBLEM_TYPE problem, int* pDeferredTime, REPAIR_STATUS* pStatus);
///The <b>GetRepairInfo</b> method retrieves the repair information that the Helper Class Extension has for a given
///problem type.
///Params:
/// problem = A PROBLEM_TYPE value that specifies the problem type that the helper class has previously diagnosed.
/// pcelt = A pointer to a count of elements in the <b>RepairInfo</b> array.
/// ppInfo = A pointer to an array of RepairInfo structures.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td
/// width="60%"> One or more parameters has not been provided correctly. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_NOTIMPL</b></dt> </dl> </td> <td width="60%"> This optional method is not implemented. </td> </tr>
/// <tr> <td width="40%"> <dl> <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td width="60%"> The caller does not
/// have sufficient privileges to perform the diagnosis or repair operation. </td> </tr> <tr> <td width="40%">
/// <dl> <dt><b>E_ABORT</b></dt> </dl> </td> <td width="60%"> The diagnosis or repair operation has been
/// canceled. </td> </tr> </table> Helper Class Extensions may return HRESULTS that are specific to the failures
/// encountered in the function.
///
HRESULT GetRepairInfo(PROBLEM_TYPE problem, uint* pcelt, RepairInfo** ppInfo);
///The <b>GetLifeTime</b> method retrieves the lifetime of the Helper Class Extension instance.
///Params:
/// pLifeTime = A pointer to a LIFE_TIME structure.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td
/// width="60%"> One or more parameters has not been provided correctly. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_NOTIMPL</b></dt> </dl> </td> <td width="60%"> This optional method is not implemented. </td> </tr>
/// <tr> <td width="40%"> <dl> <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td width="60%"> The caller does not
/// have sufficient privileges to perform the diagnosis or repair operation. </td> </tr> <tr> <td width="40%">
/// <dl> <dt><b>E_ABORT</b></dt> </dl> </td> <td width="60%"> The diagnosis or repair operation has been
/// canceled. </td> </tr> </table> Helper Class Extensions may return HRESULTS that are specific to the failures
/// encountered in the function.
///
HRESULT GetLifeTime(LIFE_TIME* pLifeTime);
///The <b>SetLifeTime</b> method is called by NDF to set the start and end time of interest to diagnostics so that
///the Helper Class Extension can limit its diagnosis to events within that time period.
///Params:
/// lifeTime = A LIFE_TIME structure.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td
/// width="60%"> One or more parameters has not been provided correctly. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_NOTIMPL</b></dt> </dl> </td> <td width="60%"> This optional method is not implemented. </td> </tr>
/// <tr> <td width="40%"> <dl> <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td width="60%"> The caller does not
/// have sufficient privileges to perform the diagnosis or repair operation. </td> </tr> <tr> <td width="40%">
/// <dl> <dt><b>E_ABORT</b></dt> </dl> </td> <td width="60%"> The diagnosis or repair operation has been
/// canceled. </td> </tr> </table> Helper Class Extensions may return HRESULTS that are specific to the failures
/// encountered in the function.
///
HRESULT SetLifeTime(LIFE_TIME lifeTime);
///The <b>GetCacheTime</b> method specifies the time when cached results of a diagnosis and repair operation have
///expired.
///Params:
/// pCacheTime = A pointer to a FILETIME structure.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td
/// width="60%"> One or more parameters has not been provided correctly. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_NOTIMPL</b></dt> </dl> </td> <td width="60%"> This optional method is not implemented. </td> </tr>
/// <tr> <td width="40%"> <dl> <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td width="60%"> The caller does not
/// have sufficient privileges to perform the diagnosis or repair operation. </td> </tr> <tr> <td width="40%">
/// <dl> <dt><b>E_ABORT</b></dt> </dl> </td> <td width="60%"> The diagnosis or repair operation has been
/// canceled. </td> </tr> </table> Helper Class Extensions may return HRESULTS that are specific to the failures
/// encountered in the function.
///
HRESULT GetCacheTime(FILETIME* pCacheTime);
///The <b>GetAttributes</b> method retrieves additional information about a problem that the helper class extension
///has diagnosed.
///Params:
/// pcelt = A pointer to a count of elements in the <b>HELPER_ATTRIBUTE</b> array.
/// pprgAttributes = A pointer to an array of HELPER_ATTRIBUTE structures.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td
/// width="60%"> One or more parameters has not been provided correctly. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_NOTIMPL</b></dt> </dl> </td> <td width="60%"> This optional method is not implemented. </td> </tr>
/// <tr> <td width="40%"> <dl> <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td width="60%"> The caller does not
/// have sufficient privileges to perform the diagnosis or repair operation. </td> </tr> <tr> <td width="40%">
/// <dl> <dt><b>E_ABORT</b></dt> </dl> </td> <td width="60%"> The diagnosis or repair operation has been
/// canceled. </td> </tr> </table> Helper Class Extensions may return HRESULTS that are specific to the failures
/// encountered in the function.
///
HRESULT GetAttributes(uint* pcelt, HELPER_ATTRIBUTE** pprgAttributes);
///The <b>Cancel</b> method cancels an ongoing diagnosis or repair.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td
/// width="60%"> The caller does not have sufficient privileges to perform the diagnosis or repair operation.
/// </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_ABORT</b></dt> </dl> </td> <td width="60%"> The diagnosis or
/// repair operation has been canceled. </td> </tr> </table> Helper Class Extensions may return HRESULTS that are
/// specific to the failures encountered in the function.
///
HRESULT Cancel();
///The <b>Cleanup</b> method allows the Helper Class Extension to clean up resources following a diagnosis or repair
///operation.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td
/// width="60%"> The caller does not have sufficient privileges to perform the diagnosis or repair operation.
/// </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_ABORT</b></dt> </dl> </td> <td width="60%"> The diagnosis or
/// repair operation has been canceled. </td> </tr> </table> Helper Class Extensions may return HRESULTS that are
/// specific to the failures encountered in the function.
///
HRESULT Cleanup();
}
///The <b>INetDiagHelperUtilFactory</b> interface provides a reserved method that is used by the Network Diagnostics
///Framework (NDF). This interface is reserved for system use.
@GUID("104613FB-BC57-4178-95BA-88809698354A")
interface INetDiagHelperUtilFactory : IUnknown
{
///The CreateUtilityInstance method is used by the Network Diagnostics Framework (NDF). This method is reserved for
///system use.
///Params:
/// riid = Reserved for system use.
/// ppvObject = Reserved for system use.
///Returns:
/// This method does not return a value.
///
HRESULT CreateUtilityInstance(const(GUID)* riid, void** ppvObject);
}
///The <b>INetDiagHelperEx</b> interface provides methods that extend on the INetDiagHelper interface to capture and
///provide information associated with diagnoses and resolution of network-related issues.
@GUID("972DAB4D-E4E3-4FC6-AE54-5F65CCDE4A15")
interface INetDiagHelperEx : IUnknown
{
///The <b>ReconfirmLowHealth</b> method is used to add a second Low Health pass after hypotheses have been diagnosed
///and before repairs are retrieved. This method allows the helper class to see the diagnostics results and to
///change the diagnosis if needed. The method is only called if a diagnosis is not rejected and hypotheses were
///generated.
///Params:
/// celt = The number of HypothesisResult structures pointed to by <i>pResults</i>.
/// pResults = Pointer to HypothesisResult structure(s) containing the HYPOTHESIS information obtained via the
/// GetLowerHypotheses method along with the status of that hypothesis. Includes one <b>HypothesisResult</b>
/// structure for each hypothesis generated by the helper class's call to <b>GetLowerHypotheses</b>.
/// ppwszUpdatedDescription = An updated description of the incident being diagnosed.
/// pUpdatedStatus = A DIAGNOSIS_STATUS value which indicates the status of the incident.
///Returns:
/// Possible return values include, but are not limited to, the following. <table> <tr> <th>Return code</th>
/// <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt> </dl> </td> <td width="60%"> The
/// operation succeeded. </td> </tr> </table> Any result other than S_OK will be interpreted as an error and will
/// cause the function results to be discarded.
///
HRESULT ReconfirmLowHealth(uint celt, HypothesisResult* pResults, PWSTR* ppwszUpdatedDescription,
DIAGNOSIS_STATUS* pUpdatedStatus);
///The <b>SetUtilities</b> method is used by the Network Diagnostics Framework (NDF). This method is reserved for
///system use.
///Params:
/// pUtilities = Reserved for system use.
///Returns:
/// This method does not return a value.
///
HRESULT SetUtilities(INetDiagHelperUtilFactory pUtilities);
///The <b>ReproduceFailure</b> method is used by the Network Diagnostics Framework (NDF). This method is reserved
///for system use.
///Returns:
/// This method does not return a value.
///
HRESULT ReproduceFailure();
}
///The <b>INetDiagHelperInfo</b> interface provides a method that is called by the Network Diagnostics Framework (NDF)
///when it needs to validate that it has the necessary information for a helper class and that it has chosen the correct
///helper class.
@GUID("C0B35747-EBF5-11D8-BBE9-505054503030")
interface INetDiagHelperInfo : IUnknown
{
///The <b>GetAttributeInfo</b> method retrieves the list of key parameters needed by the Helper Class Extension.
///Params:
/// pcelt = A pointer to a count of elements in the array pointed to by <i>pprgAttributeInfos</i>.
/// pprgAttributeInfos = A pointer to an array of HelperAttributeInfo structures that contain helper class key parameters.
///Returns:
/// <table> <tr> <th>Return code</th> <th>Description</th> </tr> <tr> <td width="40%"> <dl> <dt><b>S_OK</b></dt>
/// </dl> </td> <td width="60%"> The operation succeeded. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_OUTOFMEMORY</b></dt> </dl> </td> <td width="60%"> There is not enough memory available to complete
/// this operation. </td> </tr> <tr> <td width="40%"> <dl> <dt><b>E_INVALIDARG</b></dt> </dl> </td> <td
/// width="60%"> One or more parameters has not been provided correctly. </td> </tr> <tr> <td width="40%"> <dl>
/// <dt><b>E_ACCESSDENIED</b></dt> </dl> </td> <td width="60%"> The caller does not have sufficient privileges to
/// perform the diagnosis or repair operation. </td> </tr> </table> Helper Class Extensions may return HRESULTS
/// that are specific to the diagnoses or repairs.
///
HRESULT GetAttributeInfo(uint* pcelt, HelperAttributeInfo** pprgAttributeInfos);
}
@GUID("C0B35748-EBF5-11D8-BBE9-505054503030")
interface INetDiagExtensibleHelper : IUnknown
{
HRESULT ResolveAttributes(uint celt, HELPER_ATTRIBUTE* rgKeyAttributes, uint* pcelt,
HELPER_ATTRIBUTE** prgMatchValues);
}
// GUIDs
const GUID IID_INetDiagExtensibleHelper = GUIDOF!INetDiagExtensibleHelper;
const GUID IID_INetDiagHelper = GUIDOF!INetDiagHelper;
const GUID IID_INetDiagHelperEx = GUIDOF!INetDiagHelperEx;
const GUID IID_INetDiagHelperInfo = GUIDOF!INetDiagHelperInfo;
const GUID IID_INetDiagHelperUtilFactory = GUIDOF!INetDiagHelperUtilFactory;
| D |
void main() { runSolver(); }
void problem() {
auto S = scan;
auto solve() {
return S.countUntil!(c => c < 'a') + 1;
}
outputForAtCoder(&solve);
}
// ----------------------------------------------
import std;
T[][] combinations(T)(T[] s, in long m) { if (!m) return [[]]; if (s.empty) return []; return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
T[][] scan(T)(long h, long w){ return scan!T(w * h).chunks(w).array; }
void deb(T ...)(T t){ debug writeln(t); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
else static if (is(T == void)) fn();
else static if (is(T == string)) fn().writeln;
else static if (isInputRange!T) {
static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
else foreach(r; fn()) r.writeln;
}
else fn().writeln;
}
void runSolver() {
static import std.datetime.stopwatch;
enum BORDER = "==================================";
debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(std.datetime.stopwatch.benchmark!problem(1)); BORDER.writeln; } }
else problem();
}
enum YESNO = [true: "Yes", false: "No"];
// -----------------------------------------------
| D |
/Users/sjwu/video/HouseHold/Build/Intermediates/Pods.build/Debug-iphonesimulator/SnapKit.build/Objects-normal/x86_64/LayoutConstraint.o : /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintDSL.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintLayoutSupportDSL.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintViewDSL.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintLayoutGuide.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMakerExtendable.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMakerRelatable.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMakerEditable.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMakerFinalizable.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintConfig.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/Debugging.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintItem.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/LayoutConstraintItem.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintRelation.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintDescription.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMaker.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/Typealiases.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintAttributes.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintView+Extensions.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintInsets.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintRelatableTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMultiplierTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintOffsetTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintInsetTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintConstantTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintPriorityTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/Constraint.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/LayoutConstraint.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintLayoutSupport.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintView.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintPriority.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/sjwu/video/HouseHold/Pods/Target\ Support\ Files/SnapKit/SnapKit-umbrella.h /Users/sjwu/video/HouseHold/Build/Intermediates/Pods.build/Debug-iphonesimulator/SnapKit.build/unextended-module.modulemap
/Users/sjwu/video/HouseHold/Build/Intermediates/Pods.build/Debug-iphonesimulator/SnapKit.build/Objects-normal/x86_64/LayoutConstraint~partial.swiftmodule : /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintDSL.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintLayoutSupportDSL.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintViewDSL.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintLayoutGuide.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMakerExtendable.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMakerRelatable.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMakerEditable.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMakerFinalizable.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintConfig.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/Debugging.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintItem.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/LayoutConstraintItem.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintRelation.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintDescription.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMaker.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/Typealiases.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintAttributes.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintView+Extensions.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintInsets.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintRelatableTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMultiplierTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintOffsetTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintInsetTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintConstantTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintPriorityTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/Constraint.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/LayoutConstraint.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintLayoutSupport.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintView.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintPriority.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/sjwu/video/HouseHold/Pods/Target\ Support\ Files/SnapKit/SnapKit-umbrella.h /Users/sjwu/video/HouseHold/Build/Intermediates/Pods.build/Debug-iphonesimulator/SnapKit.build/unextended-module.modulemap
/Users/sjwu/video/HouseHold/Build/Intermediates/Pods.build/Debug-iphonesimulator/SnapKit.build/Objects-normal/x86_64/LayoutConstraint~partial.swiftdoc : /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintDSL.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintLayoutSupportDSL.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintViewDSL.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintLayoutGuide.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMakerExtendable.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMakerRelatable.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMakerEditable.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMakerFinalizable.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintConfig.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/Debugging.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintItem.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/LayoutConstraintItem.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintRelation.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintDescription.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMaker.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/Typealiases.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintAttributes.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintView+Extensions.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintInsets.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintRelatableTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintMultiplierTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintOffsetTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintInsetTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintConstantTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintPriorityTarget.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/Constraint.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/LayoutConstraint.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintLayoutSupport.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintView.swift /Users/sjwu/video/HouseHold/Pods/SnapKit/Source/ConstraintPriority.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/sjwu/video/HouseHold/Pods/Target\ Support\ Files/SnapKit/SnapKit-umbrella.h /Users/sjwu/video/HouseHold/Build/Intermediates/Pods.build/Debug-iphonesimulator/SnapKit.build/unextended-module.modulemap
| D |
module cqrslib.base;
import std.traits, std.conv;
import vibe.data.json;
class GenericId {
string id;
this(string id) pure {
this.id = id;
}
this(string id) immutable pure {
this.id = id;
}
override const string toString() {
return classToString(this, id);
}
override bool opEquals(Object o) {
auto that = cast(GenericId)o;
if (that !is null) {
return this.id == that.id;
} else {
return false;
}
}
void validate() const
{
import std.regex, std.uuid;
auto r = matchFirst(id, regex("^" ~ uuidRegex ~ "$"));
if (r.empty) {
throw new Exception("Illegal id: " ~ id ~ " does not match: " ~ uuidRegex);
}
}
}
string currentThreadId()
{
import core.thread;
auto t = Thread.getThis;
string name = t.name;
if (name && name.length > 0)
{
return name;
}
else
{
return "Thread#" ~ text(t.toHash);
}
}
unittest {
auto id = "c5143565-ef1a-4084-a17b-59132edbb55a";
// Should be possible to create both mutable and immutable GenericIds
auto a = new GenericId(id);
auto b = new immutable GenericId(id);
}
private string stringOf(A)(A a) {
static if (isSomeString!A) return "\"" ~ a ~ "\"";
else static if (isSomeChar!A) return "'" ~ text(a) ~ "'";
else return text(a);
}
private string varargsToList(A...)(A a) {
static if (a.length == 0) return "";
else static if (a.length == 1) return stringOf(a[0]);
else return stringOf(a[0]) ~ ", " ~ varargsToList(a[1..$]);
}
private string lastPartOf(string input) {
import std.string;
auto i = input.lastIndexOf('.');
return input[i+1..$];
}
string classToString(A...)(inout Object self, A a) {
static if (a.length == 0) return lastPartOf(self.classinfo.name) ~ "()";
else return lastPartOf(self.classinfo.name) ~ "(" ~ varargsToList(a) ~ ")";
} | D |
module simplepng.filters;
//import std.range,
// std.file,
// std.array,
// std.string,
// std.stdio,
// std.exception;
import std.stdio, std.file, std.bitmanip;
//import std.range.primitives : empty;
import std.bitmanip: read;
import std.zlib: compress, uncompress;
import std.math: floor;
import simplepng.headers;
import simplepng.exceptions;
class PNGFilter {
//
// Filter functions
// used when encoding PNGs
// https://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters
//
static ubyte Filter(uint type, ubyte orig, ubyte a = 0, ubyte b = 0, ubyte c = 0) {
switch (type) {
case 0:
return orig;
case 1:
return FilterSub(orig, a);
case 2:
return FilterUp(orig, b);
case 3:
return FilterAverage(orig, a, b);
case 4:
return FilterPaeth(orig, a, b, c);
default:
assert(0);
}
}
// Type 1
private static ubyte FilterSub(ubyte x, ubyte a) {
return cast(ubyte)(x - a);
}
// Type 2
private static ubyte FilterUp(ubyte x, ubyte b) {
return cast(ubyte)(x - b);
}
// Type 3
private static ubyte FilterAverage(ubyte x, ubyte a, ubyte b) {
return cast(ubyte)(x - (a + b) / 2);
}
// Type 4
private static ubyte FilterPaeth(ubyte x, ubyte a, ubyte b, ubyte c) {
throw new PNGException("The Paeth filter method is currently unsupported");
//return 0;
}
//
// Reconstruction functions
// used when decoding a PNG
//
static ubyte Recon(uint type, ubyte orig, ubyte a = 0, ubyte b = 0, ubyte c = 0) {
switch (type) {
case 0:
return orig;
case 1:
return ReconSub(orig, a);
case 2:
return ReconUp(orig, b);
case 3:
return ReconAverage(orig, a, b);
case 4:
return ReconPaeth(orig, a, b, c);
default:
assert(0);
}
}
// Type 1
private static ubyte ReconSub(ubyte x, ubyte a) {
auto uf = x + a;
return cast(ubyte)uf;
}
// Type 2
private static ubyte ReconUp(ubyte x, ubyte b) {
auto uf = x + b;
return cast(ubyte)uf;
}
// Type 3
private static ubyte ReconAverage(ubyte x, ubyte a, ubyte b) {
auto uf = x + (a + b) / 2;
return cast(ubyte)uf;
}
// Type 4
private static ubyte ReconPaeth(ubyte x, ubyte a, ubyte b, ubyte c) {
throw new PNGException("The Paeth filter method is currently unsupported");
//return 0;
}
} | D |
// Written in the D programming language.
/**
Facilities for random number generation.
The new-style generator objects hold their own state so they are
immune of threading issues. The generators feature a number of
well-known and well-documented methods of generating random
numbers. An overall fast and reliable means to generate random numbers
is the $(D_PARAM Mt19937) generator, which derives its name from
"$(LUCKY Mersenne Twister) with a period of 2 to the power of
19937". In memory-constrained situations, $(LUCKY linear congruential)
generators such as $(D MinstdRand0) and $(D MinstdRand) might be
useful. The standard library provides an alias $(D_PARAM Random) for
whichever generator it considers the most fit for the target
environment.
Example:
----
// Generate a uniformly-distributed integer in the range [0, 14]
auto i = uniform(0, 15);
// Generate a uniformly-distributed real in the range [0, 100$(RPAREN)
// using a specific random generator
Random gen;
auto r = uniform(0.0L, 100.0L, gen);
----
In addition to random number generators, this module features
distributions, which skew a generator's output statistical
distribution in various ways. So far the uniform distribution for
integers and real numbers have been implemented.
Source: $(PHOBOSSRC std/_random.d)
Macros:
WIKI = Phobos/StdRandom
Copyright: Copyright Andrei Alexandrescu 2008 - 2009, Joseph Rushton Wakeling 2012.
License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
Authors: $(WEB erdani.org, Andrei Alexandrescu)
Masahiro Nakagawa (Xorshift randome generator)
$(WEB braingam.es, Joseph Rushton Wakeling) (Algorithm D for random sampling)
Credits: The entire random number library architecture is derived from the
excellent $(WEB open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf, C++0X)
random number facility proposed by Jens Maurer and contributed to by
researchers at the Fermi laboratory(excluding Xorshift).
*/
/*
Copyright Andrei Alexandrescu 2008 - 2009.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
module std.random;
import std.algorithm, std.c.time, std.conv, std.exception,
std.math, std.numeric, std.range, std.traits,
core.thread, core.time;
import std.string : format;
version(unittest) import std.typetuple;
// Segments of the code in this file Copyright (c) 1997 by Rick Booth
// From "Inner Loops" by Rick Booth, Addison-Wesley
// Work derived from:
/*
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/
/**
* Test if Rng is a random-number generator. The overload
* taking a ElementType also makes sure that the Rng generates
* values of that type.
*
* A random-number generator has at least the following features:
* $(UL
* $(LI it's an InputRange)
* $(LI it has a 'bool isUniformRandom' field readable in CTFE)
* )
*/
template isUniformRNG(Rng, ElementType)
{
enum bool isUniformRNG = isInputRange!Rng &&
is(typeof(Rng.front) == ElementType) &&
is(typeof(
{
static assert(Rng.isUniformRandom); //tag
}));
}
/**
* ditto
*/
template isUniformRNG(Rng)
{
enum bool isUniformRNG = isInputRange!Rng &&
is(typeof(
{
static assert(Rng.isUniformRandom); //tag
}));
}
/**
* Test if Rng is seedable. The overload
* taking a SeedType also makes sure that the Rng can be seeded with SeedType.
*
* A seedable random-number generator has the following additional features:
* $(UL
* $(LI it has a 'seed(ElementType)' function)
* )
*/
template isSeedable(Rng, SeedType)
{
enum bool isSeedable = isUniformRNG!(Rng) &&
is(typeof(
{
Rng r = void; // can define a Rng object
r.seed(SeedType.init); // can seed a Rng
}));
}
///ditto
template isSeedable(Rng)
{
enum bool isSeedable = isUniformRNG!Rng &&
is(typeof(
{
Rng r = void; // can define a Rng object
r.seed(typeof(r.front).init); // can seed a Rng
}));
}
unittest
{
struct NoRng
{
@property uint front() {return 0;}
@property bool empty() {return false;}
void popFront() {}
}
static assert(!isUniformRNG!(NoRng, uint));
static assert(!isUniformRNG!(NoRng));
static assert(!isSeedable!(NoRng, uint));
static assert(!isSeedable!(NoRng));
struct NoRng2
{
@property uint front() {return 0;}
@property bool empty() {return false;}
void popFront() {}
enum isUniformRandom = false;
}
static assert(!isUniformRNG!(NoRng2, uint));
static assert(!isUniformRNG!(NoRng2));
static assert(!isSeedable!(NoRng2, uint));
static assert(!isSeedable!(NoRng2));
struct NoRng3
{
@property bool empty() {return false;}
void popFront() {}
enum isUniformRandom = true;
}
static assert(!isUniformRNG!(NoRng3, uint));
static assert(!isUniformRNG!(NoRng3));
static assert(!isSeedable!(NoRng3, uint));
static assert(!isSeedable!(NoRng3));
struct validRng
{
@property uint front() {return 0;}
@property bool empty() {return false;}
void popFront() {}
enum isUniformRandom = true;
}
static assert(isUniformRNG!(validRng, uint));
static assert(isUniformRNG!(validRng));
static assert(!isSeedable!(validRng, uint));
static assert(!isSeedable!(validRng));
struct seedRng
{
@property uint front() {return 0;}
@property bool empty() {return false;}
void popFront() {}
void seed(uint val){}
enum isUniformRandom = true;
}
static assert(isUniformRNG!(seedRng, uint));
static assert(isUniformRNG!(seedRng));
static assert(isSeedable!(seedRng, uint));
static assert(isSeedable!(seedRng));
}
/**
Linear Congruential generator.
*/
struct LinearCongruentialEngine(UIntType, UIntType a, UIntType c, UIntType m)
if(isUnsigned!UIntType)
{
///Mark this as a Rng
enum bool isUniformRandom = true;
/// Does this generator have a fixed range? ($(D_PARAM true)).
enum bool hasFixedRange = true;
/// Lowest generated value ($(D 1) if $(D c == 0), $(D 0) otherwise).
enum UIntType min = ( c == 0 ? 1 : 0 );
/// Highest generated value ($(D modulus - 1)).
enum UIntType max = m - 1;
/**
The parameters of this distribution. The random number is $(D_PARAM x
= (x * multipler + increment) % modulus).
*/
enum UIntType multiplier = a;
///ditto
enum UIntType increment = c;
///ditto
enum UIntType modulus = m;
static assert(isIntegral!(UIntType));
static assert(m == 0 || a < m);
static assert(m == 0 || c < m);
static assert(m == 0 ||
(cast(ulong)a * (m-1) + c) % m == (c < a ? c - a + m : c - a));
// Check for maximum range
private static ulong gcd(ulong a, ulong b)
{
while (b)
{
auto t = b;
b = a % b;
a = t;
}
return a;
}
private static ulong primeFactorsOnly(ulong n)
{
ulong result = 1;
ulong iter = 2;
for (; n >= iter * iter; iter += 2 - (iter == 2))
{
if (n % iter) continue;
result *= iter;
do
{
n /= iter;
} while (n % iter == 0);
}
return result * n;
}
unittest
{
static assert(primeFactorsOnly(100) == 10);
//writeln(primeFactorsOnly(11));
static assert(primeFactorsOnly(11) == 11);
static assert(primeFactorsOnly(7 * 7 * 7 * 11 * 15 * 11) == 7 * 11 * 15);
static assert(primeFactorsOnly(129 * 2) == 129 * 2);
// enum x = primeFactorsOnly(7 * 7 * 7 * 11 * 15);
// static assert(x == 7 * 11 * 15);
}
private static bool properLinearCongruentialParameters(ulong m,
ulong a, ulong c)
{
if (m == 0)
{
static if (is(UIntType == uint))
{
// Assume m is uint.max + 1
m = (1uL << 32);
}
else
{
return false;
}
}
// Bounds checking
if (a == 0 || a >= m || c >= m) return false;
// c and m are relatively prime
if (c > 0 && gcd(c, m) != 1) return false;
// a - 1 is divisible by all prime factors of m
if ((a - 1) % primeFactorsOnly(m)) return false;
// if a - 1 is multiple of 4, then m is a multiple of 4 too.
if ((a - 1) % 4 == 0 && m % 4) return false;
// Passed all tests
return true;
}
// check here
static assert(c == 0 || properLinearCongruentialParameters(m, a, c),
"Incorrect instantiation of LinearCongruentialEngine");
/**
Constructs a $(D_PARAM LinearCongruentialEngine) generator seeded with
$(D x0).
*/
this(UIntType x0)
{
seed(x0);
}
/**
(Re)seeds the generator.
*/
void seed(UIntType x0 = 1)
{
static if (c == 0)
{
enforce(x0, "Invalid (zero) seed for "
~ LinearCongruentialEngine.stringof);
}
_x = modulus ? (x0 % modulus) : x0;
popFront();
}
/**
Advances the random sequence.
*/
void popFront()
{
static if (m)
{
static if (is(UIntType == uint) && m == uint.max)
{
immutable ulong
x = (cast(ulong) a * _x + c),
v = x >> 32,
w = x & uint.max;
immutable y = cast(uint)(v + w);
_x = (y < v || y == uint.max) ? (y + 1) : y;
}
else static if (is(UIntType == uint) && m == int.max)
{
immutable ulong
x = (cast(ulong) a * _x + c),
v = x >> 31,
w = x & int.max;
immutable uint y = cast(uint)(v + w);
_x = (y >= int.max) ? (y - int.max) : y;
}
else
{
_x = cast(UIntType) ((cast(ulong) a * _x + c) % m);
}
}
else
{
_x = a * _x + c;
}
}
/**
Returns the current number in the random sequence.
*/
@property UIntType front()
{
return _x;
}
///
@property typeof(this) save()
{
return this;
}
/**
Always $(D false) (random generators are infinite ranges).
*/
enum bool empty = false;
/**
Compares against $(D_PARAM rhs) for equality.
*/
bool opEquals(ref const LinearCongruentialEngine rhs) const
{
return _x == rhs._x;
}
private UIntType _x = m ? (a + c) % m : (a + c);
}
/**
Define $(D_PARAM LinearCongruentialEngine) generators with well-chosen
parameters. $(D MinstdRand0) implements Park and Miller's "minimal
standard" $(WEB
wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator,
generator) that uses 16807 for the multiplier. $(D MinstdRand)
implements a variant that has slightly better spectral behavior by
using the multiplier 48271. Both generators are rather simplistic.
Example:
----
// seed with a constant
auto rnd0 = MinstdRand0(1);
auto n = rnd0.front; // same for each run
// Seed with an unpredictable value
rnd0.seed(unpredictableSeed);
n = rnd0.front; // different across runs
----
*/
alias MinstdRand0 = LinearCongruentialEngine!(uint, 16807, 0, 2147483647);
/// ditto
alias MinstdRand = LinearCongruentialEngine!(uint, 48271, 0, 2147483647);
unittest
{
static assert(isForwardRange!MinstdRand);
static assert(isUniformRNG!MinstdRand);
static assert(isUniformRNG!MinstdRand0);
static assert(isUniformRNG!(MinstdRand, uint));
static assert(isUniformRNG!(MinstdRand0, uint));
static assert(isSeedable!MinstdRand);
static assert(isSeedable!MinstdRand0);
static assert(isSeedable!(MinstdRand, uint));
static assert(isSeedable!(MinstdRand0, uint));
// The correct numbers are taken from The Database of Integer Sequences
// http://www.research.att.com/~njas/sequences/eisBTfry00128.txt
auto checking0 = [
16807UL,282475249,1622650073,984943658,1144108930,470211272,
101027544,1457850878,1458777923,2007237709,823564440,1115438165,
1784484492,74243042,114807987,1137522503,1441282327,16531729,
823378840,143542612 ];
//auto rnd0 = MinstdRand0(1);
MinstdRand0 rnd0;
foreach (e; checking0)
{
assert(rnd0.front == e);
rnd0.popFront();
}
// Test the 10000th invocation
// Correct value taken from:
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf
rnd0.seed();
popFrontN(rnd0, 9999);
assert(rnd0.front == 1043618065);
// Test MinstdRand
auto checking = [48271UL,182605794,1291394886,1914720637,2078669041,
407355683];
//auto rnd = MinstdRand(1);
MinstdRand rnd;
foreach (e; checking)
{
assert(rnd.front == e);
rnd.popFront();
}
// Test the 10000th invocation
// Correct value taken from:
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf
rnd.seed();
popFrontN(rnd, 9999);
assert(rnd.front == 399268537);
// Check .save works
foreach (Type; TypeTuple!(MinstdRand0, MinstdRand))
{
auto rnd1 = Type(unpredictableSeed);
auto rnd2 = rnd1.save;
assert(rnd1 == rnd2);
// Enable next test when RNGs are reference types
version(none) { assert(rnd1 !is rnd2); }
assert(rnd1.take(100).array() == rnd2.take(100).array());
}
}
/**
The $(LUCKY Mersenne Twister) generator.
*/
struct MersenneTwisterEngine(UIntType, size_t w, size_t n, size_t m, size_t r,
UIntType a, size_t u, size_t s,
UIntType b, size_t t,
UIntType c, size_t l)
if(isUnsigned!UIntType)
{
static assert(0 < w && w <= UIntType.sizeof * 8);
static assert(1 <= m && m <= n);
static assert(0 <= r && 0 <= u && 0 <= s && 0 <= t && 0 <= l);
static assert(r <= w && u <= w && s <= w && t <= w && l <= w);
static assert(0 <= a && 0 <= b && 0 <= c);
///Mark this as a Rng
enum bool isUniformRandom = true;
/**
Parameters for the generator.
*/
enum size_t wordSize = w;
enum size_t stateSize = n; /// ditto
enum size_t shiftSize = m; /// ditto
enum size_t maskBits = r; /// ditto
enum UIntType xorMask = a; /// ditto
enum UIntType temperingU = u; /// ditto
enum size_t temperingS = s; /// ditto
enum UIntType temperingB = b; /// ditto
enum size_t temperingT = t; /// ditto
enum UIntType temperingC = c; /// ditto
enum size_t temperingL = l; /// ditto
/// Smallest generated value (0).
enum UIntType min = 0;
/// Largest generated value.
enum UIntType max = UIntType.max >> (UIntType.sizeof * 8u - w);
static assert(a <= max && b <= max && c <= max);
/// The default seed value.
enum UIntType defaultSeed = 5489u;
/**
Constructs a MersenneTwisterEngine object.
*/
this(UIntType value)
{
seed(value);
}
/**
Seeds a MersenneTwisterEngine object.
Note:
This seed function gives 2^32 starting points. To allow the RNG to be started in any one of its
internal states use the seed overload taking an InputRange.
*/
void seed()(UIntType value = defaultSeed)
{
static if (w == UIntType.sizeof * 8)
{
mt[0] = value;
}
else
{
static assert(max + 1 > 0);
mt[0] = value % (max + 1);
}
for (mti = 1; mti < n; ++mti)
{
mt[mti] =
cast(UIntType)
(1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> (w - 2))) + mti);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
//mt[mti] &= ResultType.max;
/* for >32 bit machines */
}
popFront();
}
/**
Seeds a MersenneTwisterEngine object using an InputRange.
Throws:
$(D Exception) if the InputRange didn't provide enough elements to seed the generator.
The number of elements required is the 'n' template parameter of the MersenneTwisterEngine struct.
Examples:
----------------
Mt19937 gen;
gen.seed(map!((a) => unpredictableSeed)(repeat(0)));
----------------
*/
void seed(T)(T range) if(isInputRange!T && is(Unqual!(ElementType!T) == UIntType))
{
size_t j;
for(j = 0; j < n && !range.empty; ++j, range.popFront())
{
mt[j] = range.front;
}
mti = n;
if(range.empty && j < n)
{
throw new Exception(format("MersenneTwisterEngine.seed: Input range didn't provide enough"~
" elements: Need %s elemnets.", n));
}
popFront();
}
/**
Advances the generator.
*/
void popFront()
{
if (mti == size_t.max) seed();
enum UIntType
upperMask = ~((cast(UIntType) 1u <<
(UIntType.sizeof * 8 - (w - r))) - 1),
lowerMask = (cast(UIntType) 1u << r) - 1;
static immutable UIntType[2] mag01 = [0x0UL, a];
ulong y = void;
if (mti >= n)
{
/* generate N words at one time */
int kk = 0;
const limit1 = n - m;
for (; kk < limit1; ++kk)
{
y = (mt[kk] & upperMask)|(mt[kk + 1] & lowerMask);
mt[kk] = cast(UIntType) (mt[kk + m] ^ (y >> 1)
^ mag01[cast(UIntType) y & 0x1U]);
}
const limit2 = n - 1;
for (; kk < limit2; ++kk)
{
y = (mt[kk] & upperMask)|(mt[kk + 1] & lowerMask);
mt[kk] = cast(UIntType) (mt[kk + (m -n)] ^ (y >> 1)
^ mag01[cast(UIntType) y & 0x1U]);
}
y = (mt[n -1] & upperMask)|(mt[0] & lowerMask);
mt[n - 1] = cast(UIntType) (mt[m - 1] ^ (y >> 1)
^ mag01[cast(UIntType) y & 0x1U]);
mti = 0;
}
y = mt[mti++];
/* Tempering */
y ^= (y >> temperingU);
y ^= (y << temperingS) & temperingB;
y ^= (y << temperingT) & temperingC;
y ^= (y >> temperingL);
_y = cast(UIntType) y;
}
/**
Returns the current random value.
*/
@property UIntType front()
{
if (mti == size_t.max) seed();
return _y;
}
///
@property typeof(this) save()
{
return this;
}
/**
Always $(D false).
*/
enum bool empty = false;
private UIntType[n] mt;
private size_t mti = size_t.max; /* means mt is not initialized */
UIntType _y = UIntType.max;
}
/**
A $(D MersenneTwisterEngine) instantiated with the parameters of the
original engine $(WEB math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html,
MT19937), generating uniformly-distributed 32-bit numbers with a
period of 2 to the power of 19937. Recommended for random number
generation unless memory is severely restricted, in which case a $(D
LinearCongruentialEngine) would be the generator of choice.
Example:
----
// seed with a constant
Mt19937 gen;
auto n = gen.front; // same for each run
// Seed with an unpredictable value
gen.seed(unpredictableSeed);
n = gen.front; // different across runs
----
*/
alias Mt19937 = MersenneTwisterEngine!(uint, 32, 624, 397, 31,
0x9908b0df, 11, 7,
0x9d2c5680, 15,
0xefc60000, 18);
unittest
{
static assert(isUniformRNG!Mt19937);
static assert(isUniformRNG!(Mt19937, uint));
static assert(isSeedable!Mt19937);
static assert(isSeedable!(Mt19937, uint));
static assert(isSeedable!(Mt19937, typeof(map!((a) => unpredictableSeed)(repeat(0)))));
Mt19937 gen;
popFrontN(gen, 9999);
assert(gen.front == 4123659995);
}
unittest
{
Mt19937 gen;
assertThrown(gen.seed(map!((a) => unpredictableSeed)(repeat(0, 623))));
gen.seed(map!((a) => unpredictableSeed)(repeat(0, 624)));
//infinite Range
gen.seed(map!((a) => unpredictableSeed)(repeat(0)));
}
unittest
{
uint a, b;
{
Mt19937 gen;
a = gen.front;
}
{
Mt19937 gen;
gen.popFront();
//popFrontN(gen, 1); // skip 1 element
b = gen.front;
}
assert(a != b);
}
unittest
{
// Check .save works
foreach(Type; TypeTuple!(Mt19937))
{
auto gen1 = Type(unpredictableSeed);
auto gen2 = gen1.save;
assert(gen1 == gen2); // Danger, Will Robinson -- no opEquals for MT
// Enable next test when RNGs are reference types
version(none) { assert(gen1 !is gen2); }
assert(gen1.take(100).array() == gen2.take(100).array());
}
}
unittest //11690
{
alias MT(UIntType, uint w) = MersenneTwisterEngine!(UIntType, w, 624, 397, 31,
0x9908b0df, 11, 7,
0x9d2c5680, 15,
0xefc60000, 18);
foreach (R; TypeTuple!(MT!(uint, 32), MT!(ulong, 32), MT!(ulong, 48), MT!(ulong, 64)))
auto a = R();
}
/**
* Xorshift generator using 32bit algorithm.
*
* Implemented according to $(WEB www.jstatsoft.org/v08/i14/paper, Xorshift RNGs).
*
* $(BOOKTABLE $(TEXTWITHCOMMAS Supporting bits are below, $(D bits) means second parameter of XorshiftEngine.),
* $(TR $(TH bits) $(TH period))
* $(TR $(TD 32) $(TD 2^32 - 1))
* $(TR $(TD 64) $(TD 2^64 - 1))
* $(TR $(TD 96) $(TD 2^96 - 1))
* $(TR $(TD 128) $(TD 2^128 - 1))
* $(TR $(TD 160) $(TD 2^160 - 1))
* $(TR $(TD 192) $(TD 2^192 - 2^32))
* )
*/
struct XorshiftEngine(UIntType, UIntType bits, UIntType a, UIntType b, UIntType c)
if(isUnsigned!UIntType)
{
static assert(bits == 32 || bits == 64 || bits == 96 || bits == 128 || bits == 160 || bits == 192,
"Xorshift supports only 32, 64, 96, 128, 160 and 192 bit versions. "
~ to!string(bits) ~ " is not supported.");
public:
///Mark this as a Rng
enum bool isUniformRandom = true;
/// Always $(D false) (random generators are infinite ranges).
enum empty = false;
/// Smallest generated value.
enum UIntType min = 0;
/// Largest generated value.
enum UIntType max = UIntType.max;
private:
enum size = bits / 32;
static if (bits == 32)
UIntType[size] seeds_ = [2463534242];
else static if (bits == 64)
UIntType[size] seeds_ = [123456789, 362436069];
else static if (bits == 96)
UIntType[size] seeds_ = [123456789, 362436069, 521288629];
else static if (bits == 128)
UIntType[size] seeds_ = [123456789, 362436069, 521288629, 88675123];
else static if (bits == 160)
UIntType[size] seeds_ = [123456789, 362436069, 521288629, 88675123, 5783321];
else static if (bits == 192)
{
UIntType[size] seeds_ = [123456789, 362436069, 521288629, 88675123, 5783321, 6615241];
UIntType value_;
}
else
{
static assert(false, "Phobos Error: Xorshift has no instantiation rule for "
~ to!string(bits) ~ " bits.");
}
public:
/**
* Constructs a $(D XorshiftEngine) generator seeded with $(D_PARAM x0).
*/
@safe
this(UIntType x0)
{
seed(x0);
}
/**
* (Re)seeds the generator.
*/
@safe
nothrow void seed(UIntType x0)
{
// Initialization routine from MersenneTwisterEngine.
foreach (i, e; seeds_)
seeds_[i] = x0 = cast(UIntType)(1812433253U * (x0 ^ (x0 >> 30)) + i + 1);
// All seeds must not be 0.
sanitizeSeeds(seeds_);
popFront();
}
/**
* Returns the current number in the random sequence.
*/
@property @safe
nothrow UIntType front()
{
static if (bits == 192)
return value_;
else
return seeds_[size - 1];
}
/**
* Advances the random sequence.
*/
@safe
nothrow void popFront()
{
UIntType temp;
static if (bits == 32)
{
temp = seeds_[0] ^ (seeds_[0] << a);
temp = temp ^ (temp >> b);
seeds_[0] = temp ^ (temp << c);
}
else static if (bits == 64)
{
temp = seeds_[0] ^ (seeds_[0] << a);
seeds_[0] = seeds_[1];
seeds_[1] = seeds_[1] ^ (seeds_[1] >> c) ^ temp ^ (temp >> b);
}
else static if (bits == 96)
{
temp = seeds_[0] ^ (seeds_[0] << a);
seeds_[0] = seeds_[1];
seeds_[1] = seeds_[2];
seeds_[2] = seeds_[2] ^ (seeds_[2] >> c) ^ temp ^ (temp >> b);
}
else static if (bits == 128)
{
temp = seeds_[0] ^ (seeds_[0] << a);
seeds_[0] = seeds_[1];
seeds_[1] = seeds_[2];
seeds_[2] = seeds_[3];
seeds_[3] = seeds_[3] ^ (seeds_[3] >> c) ^ temp ^ (temp >> b);
}
else static if (bits == 160)
{
temp = seeds_[0] ^ (seeds_[0] << a);
seeds_[0] = seeds_[1];
seeds_[1] = seeds_[2];
seeds_[2] = seeds_[3];
seeds_[3] = seeds_[4];
seeds_[4] = seeds_[4] ^ (seeds_[4] >> c) ^ temp ^ (temp >> b);
}
else static if (bits == 192)
{
temp = seeds_[0] ^ (seeds_[0] >> a);
seeds_[0] = seeds_[1];
seeds_[1] = seeds_[2];
seeds_[2] = seeds_[3];
seeds_[3] = seeds_[4];
seeds_[4] = seeds_[4] ^ (seeds_[4] << c) ^ temp ^ (temp << b);
value_ = seeds_[4] + (seeds_[5] += 362437);
}
else
{
static assert(false, "Phobos Error: Xorshift has no popFront() update for "
~ to!string(bits) ~ " bits.");
}
}
/**
* Captures a range state.
*/
@property
typeof(this) save()
{
return this;
}
/**
* Compares against $(D_PARAM rhs) for equality.
*/
@safe
nothrow bool opEquals(ref const XorshiftEngine rhs) const
{
return seeds_ == rhs.seeds_;
}
private:
@safe
static nothrow void sanitizeSeeds(ref UIntType[size] seeds)
{
for (uint i; i < seeds.length; i++)
{
if (seeds[i] == 0)
seeds[i] = i + 1;
}
}
unittest
{
static if (size == 4) // Other bits too
{
UIntType[size] seeds = [1, 0, 0, 4];
sanitizeSeeds(seeds);
assert(seeds == [1, 2, 3, 4]);
}
}
}
/**
* Define $(D XorshiftEngine) generators with well-chosen parameters. See each bits examples of "Xorshift RNGs".
* $(D Xorshift) is a Xorshift128's alias because 128bits implementation is mostly used.
*
* Example:
* -----
* // Seed with a constant
* auto rnd = Xorshift(1);
* auto num = rnd.front; // same for each run
*
* // Seed with an unpredictable value
* rnd.seed(unpredictableSeed());
* num = rnd.front; // different across runs
* -----
*/
alias Xorshift32 = XorshiftEngine!(uint, 32, 13, 17, 15) ;
alias Xorshift64 = XorshiftEngine!(uint, 64, 10, 13, 10); /// ditto
alias Xorshift96 = XorshiftEngine!(uint, 96, 10, 5, 26); /// ditto
alias Xorshift128 = XorshiftEngine!(uint, 128, 11, 8, 19); /// ditto
alias Xorshift160 = XorshiftEngine!(uint, 160, 2, 1, 4); /// ditto
alias Xorshift192 = XorshiftEngine!(uint, 192, 2, 1, 4); /// ditto
alias Xorshift = Xorshift128; /// ditto
unittest
{
static assert(isForwardRange!Xorshift);
static assert(isUniformRNG!Xorshift);
static assert(isUniformRNG!(Xorshift, uint));
static assert(isSeedable!Xorshift);
static assert(isSeedable!(Xorshift, uint));
// Result from reference implementation.
auto checking = [
[2463534242UL, 901999875, 3371835698, 2675058524, 1053936272, 3811264849, 472493137, 3856898176, 2131710969, 2312157505],
[362436069UL, 2113136921, 19051112, 3010520417, 951284840, 1213972223, 3173832558, 2611145638, 2515869689, 2245824891],
[521288629UL, 1950277231, 185954712, 1582725458, 3580567609, 2303633688, 2394948066, 4108622809, 1116800180, 3357585673],
[88675123UL, 3701687786, 458299110, 2500872618, 3633119408, 516391518, 2377269574, 2599949379, 717229868, 137866584],
[5783321UL, 393427209, 1947109840, 565829276, 1006220149, 971147905, 1436324242, 2800460115, 1484058076, 3823330032],
[0UL, 246875399, 3690007200, 1264581005, 3906711041, 1866187943, 2481925219, 2464530826, 1604040631, 3653403911]
];
alias XorshiftTypes = TypeTuple!(Xorshift32, Xorshift64, Xorshift96, Xorshift128, Xorshift160, Xorshift192);
foreach (I, Type; XorshiftTypes)
{
Type rnd;
foreach (e; checking[I])
{
assert(rnd.front == e);
rnd.popFront();
}
}
// Check .save works
foreach (Type; XorshiftTypes)
{
auto rnd1 = Type(unpredictableSeed);
auto rnd2 = rnd1.save;
assert(rnd1 == rnd2);
// Enable next test when RNGs are reference types
version(none) { assert(rnd1 !is rnd2); }
assert(rnd1.take(100).array() == rnd2.take(100).array());
}
}
/* A complete list of all pseudo-random number generators implemented in
* std.random. This can be used to confirm that a given function or
* object is compatible with all the pseudo-random number generators
* available. It is enabled only in unittest mode.
*
* Example:
*
* ----
* foreach(Rng; PseudoRngTypes)
* {
* static assert(isUniformRng!Rng);
* auto rng = Rng(unpredictableSeed);
* foo(rng);
* }
* ----
*/
version(unittest)
{
package alias PseudoRngTypes = TypeTuple!(MinstdRand0, MinstdRand, Mt19937, Xorshift32, Xorshift64,
Xorshift96, Xorshift128, Xorshift160, Xorshift192);
}
unittest
{
foreach(Rng; PseudoRngTypes)
{
static assert(isUniformRNG!Rng);
}
}
/**
A "good" seed for initializing random number engines. Initializing
with $(D_PARAM unpredictableSeed) makes engines generate different
random number sequences every run.
Example:
----
auto rnd = Random(unpredictableSeed);
auto n = rnd.front;
...
----
*/
@property uint unpredictableSeed()
{
static bool seeded;
static MinstdRand0 rand;
if (!seeded)
{
uint threadID = cast(uint) cast(void*) Thread.getThis();
rand.seed((getpid() + threadID) ^ cast(uint) TickDuration.currSystemTick.length);
seeded = true;
}
rand.popFront();
return cast(uint) (TickDuration.currSystemTick.length ^ rand.front);
}
unittest
{
// not much to test here
auto a = unpredictableSeed;
static assert(is(typeof(a) == uint));
}
/**
The "default", "favorite", "suggested" random number generator type on
the current platform. It is an alias for one of the previously-defined
generators. You may want to use it if (1) you need to generate some
nice random numbers, and (2) you don't care for the minutiae of the
method being used.
*/
alias Random = Mt19937;
unittest
{
static assert(isUniformRNG!Random);
static assert(isUniformRNG!(Random, uint));
static assert(isSeedable!Random);
static assert(isSeedable!(Random, uint));
}
/**
Global random number generator used by various functions in this
module whenever no generator is specified. It is allocated per-thread
and initialized to an unpredictable value for each thread.
*/
@property ref Random rndGen()
{
static Random result;
static bool initialized;
if (!initialized)
{
static if(isSeedable!(Random, typeof(map!((a) => unpredictableSeed)(repeat(0)))))
result.seed(map!((a) => unpredictableSeed)(repeat(0)));
else
result = Random(unpredictableSeed);
initialized = true;
}
return result;
}
/**
Generates a number between $(D a) and $(D b). The $(D boundaries)
parameter controls the shape of the interval (open vs. closed on
either side). Valid values for $(D boundaries) are $(D "[]"), $(D
"$(LPAREN)]"), $(D "[$(RPAREN)"), and $(D "()"). The default interval
is closed to the left and open to the right. The version that does not
take $(D urng) uses the default generator $(D rndGen).
Example:
----
auto gen = Random(unpredictableSeed);
// Generate an integer in [0, 1023]
auto a = uniform(0, 1024, gen);
// Generate a float in [0, 1$(RPAREN)
auto a = uniform(0.0f, 1.0f, gen);
----
*/
auto uniform(string boundaries = "[)", T1, T2)
(T1 a, T2 b) if (!is(CommonType!(T1, T2) == void))
{
return uniform!(boundaries, T1, T2, Random)(a, b, rndGen);
}
unittest
{
MinstdRand0 gen;
foreach (i; 0 .. 20)
{
auto x = uniform(0.0, 15.0, gen);
assert(0 <= x && x < 15);
}
foreach (i; 0 .. 20)
{
auto x = uniform!"[]"('a', 'z', gen);
assert('a' <= x && x <= 'z');
}
foreach (i; 0 .. 20)
{
auto x = uniform('a', 'z', gen);
assert('a' <= x && x < 'z');
}
foreach(i; 0 .. 20)
{
immutable ubyte a = 0;
immutable ubyte b = 15;
auto x = uniform(a, b, gen);
assert(a <= x && x < b);
}
}
// Implementation of uniform for floating-point types
/// ditto
auto uniform(string boundaries = "[)",
T1, T2, UniformRandomNumberGenerator)
(T1 a, T2 b, ref UniformRandomNumberGenerator urng)
if (isFloatingPoint!(CommonType!(T1, T2)) && isUniformRNG!UniformRandomNumberGenerator)
{
alias NumberType = Unqual!(CommonType!(T1, T2));
static if (boundaries[0] == '(')
{
NumberType _a = nextafter(cast(NumberType) a, NumberType.infinity);
}
else
{
NumberType _a = a;
}
static if (boundaries[1] == ')')
{
NumberType _b = nextafter(cast(NumberType) b, -NumberType.infinity);
}
else
{
NumberType _b = b;
}
enforce(_a <= _b,
text("std.random.uniform(): invalid bounding interval ",
boundaries[0], a, ", ", b, boundaries[1]));
NumberType result =
_a + (_b - _a) * cast(NumberType) (urng.front - urng.min)
/ (urng.max - urng.min);
urng.popFront();
return result;
}
// Implementation of uniform for integral types
/+ Description of algorithm and suggestion of correctness:
The modulus operator maps an integer to a small, finite space. For instance, `x
% 3` will map whatever x is into the range [0 .. 3). 0 maps to 0, 1 maps to 1, 2
maps to 2, 3 maps to 0, and so on infinitely. As long as the integer is
uniformly chosen from the infinite space of all non-negative integers then `x %
3` will uniformly fall into that range.
(Non-negative is important in this case because some definitions of modulus,
namely the one used in computers generally, map negative numbers differently to
(-3 .. 0]. `uniform` does not use negative number modulus, thus we can safely
ignore that fact.)
The issue with computers is that integers have a finite space they must fit in,
and our uniformly chosen random number is picked in that finite space. So, that
method is not sufficient. You can look at it as the integer space being divided
into "buckets" and every bucket after the first bucket maps directly into that
first bucket. `[0, 1, 2]`, `[3, 4, 5]`, ... When integers are finite, then the
last bucket has the chance to be "incomplete": `[uint.max - 3, uint.max - 2,
uint.max - 1]`, `[uint.max]` ... (the last bucket only has 1!). The issue here
is that _every_ bucket maps _completely_ to the first bucket except for that
last one. The last one doesn't have corresponding mappings to 1 or 2, in this
case, which makes it unfair.
So, the answer is to simply "reroll" if you're in that last bucket, since it's
the only unfair one. Eventually you'll roll into a fair bucket. Simply, instead
of the meaning of the last bucket being "maps to `[0]`", it changes to "maps to
`[0, 1, 2]`", which is precisely what we want.
To generalize, `upperDist` represents the size of our buckets (and, thus, the
exclusive upper bound for our desired uniform number). `rnum` is a uniformly
random number picked from the space of integers that a computer can hold (we'll
say `UpperType` represents that type).
We'll first try to do the mapping into the first bucket by doing `offset = rnum
% upperDist`. We can figure out the position of the front of the bucket we're in
by `bucketFront = rnum - offset`.
If we start at `UpperType.max` and walk backwards `upperDist - 1` spaces, then
the space we land on is the last acceptable position where a full bucket can
fit:
```
bucketFront UpperType.max
v v
[..., 0, 1, 2, ..., upperDist - 1]
^~~ upperDist - 1 ~~^
```
If the bucket starts any later, then it must have lost at least one number and
at least that number won't be represented fairly.
```
bucketFront UpperType.max
v v
[..., upperDist - 1, 0, 1, 2, ..., upperDist - 2]
^~~~~~~~ upperDist - 1 ~~~~~~~^
```
Hence, our condition to reroll is
`bucketFront > (UpperType.max - (upperDist - 1))`
+/
auto uniform(string boundaries = "[)", T1, T2, RandomGen)
(T1 a, T2 b, ref RandomGen rng)
if ((isIntegral!(CommonType!(T1, T2)) || isSomeChar!(CommonType!(T1, T2))) &&
isUniformRNG!RandomGen)
{
alias ResultType = Unqual!(CommonType!(T1, T2));
static if (boundaries[0] == '(')
{
enforce(a < ResultType.max,
text("std.random.uniform(): invalid left bound ", a));
ResultType lower = a + 1;
}
else
{
ResultType lower = a;
}
static if (boundaries[1] == ']')
{
enforce(lower <= b,
text("std.random.uniform(): invalid bounding interval ",
boundaries[0], a, ", ", b, boundaries[1]));
if (b == ResultType.max && lower == ResultType.min)
{
// Special case - all bits are occupied
return std.random.uniform!ResultType(rng);
}
auto upperDist = unsigned(b - lower) + 1u;
}
else
{
enforce(lower < b,
text("std.random.uniform(): invalid bounding interval ",
boundaries[0], a, ", ", b, boundaries[1]));
auto upperDist = unsigned(b - lower);
}
assert(upperDist != 0);
alias UpperType = typeof(upperDist);
static assert(UpperType.min == 0);
UpperType offset, rnum, bucketFront;
do
{
rnum = uniform!UpperType(rng);
offset = rnum % upperDist;
bucketFront = rnum - offset;
} // while we're in an unfair bucket...
while (bucketFront > (UpperType.max - (upperDist - 1)));
return cast(ResultType)(lower + offset);
}
unittest
{
auto gen = Mt19937(unpredictableSeed);
static assert(isForwardRange!(typeof(gen)));
auto a = uniform(0, 1024, gen);
assert(0 <= a && a <= 1024);
auto b = uniform(0.0f, 1.0f, gen);
assert(0 <= b && b < 1, to!string(b));
auto c = uniform(0.0, 1.0);
assert(0 <= c && c < 1);
foreach (T; TypeTuple!(char, wchar, dchar, byte, ubyte, short, ushort,
int, uint, long, ulong, float, double, real))
{
T lo = 0, hi = 100;
T init = uniform(lo, hi);
size_t i = 50;
while (--i && uniform(lo, hi) == init) {}
assert(i > 0);
}
auto reproRng = Xorshift(239842);
foreach (T; TypeTuple!(char, wchar, dchar, byte, ubyte, short,
ushort, int, uint, long, ulong))
{
T lo = T.min + 10, hi = T.max - 10;
T init = uniform(lo, hi, reproRng);
size_t i = 50;
while (--i && uniform(lo, hi, reproRng) == init) {}
assert(i > 0);
}
{
bool sawLB = false, sawUB = false;
foreach (i; 0 .. 50)
{
auto x = uniform!"[]"('a', 'd', reproRng);
if (x == 'a') sawLB = true;
if (x == 'd') sawUB = true;
assert('a' <= x && x <= 'd');
}
assert(sawLB && sawUB);
}
{
bool sawLB = false, sawUB = false;
foreach (i; 0 .. 50)
{
auto x = uniform('a', 'd', reproRng);
if (x == 'a') sawLB = true;
if (x == 'c') sawUB = true;
assert('a' <= x && x < 'd');
}
assert(sawLB && sawUB);
}
{
bool sawLB = false, sawUB = false;
foreach (i; 0 .. 50)
{
immutable int lo = -2, hi = 2;
auto x = uniform!"()"(lo, hi, reproRng);
if (x == (lo+1)) sawLB = true;
if (x == (hi-1)) sawUB = true;
assert(lo < x && x < hi);
}
assert(sawLB && sawUB);
}
{
bool sawLB = false, sawUB = false;
foreach (i; 0 .. 50)
{
immutable ubyte lo = 0, hi = 5;
auto x = uniform(lo, hi, reproRng);
if (x == lo) sawLB = true;
if (x == (hi-1)) sawUB = true;
assert(lo <= x && x < hi);
}
assert(sawLB && sawUB);
}
{
foreach (i; 0 .. 30)
{
assert(i == uniform(i, i+1, reproRng));
}
}
}
/**
Generates a uniformly-distributed number in the range $(D [T.min,
T.max]) for any integral type $(D T). If no random number generator is
passed, uses the default $(D rndGen).
*/
auto uniform(T, UniformRandomNumberGenerator)
(ref UniformRandomNumberGenerator urng)
if (!is(T == enum) && (isIntegral!T || isSomeChar!T) && isUniformRNG!UniformRandomNumberGenerator)
{
auto r = urng.front;
urng.popFront();
static if (T.sizeof <= r.sizeof)
{
return cast(T) r;
}
else
{
static assert(T.sizeof == 8 && r.sizeof == 4);
T r1 = urng.front | (cast(T)r << 32);
urng.popFront();
return r1;
}
}
/// Ditto
auto uniform(T)()
if (!is(T == enum) && (isIntegral!T || isSomeChar!T))
{
return uniform!T(rndGen);
}
unittest
{
foreach(T; TypeTuple!(char, wchar, dchar, byte, ubyte, short, ushort,
int, uint, long, ulong))
{
T init = uniform!T();
size_t i = 50;
while (--i && uniform!T() == init) {}
assert(i > 0);
}
}
/**
Returns a uniformly selected member of enum $(D E). If no random number
generator is passed, uses the default $(D rndGen).
*/
auto uniform(E, UniformRandomNumberGenerator)
(ref UniformRandomNumberGenerator urng)
if (is(E == enum) && isUniformRNG!UniformRandomNumberGenerator)
{
static immutable E[EnumMembers!E.length] members = [EnumMembers!E];
return members[std.random.uniform(0, members.length, urng)];
}
/// Ditto
auto uniform(E)()
if (is(E == enum))
{
return uniform!E(rndGen);
}
///
unittest
{
enum Fruit { apple, mango, pear }
auto randFruit = uniform!Fruit();
}
unittest
{
enum Fruit { Apple = 12, Mango = 29, Pear = 72 }
foreach (_; 0 .. 100)
{
foreach(f; [uniform!Fruit(), rndGen.uniform!Fruit()])
{
assert(f == Fruit.Apple || f == Fruit.Mango || f == Fruit.Pear);
}
}
}
/**
Generates a uniform probability distribution of size $(D n), i.e., an
array of size $(D n) of positive numbers of type $(D F) that sum to
$(D 1). If $(D useThis) is provided, it is used as storage.
*/
F[] uniformDistribution(F = double)(size_t n, F[] useThis = null)
if(isFloatingPoint!F)
{
useThis.length = n;
foreach (ref e; useThis)
{
e = uniform(0.0, 1);
}
normalize(useThis);
return useThis;
}
unittest
{
static assert(is(CommonType!(double, int) == double));
auto a = uniformDistribution(5);
enforce(a.length == 5);
enforce(approxEqual(reduce!"a + b"(a), 1));
a = uniformDistribution(10, a);
enforce(a.length == 10);
enforce(approxEqual(reduce!"a + b"(a), 1));
}
/**
Shuffles elements of $(D r) using $(D gen) as a shuffler. $(D r) must be
a random-access range with length. If no RNG is specified, $(D rndGen)
will be used.
*/
void randomShuffle(Range, RandomGen)(Range r, ref RandomGen gen)
if(isRandomAccessRange!Range && isUniformRNG!RandomGen)
{
return partialShuffle!(Range, RandomGen)(r, r.length, gen);
}
/// ditto
void randomShuffle(Range)(Range r)
if(isRandomAccessRange!Range)
{
return randomShuffle(r, rndGen);
}
unittest
{
foreach(RandomGen; PseudoRngTypes)
{
// Also tests partialShuffle indirectly.
auto a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
auto b = a.dup;
auto gen = RandomGen(unpredictableSeed);
randomShuffle(a, gen);
assert(a.sort == b);
randomShuffle(a);
assert(a.sort == b);
}
}
/**
Partially shuffles the elements of $(D r) such that upon returning $(D r[0..n])
is a random subset of $(D r) and is randomly ordered. $(D r[n..r.length])
will contain the elements not in $(D r[0..n]). These will be in an undefined
order, but will not be random in the sense that their order after
$(D partialShuffle) returns will not be independent of their order before
$(D partialShuffle) was called.
$(D r) must be a random-access range with length. $(D n) must be less than
or equal to $(D r.length). If no RNG is specified, $(D rndGen) will be used.
*/
void partialShuffle(Range, RandomGen)(Range r, in size_t n, ref RandomGen gen)
if(isRandomAccessRange!Range && isUniformRNG!RandomGen)
{
enforce(n <= r.length, "n must be <= r.length for partialShuffle.");
foreach (i; 0 .. n)
{
swapAt(r, i, i + uniform(0, n - i, gen));
}
}
/// ditto
void partialShuffle(Range)(Range r, in size_t n)
if(isRandomAccessRange!Range)
{
return partialShuffle(r, n, rndGen);
}
unittest
{
foreach(RandomGen; PseudoRngTypes)
{
auto a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
auto b = a.dup;
auto gen = RandomGen(unpredictableSeed);
partialShuffle(a, 5, gen);
assert(a[5 .. $] == b[5 .. $]);
assert(a[0 .. 5].sort == b[0 .. 5]);
partialShuffle(a, 6);
assert(a[6 .. $] == b[6 .. $]);
assert(a[0 .. 6].sort == b[0 .. 6]);
}
}
/**
Rolls a dice with relative probabilities stored in $(D
proportions). Returns the index in $(D proportions) that was chosen.
Example:
----
auto x = dice(0.5, 0.5); // x is 0 or 1 in equal proportions
auto y = dice(50, 50); // y is 0 or 1 in equal proportions
auto z = dice(70, 20, 10); // z is 0 70% of the time, 1 20% of the time,
// and 2 10% of the time
----
*/
size_t dice(Rng, Num)(ref Rng rnd, Num[] proportions...)
if (isNumeric!Num && isForwardRange!Rng)
{
return diceImpl(rnd, proportions);
}
/// Ditto
size_t dice(R, Range)(ref R rnd, Range proportions)
if (isForwardRange!Range && isNumeric!(ElementType!Range) && !isArray!Range)
{
return diceImpl(rnd, proportions);
}
/// Ditto
size_t dice(Range)(Range proportions)
if (isForwardRange!Range && isNumeric!(ElementType!Range) && !isArray!Range)
{
return diceImpl(rndGen, proportions);
}
/// Ditto
size_t dice(Num)(Num[] proportions...)
if (isNumeric!Num)
{
return diceImpl(rndGen, proportions);
}
private size_t diceImpl(Rng, Range)(ref Rng rng, Range proportions)
if (isForwardRange!Range && isNumeric!(ElementType!Range) && isForwardRange!Rng)
{
double sum = reduce!((a,b) { assert(b >= 0); return a + b; })(0.0, proportions.save);
enforce(sum > 0, "Proportions in a dice cannot sum to zero");
immutable point = uniform(0.0, sum, rng);
assert(point < sum);
auto mass = 0.0;
size_t i = 0;
foreach (e; proportions)
{
mass += e;
if (point < mass) return i;
i++;
}
// this point should not be reached
assert(false);
}
unittest
{
auto rnd = Random(unpredictableSeed);
auto i = dice(rnd, 0.0, 100.0);
assert(i == 1);
i = dice(rnd, 100.0, 0.0);
assert(i == 0);
i = dice(100U, 0U);
assert(i == 0);
}
/**
Covers a given range $(D r) in a random manner, i.e. goes through each
element of $(D r) once and only once, just in a random order. $(D r)
must be a random-access range with length.
If no random number generator is passed to $(D randomCover), the
thread-global RNG rndGen will be used internally.
Example:
----
int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ];
foreach (e; randomCover(a))
{
writeln(e);
}
----
$(B WARNING:) If an alternative RNG is desired, it is essential for this
to be a $(I new) RNG seeded in an unpredictable manner. Passing it a RNG
used elsewhere in the program will result in unintended correlations,
due to the current implementation of RNGs as value types.
Example:
----
int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ];
foreach (e; randomCover(a, Random(unpredictableSeed))) // correct!
{
writeln(e);
}
foreach (e; randomCover(a, rndGen)) // DANGEROUS!! rndGen gets copied by value
{
writeln(e);
}
foreach (e; randomCover(a, rndGen)) // ... so this second random cover
{ // will output the same sequence as
writeln(e); // the previous one.
}
----
These issues will be resolved in a second-generation std.random that
re-implements random number generators as reference types.
*/
struct RandomCover(Range, UniformRNG = void)
if (isRandomAccessRange!Range && (isUniformRNG!UniformRNG || is(UniformRNG == void)))
{
private Range _input;
private bool[] _chosen;
private size_t _current;
private size_t _alreadyChosen = 0;
static if (is(UniformRNG == void))
{
this(Range input)
{
_input = input;
_chosen.length = _input.length;
_alreadyChosen = 0;
}
}
else
{
private UniformRNG _rng;
this(Range input, ref UniformRNG rng)
{
_input = input;
_rng = rng;
_chosen.length = _input.length;
_alreadyChosen = 0;
}
this(Range input, UniformRNG rng)
{
this(input, rng);
}
}
static if (hasLength!Range)
{
@property size_t length()
{
if (_alreadyChosen == 0)
{
return _input.length;
}
else
{
return (1 + _input.length) - _alreadyChosen;
}
}
}
@property auto ref front()
{
if (_alreadyChosen == 0)
{
_chosen[] = false;
popFront();
}
return _input[_current];
}
void popFront()
{
if (_alreadyChosen >= _input.length)
{
// No more elements
++_alreadyChosen; // means we're done
return;
}
size_t k = _input.length - _alreadyChosen;
size_t i;
foreach (e; _input)
{
if (_chosen[i]) { ++i; continue; }
// Roll a dice with k faces
static if (is(UniformRNG == void))
{
auto chooseMe = uniform(0, k) == 0;
}
else
{
auto chooseMe = uniform(0, k, _rng) == 0;
}
assert(k > 1 || chooseMe);
if (chooseMe)
{
_chosen[i] = true;
_current = i;
++_alreadyChosen;
return;
}
--k;
++i;
}
}
static if (isForwardRange!UniformRNG)
{
@property typeof(this) save()
{
auto ret = this;
ret._input = _input.save;
ret._rng = _rng.save;
return ret;
}
}
@property bool empty() { return _alreadyChosen > _input.length; }
}
/// Ditto
auto randomCover(Range, UniformRNG)(Range r, auto ref UniformRNG rng)
if (isRandomAccessRange!Range && isUniformRNG!UniformRNG)
{
return RandomCover!(Range, UniformRNG)(r, rng);
}
/// Ditto
auto randomCover(Range)(Range r)
if (isRandomAccessRange!Range)
{
return RandomCover!(Range, void)(r);
}
unittest
{
int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ];
foreach (UniformRNG; TypeTuple!(void, PseudoRngTypes))
{
static if (is(UniformRNG == void))
{
auto rc = randomCover(a);
static assert(isInputRange!(typeof(rc)));
static assert(!isForwardRange!(typeof(rc)));
}
else
{
auto rng = UniformRNG(unpredictableSeed);
auto rc = randomCover(a, rng);
static assert(isForwardRange!(typeof(rc)));
// check for constructor passed a value-type RNG
auto rc2 = RandomCover!(int[], UniformRNG)(a, UniformRNG(unpredictableSeed));
static assert(isForwardRange!(typeof(rc2)));
}
int[] b = new int[9];
uint i;
foreach (e; rc)
{
//writeln(e);
b[i++] = e;
}
sort(b);
assert(a == b, text(b));
}
}
// RandomSample
/**
Selects a random subsample out of $(D r), containing exactly $(D n)
elements. The order of elements is the same as in the original
range. The total length of $(D r) must be known. If $(D total) is
passed in, the total number of sample is considered to be $(D
total). Otherwise, $(D RandomSample) uses $(D r.length).
$(D RandomSample) implements Jeffrey Scott Vitter's Algorithm D
(see Vitter $(WEB dx.doi.org/10.1145/358105.893, 1984), $(WEB
dx.doi.org/10.1145/23002.23003, 1987)), which selects a sample
of size $(D n) in O(n) steps and requiring O(n) random variates,
regardless of the size of the data being sampled. The exception
to this is if traversing k elements on the input range is itself
an O(k) operation (e.g. when sampling lines from an input file),
in which case the sampling calculation will inevitably be of
O(total).
RandomSample will throw an exception if $(D total) is verifiably
less than the total number of elements available in the input,
or if $(D n > total).
If no random number generator is passed to $(D randomSample), the
thread-global RNG rndGen will be used internally.
Example:
----
int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
// Print 5 random elements picked off from a
foreach (e; randomSample(a, 5))
{
writeln(e);
}
----
$(B WARNING:) If an alternative RNG is desired, it is essential for this
to be a $(I new) RNG seeded in an unpredictable manner. Passing it a RNG
used elsewhere in the program will result in unintended correlations,
due to the current implementation of RNGs as value types.
Example:
----
int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
foreach (e; randomSample(a, 5, Random(unpredictableSeed))) // correct!
{
writeln(e);
}
foreach (e; randomSample(a, 5, rndGen)) // DANGEROUS!! rndGen gets
{ // copied by value
writeln(e);
}
foreach (e; randomSample(a, 5, rndGen)) // ... so this second random
{ // sample will select the same
writeln(e); // values as the previous one.
}
----
These issues will be resolved in a second-generation std.random that
re-implements random number generators as reference types.
*/
struct RandomSample(Range, UniformRNG = void)
if (isInputRange!Range && (isUniformRNG!UniformRNG || is(UniformRNG == void)))
{
private size_t _available, _toSelect;
private enum ushort _alphaInverse = 13; // Vitter's recommended value.
private double _Vprime;
private Range _input;
private size_t _index;
private enum Skip { None, A, D };
private Skip _skip = Skip.None;
// If we're using the default thread-local random number generator then
// we shouldn't store a copy of it here. UniformRNG == void is a sentinel
// for this. If we're using a user-specified generator then we have no
// choice but to store a copy.
static if (is(UniformRNG == void))
{
static if (hasLength!Range)
{
this(Range input, size_t howMany)
{
_input = input;
initialize(howMany, input.length);
}
}
this(Range input, size_t howMany, size_t total)
{
_input = input;
initialize(howMany, total);
}
}
else
{
UniformRNG _rng;
static if (hasLength!Range)
{
this(Range input, size_t howMany, ref UniformRNG rng)
{
_rng = rng;
_input = input;
initialize(howMany, input.length);
}
this(Range input, size_t howMany, UniformRNG rng)
{
this(input, howMany, rng);
}
}
this(Range input, size_t howMany, size_t total, ref UniformRNG rng)
{
_rng = rng;
_input = input;
initialize(howMany, total);
}
this(Range input, size_t howMany, size_t total, UniformRNG rng)
{
this(input, howMany, total, rng);
}
}
private void initialize(size_t howMany, size_t total)
{
_available = total;
_toSelect = howMany;
enforce(_toSelect <= _available,
text("RandomSample: cannot sample ", _toSelect,
" items when only ", _available, " are available"));
static if (hasLength!Range)
{
enforce(_available <= _input.length,
text("RandomSample: specified ", _available,
" items as available when input contains only ",
_input.length));
}
}
private void initializeFront()
{
assert(_skip == Skip.None);
// We can save ourselves a random variate by checking right
// at the beginning if we should use Algorithm A.
if ((_alphaInverse * _toSelect) > _available)
{
_skip = Skip.A;
}
else
{
_skip = Skip.D;
_Vprime = newVprime(_toSelect);
}
prime();
}
/**
Range primitives.
*/
@property bool empty() const
{
return _toSelect == 0;
}
@property auto ref front()
{
assert(!empty);
// The first sample point must be determined here to avoid
// having it always correspond to the first element of the
// input. The rest of the sample points are determined each
// time we call popFront().
if (_skip == Skip.None)
{
initializeFront();
}
return _input.front;
}
/// Ditto
void popFront()
{
// First we need to check if the sample has
// been initialized in the first place.
if (_skip == Skip.None)
{
initializeFront();
}
_input.popFront();
--_available;
--_toSelect;
++_index;
prime();
}
/// Ditto
static if (isForwardRange!Range && isForwardRange!UniformRNG)
{
@property typeof(this) save()
{
auto ret = this;
ret._input = _input.save;
ret._rng = _rng.save;
return ret;
}
}
/// Ditto
@property size_t length()
{
return _toSelect;
}
/**
Returns the index of the visited record.
*/
@property size_t index()
{
if (_skip == Skip.None)
{
initializeFront();
}
return _index;
}
private size_t skip()
{
assert(_skip != Skip.None);
// Step D1: if the number of points still to select is greater
// than a certain proportion of the remaining data points, i.e.
// if n >= alpha * N where alpha = 1/13, we carry out the
// sampling with Algorithm A.
if (_skip == Skip.A)
{
return skipA();
}
else if ((_alphaInverse * _toSelect) > _available)
{
// We shouldn't get here unless the current selected
// algorithm is D.
assert(_skip == Skip.D);
_skip = Skip.A;
return skipA();
}
else
{
assert(_skip == Skip.D);
return skipD();
}
}
/*
Vitter's Algorithm A, used when the ratio of needed sample values
to remaining data values is sufficiently large.
*/
private size_t skipA()
{
size_t s;
double v, quot, top;
if (_toSelect==1)
{
static if (is(UniformRNG == void))
{
s = uniform(0, _available);
}
else
{
s = uniform(0, _available, _rng);
}
}
else
{
v = 0;
top = _available - _toSelect;
quot = top / _available;
static if (is(UniformRNG == void))
{
v = uniform!"()"(0.0, 1.0);
}
else
{
v = uniform!"()"(0.0, 1.0, _rng);
}
while (quot > v)
{
++s;
quot *= (top - s) / (_available - s);
}
}
return s;
}
/*
Randomly reset the value of _Vprime.
*/
private double newVprime(size_t remaining)
{
static if (is(UniformRNG == void))
{
double r = uniform!"()"(0.0, 1.0);
}
else
{
double r = uniform!"()"(0.0, 1.0, _rng);
}
return r ^^ (1.0 / remaining);
}
/*
Vitter's Algorithm D. For an extensive description of the algorithm
and its rationale, see:
* Vitter, J.S. (1984), "Faster methods for random sampling",
Commun. ACM 27(7): 703--718
* Vitter, J.S. (1987) "An efficient algorithm for sequential random
sampling", ACM Trans. Math. Softw. 13(1): 58-67.
Variable names are chosen to match those in Vitter's paper.
*/
private size_t skipD()
{
// Confirm that the check in Step D1 is valid and we
// haven't been sent here by mistake
assert((_alphaInverse * _toSelect) <= _available);
// Now it's safe to use the standard Algorithm D mechanism.
if (_toSelect > 1)
{
size_t s;
size_t qu1 = 1 + _available - _toSelect;
double x, y1;
assert(!_Vprime.isNaN);
while (true)
{
// Step D2: set values of x and u.
while(1)
{
x = _available * (1-_Vprime);
s = cast(size_t) trunc(x);
if (s < qu1)
break;
_Vprime = newVprime(_toSelect);
}
static if (is(UniformRNG == void))
{
double u = uniform!"()"(0.0, 1.0);
}
else
{
double u = uniform!"()"(0.0, 1.0, _rng);
}
y1 = (u * (cast(double) _available) / qu1) ^^ (1.0/(_toSelect - 1));
_Vprime = y1 * ((-x/_available)+1.0) * ( qu1/( (cast(double) qu1) - s ) );
// Step D3: if _Vprime <= 1.0 our work is done and we return S.
// Otherwise ...
if (_Vprime > 1.0)
{
size_t top = _available - 1, limit;
double y2 = 1.0, bottom;
if (_toSelect > (s+1))
{
bottom = _available - _toSelect;
limit = _available - s;
}
else
{
bottom = _available - (s+1);
limit = qu1;
}
foreach (size_t t; limit .. _available)
{
y2 *= top/bottom;
top--;
bottom--;
}
// Step D4: decide whether or not to accept the current value of S.
if (_available/(_available-x) < y1 * (y2 ^^ (1.0/(_toSelect-1))))
{
// If it's not acceptable, we generate a new value of _Vprime
// and go back to the start of the for (;;) loop.
_Vprime = newVprime(_toSelect);
}
else
{
// If it's acceptable we generate a new value of _Vprime
// based on the remaining number of sample points needed,
// and return S.
_Vprime = newVprime(_toSelect-1);
return s;
}
}
else
{
// Return if condition D3 satisfied.
return s;
}
}
}
else
{
// If only one sample point remains to be taken ...
return cast(size_t) trunc(_available * _Vprime);
}
}
private void prime()
{
if (empty)
{
return;
}
assert(_available && _available >= _toSelect);
immutable size_t s = skip();
assert(s + _toSelect <= _available);
static if (hasLength!Range)
{
assert(s + _toSelect <= _input.length);
}
assert(!_input.empty);
_input.popFrontExactly(s);
_index += s;
_available -= s;
assert(_available > 0);
}
}
/// Ditto
auto randomSample(Range)(Range r, size_t n, size_t total)
if (isInputRange!Range)
{
return RandomSample!(Range, void)(r, n, total);
}
/// Ditto
auto randomSample(Range)(Range r, size_t n)
if (isInputRange!Range && hasLength!Range)
{
return RandomSample!(Range, void)(r, n, r.length);
}
/// Ditto
auto randomSample(Range, UniformRNG)(Range r, size_t n, size_t total, auto ref UniformRNG rng)
if (isInputRange!Range && isUniformRNG!UniformRNG)
{
return RandomSample!(Range, UniformRNG)(r, n, total, rng);
}
/// Ditto
auto randomSample(Range, UniformRNG)(Range r, size_t n, auto ref UniformRNG rng)
if (isInputRange!Range && hasLength!Range && isUniformRNG!UniformRNG)
{
return RandomSample!(Range, UniformRNG)(r, n, r.length, rng);
}
unittest
{
// For test purposes, an infinite input range
struct TestInputRange
{
private auto r = recurrence!"a[n-1] + 1"(0);
bool empty() @property const pure nothrow { return r.empty; }
auto front() @property pure nothrow { return r.front; }
void popFront() pure nothrow { r.popFront(); }
}
static assert(isInputRange!TestInputRange);
static assert(!isForwardRange!TestInputRange);
int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
foreach (UniformRNG; PseudoRngTypes)
{
auto rng = UniformRNG(unpredictableSeed);
/* First test the most general case: randomSample of input range, with and
* without a specified random number generator.
*/
static assert(isInputRange!(typeof(randomSample(TestInputRange(), 5, 10))));
static assert(isInputRange!(typeof(randomSample(TestInputRange(), 5, 10, rng))));
static assert(!isForwardRange!(typeof(randomSample(TestInputRange(), 5, 10))));
static assert(!isForwardRange!(typeof(randomSample(TestInputRange(), 5, 10, rng))));
// test case with range initialized by direct call to struct
{
auto sample =
RandomSample!(TestInputRange, UniformRNG)
(TestInputRange(), 5, 10, UniformRNG(unpredictableSeed));
static assert(isInputRange!(typeof(sample)));
static assert(!isForwardRange!(typeof(sample)));
}
/* Now test the case of an input range with length. We ignore the cases
* already covered by the previous tests.
*/
static assert(isInputRange!(typeof(randomSample(TestInputRange().takeExactly(10), 5))));
static assert(isInputRange!(typeof(randomSample(TestInputRange().takeExactly(10), 5, rng))));
static assert(!isForwardRange!(typeof(randomSample(TestInputRange().takeExactly(10), 5))));
static assert(!isForwardRange!(typeof(randomSample(TestInputRange().takeExactly(10), 5, rng))));
// test case with range initialized by direct call to struct
{
auto sample =
RandomSample!(typeof(TestInputRange().takeExactly(10)), UniformRNG)
(TestInputRange().takeExactly(10), 5, 10, UniformRNG(unpredictableSeed));
static assert(isInputRange!(typeof(sample)));
static assert(!isForwardRange!(typeof(sample)));
}
// Now test the case of providing a forward range as input.
static assert(!isForwardRange!(typeof(randomSample(a, 5))));
static if (isForwardRange!UniformRNG)
{
static assert(isForwardRange!(typeof(randomSample(a, 5, rng))));
// ... and test with range initialized directly
{
auto sample =
RandomSample!(int[], UniformRNG)
(a, 5, UniformRNG(unpredictableSeed));
static assert(isForwardRange!(typeof(sample)));
}
}
else
{
static assert(isInputRange!(typeof(randomSample(a, 5, rng))));
static assert(!isForwardRange!(typeof(randomSample(a, 5, rng))));
// ... and test with range initialized directly
{
auto sample =
RandomSample!(int[], UniformRNG)
(a, 5, UniformRNG(unpredictableSeed));
static assert(isInputRange!(typeof(sample)));
static assert(!isForwardRange!(typeof(sample)));
}
}
/* Check that randomSample will throw an error if we claim more
* items are available than there actually are, or if we try to
* sample more items than are available. */
assert(collectExceptionMsg(randomSample(a, 5, 15)) == "RandomSample: specified 15 items as available when input contains only 10");
assert(collectExceptionMsg(randomSample(a, 15)) == "RandomSample: cannot sample 15 items when only 10 are available");
assert(collectExceptionMsg(randomSample(a, 9, 8)) == "RandomSample: cannot sample 9 items when only 8 are available");
assert(collectExceptionMsg(randomSample(TestInputRange(), 12, 11)) == "RandomSample: cannot sample 12 items when only 11 are available");
/* Check that sampling algorithm never accidentally overruns the end of
* the input range. If input is an InputRange without .length, this
* relies on the user specifying the total number of available items
* correctly.
*/
{
uint i = 0;
foreach (e; randomSample(a, a.length))
{
assert(e == i);
++i;
}
assert(i == a.length);
i = 0;
foreach (e; randomSample(TestInputRange(), 17, 17))
{
assert(e == i);
++i;
}
assert(i == 17);
}
// Check length properties of random samples.
assert(randomSample(a, 5).length == 5);
assert(randomSample(a, 5, 10).length == 5);
assert(randomSample(a, 5, rng).length == 5);
assert(randomSample(a, 5, 10, rng).length == 5);
assert(randomSample(TestInputRange(), 5, 10).length == 5);
assert(randomSample(TestInputRange(), 5, 10, rng).length == 5);
// ... and emptiness!
assert(randomSample(a, 0).empty);
assert(randomSample(a, 0, 5).empty);
assert(randomSample(a, 0, rng).empty);
assert(randomSample(a, 0, 5, rng).empty);
assert(randomSample(TestInputRange(), 0, 10).empty);
assert(randomSample(TestInputRange(), 0, 10, rng).empty);
/* Test that the (lazy) evaluation of random samples works correctly.
*
* We cover 2 different cases: a sample where the ratio of sample points
* to total points is greater than the threshold for using Algorithm, and
* one where the ratio is small enough (< 1/13) for Algorithm D to be used.
*
* For each, we also cover the case with and without a specified RNG.
*/
{
// Small sample/source ratio, no specified RNG.
uint i = 0;
foreach (e; randomSample(randomCover(a), 5))
{
++i;
}
assert(i == 5);
// Small sample/source ratio, specified RNG.
i = 0;
foreach (e; randomSample(randomCover(a), 5, rng))
{
++i;
}
assert(i == 5);
// Large sample/source ratio, no specified RNG.
i = 0;
foreach (e; randomSample(TestInputRange(), 123, 123_456))
{
++i;
}
assert(i == 123);
// Large sample/source ratio, specified RNG.
i = 0;
foreach (e; randomSample(TestInputRange(), 123, 123_456, rng))
{
++i;
}
assert(i == 123);
/* Sample/source ratio large enough to start with Algorithm D,
* small enough to switch to Algorithm A.
*/
i = 0;
foreach (e; randomSample(TestInputRange(), 10, 131))
{
++i;
}
assert(i == 10);
}
// Test that the .index property works correctly
{
auto sample1 = randomSample(TestInputRange(), 654, 654_321);
for (; !sample1.empty; sample1.popFront())
{
assert(sample1.front == sample1.index);
}
auto sample2 = randomSample(TestInputRange(), 654, 654_321, rng);
for (; !sample2.empty; sample2.popFront())
{
assert(sample2.front == sample2.index);
}
/* Check that it also works if .index is called before .front.
* See: http://d.puremagic.com/issues/show_bug.cgi?id=10322
*/
auto sample3 = randomSample(TestInputRange(), 654, 654_321);
for (; !sample3.empty; sample3.popFront())
{
assert(sample3.index == sample3.front);
}
auto sample4 = randomSample(TestInputRange(), 654, 654_321, rng);
for (; !sample4.empty; sample4.popFront())
{
assert(sample4.index == sample4.front);
}
}
/* Test behaviour if .popFront() is called before sample is read.
* This is a rough-and-ready check that the statistical properties
* are in the ballpark -- not a proper validation of statistical
* quality! This incidentally also checks for reference-type
* initialization bugs, as the foreach() loop will operate on a
* copy of the popFronted (and hence initialized) sample.
*/
{
size_t count0, count1, count99;
foreach(_; 0 .. 100_000)
{
auto sample = randomSample(iota(100), 5);
sample.popFront();
foreach(s; sample)
{
if (s == 0)
{
++count0;
}
else if (s == 1)
{
++count1;
}
else if (s == 99)
{
++count99;
}
}
}
/* Statistical assumptions here: this is a sequential sampling process
* so (i) 0 can only be the first sample point, so _can't_ be in the
* remainder of the sample after .popFront() is called. (ii) By similar
* token, 1 can only be in the remainder if it's the 2nd point of the
* whole sample, and hence if 0 was the first; probability of 0 being
* first and 1 second is 5/100 * 4/99 (thank you, Algorithm S:-) and
* so the mean count of 1 should be about 202. Finally, 99 can only
* be the _last_ sample point to be picked, so its probability of
* inclusion should be independent of the .popFront() and it should
* occur with frequency 5/100, hence its count should be about 5000.
* Unfortunately we have to set quite a high tolerance because with
* sample size small enough for unittests to run in reasonable time,
* the variance can be quite high.
*/
assert(count0 == 0);
assert(count1 < 300, text("1: ", count1, " > 300."));
assert(4_700 < count99, text("99: ", count99, " < 4700."));
assert(count99 < 5_300, text("99: ", count99, " > 5300."));
}
/* Odd corner-cases: RandomSample has 2 constructors that are not called
* by the randomSample() helper functions, but that can be used if the
* constructor is called directly. These cover the case of the user
* specifying input but not input length.
*/
{
auto input1 = TestInputRange().takeExactly(456_789);
static assert(hasLength!(typeof(input1)));
auto sample1 = RandomSample!(typeof(input1), void)(input1, 789);
static assert(isInputRange!(typeof(sample1)));
static assert(!isForwardRange!(typeof(sample1)));
assert(sample1.length == 789);
assert(sample1._available == 456_789);
uint i = 0;
for (; !sample1.empty; sample1.popFront())
{
assert(sample1.front == sample1.index);
++i;
}
assert(i == 789);
auto input2 = TestInputRange().takeExactly(456_789);
static assert(hasLength!(typeof(input2)));
auto sample2 = RandomSample!(typeof(input2), typeof(rng))(input2, 789, rng);
static assert(isInputRange!(typeof(sample2)));
static assert(!isForwardRange!(typeof(sample2)));
assert(sample2.length == 789);
assert(sample2._available == 456_789);
i = 0;
for (; !sample2.empty; sample2.popFront())
{
assert(sample2.front == sample2.index);
++i;
}
assert(i == 789);
}
/* Test that the save property works where input is a forward range,
* and RandomSample is using a (forward range) random number generator
* that is not rndGen.
*/
static if (isForwardRange!UniformRNG)
{
auto sample1 = randomSample(a, 5, rng);
auto sample2 = sample1.save;
assert(sample1.array() == sample2.array());
}
// Bugzilla 8314
{
auto sample(RandomGen)(uint seed) { return randomSample(a, 1, RandomGen(seed)).front; }
// Start from 1 because not all RNGs accept 0 as seed.
immutable fst = sample!UniformRNG(1);
uint n = 1;
while (sample!UniformRNG(++n) == fst && n < n.max) {}
assert(n < n.max);
}
}
}
| D |
module antlr.runtime.tests.main_t004Lexer;
import antlr.runtime.Lexer;
import antlr.runtime.CharStream;
import antlr.runtime.Token;
import antlr.runtime.CommonToken;
import antlr.runtime.ANTLRStringStream;
import tango.io.Stdout;
import antlr.runtime.tests.t004Lexer;
template main_test(char_t) {
void main_test(){
Stdout.formatln("Test {} ",typeid(char_t));
auto input=new ANTLRStringStream!(char_t)("ffofoofooo");
auto lexer=new t004Lexer!(char_t)(input,null);
// while (true) {
CommonToken!(char_t) token;
token=cast(CommonToken!(char_t))lexer.nextToken;
assert(token.Type==lexer.FOO);
assert(token.Text=="f");
assert(token.StopIndex==0);
assert(token.StartIndex==0);
token=cast(CommonToken!(char_t))lexer.nextToken;
assert(token.Type==lexer.FOO);
assert(token.Text=="fo");
assert(token.StartIndex==1);
assert(token.StopIndex==2);
token=cast(CommonToken!(char_t))lexer.nextToken;
assert(token.Type==lexer.FOO);
assert(token.Text=="foo");
assert(token.StartIndex==3);
assert(token.StopIndex==5);
token=cast(CommonToken!(char_t))lexer.nextToken;
assert(token.Type==lexer.FOO);
assert(token.Text=="fooo");
assert(token.StartIndex==6);
assert(token.StopIndex==9);
token=cast(CommonToken!(char_t))lexer.nextToken;
assert(token.Type==lexer.EOF);
Stdout
.format("passed: {}",typeid(typeof(lexer)))
.newline;
}
}
int main() {
main_test!(char);
main_test!(wchar);
main_test!(dchar);
return 0;
} | D |
/*
This file is part of BioD.
Copyright (C) 2012-2014 Artem Tarasov <lomereiter@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
Module for random access operations on BAM file.
*/
module bio.std.hts.bam.randomaccessmanager;
import bio.std.hts.bam.constants;
import bio.std.hts.bam.reader;
import bio.std.hts.bam.read;
import bio.std.hts.bam.readrange;
import bio.std.hts.bam.baifile;
import bio.std.hts.bam.region;
import bio.core.utils.algo;
import bio.core.bgzf.block;
import bio.core.bgzf.virtualoffset;
import bio.core.bgzf.inputstream;
import bio.core.bgzf.constants;
import bio.core.bgzf.chunk;
import bio.core.utils.range;
import bio.core.utils.stream;
import std.system;
import std.algorithm;
import std.array;
import std.range;
import std.traits;
import std.exception;
import std.container;
import std.parallelism;
static import std.file;
debug {
import std.stdio;
}
private {
auto nonOverlappingChunks(R)(R chunks) {
static ref auto chunkB(ref Chunk chunk) { return chunk.beg; }
static ref auto chunkE(ref Chunk chunk) { return chunk.end; }
return nonOverlapping!(chunkB, chunkE)(chunks);
}
}
/// Class which random access tasks are delegated to.
class RandomAccessManager {
// void setCache(BgzfBlockCache cache) {
// _cache = cache;
//}
void setTaskPool(TaskPool task_pool) {
_task_pool = task_pool;
}
void setBufferSize(size_t buffer_size) {
_buffer_size = buffer_size;
}
/// Constructs new manager for BAM file
this(string filename) {
_filename = filename;
}
/// ditto
this(BamReader reader) {
_reader = reader;
_filename = reader.filename;
}
/// Constructs new manager with given index file.
/// This allows to do random-access interval queries.
///
/// Params:
/// filename = location of BAM file
/// bai = index file
this(string filename, ref BaiFile bai) {
_filename = filename;
_bai = bai;
_found_index_file = true;
}
/// ditto
this(BamReader reader, ref BaiFile bai) {
_reader = reader;
_filename = reader.filename;
_bai = bai;
_found_index_file = true;
}
/// If file ends with EOF block, returns virtual offset of the start of EOF block.
/// Otherwise, returns virtual offset of the physical end of file.
VirtualOffset eofVirtualOffset() const {
ulong file_offset = std.file.getSize(_filename);
if (hasEofBlock()) {
return VirtualOffset(file_offset - BAM_EOF.length, 0);
} else {
return VirtualOffset(file_offset, 0);
}
}
/// Returns true if the file ends with EOF block, and false otherwise.
bool hasEofBlock() const {
auto _stream = new bio.core.utils.stream.File(_filename);
if (_stream.size < BAM_EOF.length) {
return false;
}
ubyte[BAM_EOF.length] buf;
_stream.seekEnd(-cast(int)BAM_EOF.length);
_stream.readExact(&buf, BAM_EOF.length);
if (buf != BAM_EOF) {
return false;
}
return true;
}
/// Get new BgzfInputStream starting from specified virtual offset.
BgzfInputStream createStreamStartingFrom(VirtualOffset offset)
{
auto _stream = new bio.core.utils.stream.File(_filename);
auto _compressed_stream = new EndianStream(_stream, Endian.littleEndian);
_compressed_stream.seekSet(cast(size_t)(offset.coffset));
auto supplier = new StreamSupplier(_compressed_stream, offset.uoffset);
// auto bgzf_stream = new BgzfInputStream(supplier, _task_pool, _cache);
auto bgzf_stream = new BgzfInputStream(supplier, _task_pool);
return bgzf_stream;
}
/// Get single read at a given virtual offset.
/// Every time new stream is used.
BamRead getReadAt(VirtualOffset offset) {
auto stream = createStreamStartingFrom(offset);
bool old_mode = _reader._seqprocmode;
_reader._seqprocmode = true;
auto read = bamReadRange(stream, _reader).front.dup;
_reader._seqprocmode = old_mode;
return read;
}
/// Get BGZF block at a given offset.
BgzfBlock getBgzfBlockAt(ulong offset) {
auto fstream = new bio.core.utils.stream.File(_filename);
auto stream = new EndianStream(fstream, Endian.littleEndian);
stream.seekSet(offset);
BgzfBlock block = void;
ubyte[BGZF_MAX_BLOCK_SIZE] buf = void;
fillBgzfBufferFromStream(stream, true, &block, buf.ptr);
block._buffer = block._buffer.dup;
return block;
}
/// Get reads between two virtual offsets. First virtual offset must point
/// to a start of an alignment record.
auto getReadsBetween(VirtualOffset from, VirtualOffset to) {
auto stream = createStreamStartingFrom(from);
static bool offsetTooBig(BamReadBlock record, VirtualOffset vo) {
return record.end_virtual_offset > vo;
}
return until!offsetTooBig(bamReadRange!withOffsets(stream, _reader), to);
}
bool found_index_file() @property const {
return _found_index_file;
}
private bool _found_index_file = false; // overwritten in constructor if filename is provided
/// BAI file
ref const(BaiFile) getBai() const {
enforce(found_index_file, "BAM index file (.bai) must be provided");
return _bai;
}
private void checkIndexExistence() {
enforce(found_index_file, "BAM index file (.bai) must be provided");
}
private void checkRefId(uint ref_id) {
enforce(ref_id < _bai.indices.length, "Invalid reference sequence index");
}
private void appendChunks(ref Chunk[] chunks, Bin bin, VirtualOffset min_offset) {
foreach (chunk; bin.chunks) {
if (chunk.end > min_offset) {
chunks ~= chunk;
// optimization
if (chunks[$-1].beg < min_offset)
chunks[$-1].beg = min_offset;
}
}
}
/// Get BAI chunks containing all alignment records overlapping the region
Chunk[] getChunks(BamRegion region) {
auto ref_id = region.ref_id;
auto beg = region.start;
auto end = region.end;
checkIndexExistence();
checkRefId(ref_id);
// Select all bins that overlap with [beg, end).
// Then from such bins select all chunks that end to the right of min_offset.
// Sort these chunks by leftmost coordinate and remove all overlaps.
auto min_offset = _bai.indices[ref_id].getMinimumOffset(beg);
Chunk[] bai_chunks;
foreach (b; _bai.indices[ref_id].bins) {
if (!b.canOverlapWith(beg, end))
continue;
appendChunks(bai_chunks, b, min_offset);
}
sort(bai_chunks);
return bai_chunks.nonOverlappingChunks().array();
}
// regions should be from the same reference sequence
private Chunk[] getGroupChunks(BamRegion[] regions) {
auto bitset = Array!bool();
enforce(regions.length > 0);
bitset.length = BAI_MAX_BIN_ID;
bitset[0] = true;
foreach (region; regions) {
auto beg = region.start;
auto end = region.end;
int i = 0, k;
enforce(beg < end);
--end;
for (k = 1 + (beg>>26); k <= 1 + (end>>26); ++k) bitset[k] = true;
for (k = 9 + (beg>>23); k <= 9 + (end>>23); ++k) bitset[k] = true;
for (k = 73 + (beg>>20); k <= 73 + (end>>20); ++k) bitset[k] = true;
for (k = 585 + (beg>>17); k <= 585 + (end>>17); ++k) bitset[k] = true;
for (k = 4681 + (beg>>14); k <= 4681 + (end>>14); ++k) bitset[k] = true;
}
auto ref_id = regions.front.ref_id;
checkIndexExistence();
checkRefId(ref_id);
// Select all bins that overlap with [beg, end).
// Then from such bins select all chunks that end to the right of min_offset.
// Sort these chunks by leftmost coordinate and remove all overlaps.
auto min_offset = _bai.indices[ref_id].getMinimumOffset(regions.front.start);
version(extraVerbose) {
import std.stdio;
stderr.writeln("min offset = ", min_offset);
}
Chunk[] bai_chunks;
auto bins = _bai.indices[ref_id].bins;
foreach (bin; bins)
if (bitset[bin.id])
appendChunks(bai_chunks, bin, min_offset);
sort(bai_chunks);
version(extraVerbose) {
stderr.writeln("[chunks before normalization]");
foreach(chunk; bai_chunks)
stderr.writeln(chunk.beg, " - ", chunk.end);
}
return bai_chunks.nonOverlappingChunks().array();
}
private auto filteredReads(alias IteratePolicy)(BamRegion[] regions) {
auto chunks = getGroupChunks(regions);
version(extraVerbose) {
import std.stdio;
stderr.writeln("[chunks]");
foreach (chunk; chunks)
stderr.writeln(chunk.beg, " - ", chunk.end);
}
auto reads = readsFromChunks!IteratePolicy(chunks);
return filterBamReads(reads, regions);
}
/// Fetch alignments with given reference sequence id, overlapping [beg..end)
auto getReads(alias IteratePolicy=withOffsets)(BamRegion region)
{
auto chunks = getChunks(region);
auto reads = readsFromChunks!IteratePolicy(chunks);
return filterBamReads(reads, [region]);
}
auto getReads(alias IteratePolicy=withOffsets)(BamRegion[] regions) {
auto sorted_regions = regions.sort();
BamRegion[][] regions_by_ref;
// TODO: replace with groupBy once it's included into Phobos
uint last_ref_id = uint.max;
foreach (region; sorted_regions) {
if (region.ref_id == last_ref_id) {
regions_by_ref.back ~= region;
} else {
regions_by_ref ~= [region];
last_ref_id = region.ref_id;
}
}
static ref auto regB(ref BamRegion region) { return region.start; }
static ref auto regE(ref BamRegion region) { return region.end; }
foreach (ref group; regions_by_ref)
group = nonOverlapping!(regB, regE)(group).array();
return regions_by_ref.zip(repeat(this))
.map!(gt => gt[1].filteredReads!IteratePolicy(gt[0]))()
.joiner();
}
private:
auto readsFromChunks(alias IteratePolicy, R)(R chunks) {
auto fstream = new bio.core.utils.stream.File(_filename);
auto compressed_stream = new EndianStream(fstream, Endian.littleEndian);
auto supplier = new StreamChunksSupplier(compressed_stream, chunks);
// auto stream = new BgzfInputStream(supplier, _task_pool, _cache);
auto stream = new BgzfInputStream(supplier, _task_pool);
return bamReadRange!IteratePolicy(stream, _reader);
}
string _filename;
BaiFile _bai;
BamReader _reader;
TaskPool _task_pool;
size_t _buffer_size;
// BgzfBlockCache _cache;
TaskPool task_pool() @property {
if (_task_pool is null)
_task_pool = taskPool;
return _task_pool;
}
public:
static struct BamReadFilter(R) {
this(R r, BamRegion[] regions) {
_range = r;
_regions = regions;
enforce(regions.length > 0);
_region = _regions.front;
_ref_id = _region.ref_id; // assumed to be constant
findNext();
}
bool empty() @property {
return _empty;
}
ElementType!R front() @property {
return _current_read;
}
void popFront() {
_range.popFront();
findNext();
}
private:
R _range;
uint _ref_id;
BamRegion _region;
BamRegion[] _regions; // non-overlapping and sorted
bool _empty;
ElementType!R _current_read;
void findNext() {
if (_regions.empty || _range.empty) {
_empty = true;
return;
}
while (!_range.empty) {
_current_read = _range.front;
// BamReads are sorted first by ref. ID.
auto current_ref_id = cast(uint)_current_read.ref_id;
// ref_id can't be -1 unless the index is fucked up
if (current_ref_id > _ref_id) {
// no more records for this _ref_id
_empty = true;
return;
} else if (current_ref_id < _ref_id) {
// skip reads referring to sequences
// with ID less than ours
_range.popFront();
continue;
}
if (_current_read.position >= _region.end) {
// As reads are sorted by leftmost coordinate,
// all remaining alignments in _range
// will not overlap the current interval as well.
//
// [-----)
// . [-----------)
// . [---)
// . [-------)
// . [-)
// [beg ..... end)
_regions.popFront();
// TODO: potentially binary search may be faster,
// but it needs to be checked
if (_regions.empty) {
_empty = true;
return;
} else {
_region = _regions.front;
continue;
}
}
if (_current_read.position > _region.start) {
return; // definitely overlaps
}
if (_current_read.position +
_current_read.basesCovered() <= _region.start)
{
/// ends before beginning of the region
/// [-----------)
/// [beg .......... end)
_range.popFront();
/// Zero-length reads are also considered non-overlapping,
/// so for consistency the inequality 12 lines above is strict.
} else {
return; /// _current_read overlaps the region
}
}
_empty = true;
}
}
// Get range of alignments sorted by leftmost coordinate,
// together with an interval [beg, end),
// and return another range of alignments which overlap the region.
static auto filterBamReads(R)(R r, BamRegion[] regions)
{
return BamReadFilter!R(r, regions);
}
}
| D |
module dcompute.driver.cuda.buffer;
import dcompute.driver.cuda;
struct Buffer(T)
{
size_t raw;
this(size_t elems)
{
status = cast(Status)cuMemAlloc(&raw,elems * T.sizeof);
checkErrors();
}
}
alias bf = Buffer!float;
| D |
/**
* The read/write mutex module provides a primitive for maintaining shared read
* access and mutually exclusive write access.
*
* Copyright: Copyright Sean Kelly 2005 - 2009.
* License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Authors: Sean Kelly
* Source: $(DRUNTIMESRC core/sync/_rwmutex.d)
*/
/* Copyright Sean Kelly 2005 - 2009.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
module core.sync.rwmutex;
public import core.sync.exception;
private import core.sync.condition;
private import core.sync.mutex;
version( Win32 )
{
private import core.sys.windows.windows;
}
else version( Posix )
{
private import core.sys.posix.pthread;
}
////////////////////////////////////////////////////////////////////////////////
// ReadWriteMutex
//
// Reader reader();
// Writer writer();
////////////////////////////////////////////////////////////////////////////////
/**
* This class represents a mutex that allows any number of readers to enter,
* but when a writer enters, all other readers and writers are blocked.
*
* Please note that this mutex is not recursive and is intended to guard access
* to data only. Also, no deadlock checking is in place because doing so would
* require dynamic memory allocation, which would reduce performance by an
* unacceptable amount. As a result, any attempt to recursively acquire this
* mutex may well deadlock the caller, particularly if a write lock is acquired
* while holding a read lock, or vice-versa. In practice, this should not be
* an issue however, because it is uncommon to call deeply into unknown code
* while holding a lock that simply protects data.
*/
class ReadWriteMutex
{
/**
* Defines the policy used by this mutex. Currently, two policies are
* defined.
*
* The first will queue writers until no readers hold the mutex, then
* pass the writers through one at a time. If a reader acquires the mutex
* while there are still writers queued, the reader will take precedence.
*
* The second will queue readers if there are any writers queued. Writers
* are passed through one at a time, and once there are no writers present,
* all queued readers will be alerted.
*
* Future policies may offer a more even balance between reader and writer
* precedence.
*/
enum Policy
{
PREFER_READERS, /// Readers get preference. This may starve writers.
PREFER_WRITERS /// Writers get preference. This may starve readers.
}
////////////////////////////////////////////////////////////////////////////
// Initialization
////////////////////////////////////////////////////////////////////////////
/**
* Initializes a read/write mutex object with the supplied policy.
*
* Params:
* policy = The policy to use.
*
* Throws:
* SyncException on error.
*/
this( Policy policy = Policy.PREFER_WRITERS )
{
m_commonMutex = new Mutex;
if( !m_commonMutex )
throw new SyncException( "Unable to initialize mutex" );
scope(failure) delete m_commonMutex;
m_readerQueue = new Condition( m_commonMutex );
if( !m_readerQueue )
throw new SyncException( "Unable to initialize mutex" );
scope(failure) delete m_readerQueue;
m_writerQueue = new Condition( m_commonMutex );
if( !m_writerQueue )
throw new SyncException( "Unable to initialize mutex" );
scope(failure) delete m_writerQueue;
m_policy = policy;
m_reader = new Reader;
m_writer = new Writer;
}
////////////////////////////////////////////////////////////////////////////
// General Properties
////////////////////////////////////////////////////////////////////////////
/**
* Gets the policy used by this mutex.
*
* Returns:
* The policy used by this mutex.
*/
@property Policy policy()
{
return m_policy;
}
////////////////////////////////////////////////////////////////////////////
// Reader/Writer Handles
////////////////////////////////////////////////////////////////////////////
/**
* Gets an object representing the reader lock for the associated mutex.
*
* Returns:
* A reader sub-mutex.
*/
@property Reader reader()
{
return m_reader;
}
/**
* Gets an object representing the writer lock for the associated mutex.
*
* Returns:
* A writer sub-mutex.
*/
@property Writer writer()
{
return m_writer;
}
////////////////////////////////////////////////////////////////////////////
// Reader
////////////////////////////////////////////////////////////////////////////
/**
* This class can be considered a mutex in its own right, and is used to
* negotiate a read lock for the enclosing mutex.
*/
class Reader :
Object.Monitor
{
/**
* Initializes a read/write mutex reader proxy object.
*/
this()
{
m_proxy.link = this;
this.__monitor = &m_proxy;
}
/**
* Acquires a read lock on the enclosing mutex.
*/
@trusted void lock()
{
synchronized( m_commonMutex )
{
++m_numQueuedReaders;
scope(exit) --m_numQueuedReaders;
while( shouldQueueReader )
m_readerQueue.wait();
++m_numActiveReaders;
}
}
/**
* Releases a read lock on the enclosing mutex.
*/
@trusted void unlock()
{
synchronized( m_commonMutex )
{
if( --m_numActiveReaders < 1 )
{
if( m_numQueuedWriters > 0 )
m_writerQueue.notify();
}
}
}
/**
* Attempts to acquire a read lock on the enclosing mutex. If one can
* be obtained without blocking, the lock is acquired and true is
* returned. If not, the lock is not acquired and false is returned.
*
* Returns:
* true if the lock was acquired and false if not.
*/
bool tryLock()
{
synchronized( m_commonMutex )
{
if( shouldQueueReader )
return false;
++m_numActiveReaders;
return true;
}
}
private:
@property bool shouldQueueReader()
{
if( m_numActiveWriters > 0 )
return true;
switch( m_policy )
{
case Policy.PREFER_WRITERS:
return m_numQueuedWriters > 0;
case Policy.PREFER_READERS:
default:
break;
}
return false;
}
struct MonitorProxy
{
Object.Monitor link;
}
MonitorProxy m_proxy;
}
////////////////////////////////////////////////////////////////////////////
// Writer
////////////////////////////////////////////////////////////////////////////
/**
* This class can be considered a mutex in its own right, and is used to
* negotiate a write lock for the enclosing mutex.
*/
class Writer :
Object.Monitor
{
/**
* Initializes a read/write mutex writer proxy object.
*/
this()
{
m_proxy.link = this;
this.__monitor = &m_proxy;
}
/**
* Acquires a write lock on the enclosing mutex.
*/
@trusted void lock()
{
synchronized( m_commonMutex )
{
++m_numQueuedWriters;
scope(exit) --m_numQueuedWriters;
while( shouldQueueWriter )
m_writerQueue.wait();
++m_numActiveWriters;
}
}
/**
* Releases a write lock on the enclosing mutex.
*/
@trusted void unlock()
{
synchronized( m_commonMutex )
{
if( --m_numActiveWriters < 1 )
{
switch( m_policy )
{
default:
case Policy.PREFER_READERS:
if( m_numQueuedReaders > 0 )
m_readerQueue.notifyAll();
else if( m_numQueuedWriters > 0 )
m_writerQueue.notify();
break;
case Policy.PREFER_WRITERS:
if( m_numQueuedWriters > 0 )
m_writerQueue.notify();
else if( m_numQueuedReaders > 0 )
m_readerQueue.notifyAll();
}
}
}
}
/**
* Attempts to acquire a write lock on the enclosing mutex. If one can
* be obtained without blocking, the lock is acquired and true is
* returned. If not, the lock is not acquired and false is returned.
*
* Returns:
* true if the lock was acquired and false if not.
*/
bool tryLock()
{
synchronized( m_commonMutex )
{
if( shouldQueueWriter )
return false;
++m_numActiveWriters;
return true;
}
}
private:
@property bool shouldQueueWriter()
{
if( m_numActiveWriters > 0 ||
m_numActiveReaders > 0 )
return true;
switch( m_policy )
{
case Policy.PREFER_READERS:
return m_numQueuedReaders > 0;
case Policy.PREFER_WRITERS:
default:
break;
}
return false;
}
struct MonitorProxy
{
Object.Monitor link;
}
MonitorProxy m_proxy;
}
private:
Policy m_policy;
Reader m_reader;
Writer m_writer;
Mutex m_commonMutex;
Condition m_readerQueue;
Condition m_writerQueue;
int m_numQueuedReaders;
int m_numActiveReaders;
int m_numQueuedWriters;
int m_numActiveWriters;
}
////////////////////////////////////////////////////////////////////////////////
// Unit Tests
////////////////////////////////////////////////////////////////////////////////
version( unittest )
{
static if( !is( typeof( Thread ) ) )
private import core.thread;
void testRead( ReadWriteMutex.Policy policy )
{
auto mutex = new ReadWriteMutex( policy );
auto synInfo = new Object;
int numThreads = 10;
int numReaders = 0;
int maxReaders = 0;
void readerFn()
{
synchronized( mutex.reader() )
{
synchronized( synInfo )
{
if( ++numReaders > maxReaders )
maxReaders = numReaders;
}
Thread.sleep( dur!"msecs"(1) );
synchronized( synInfo )
{
--numReaders;
}
}
}
auto group = new ThreadGroup;
for( int i = 0; i < numThreads; ++i )
{
group.create( &readerFn );
}
group.joinAll();
assert( numReaders < 1 && maxReaders > 1 );
}
void testReadWrite( ReadWriteMutex.Policy policy )
{
auto mutex = new ReadWriteMutex( policy );
auto synInfo = new Object;
int numThreads = 10;
int numReaders = 0;
int numWriters = 0;
int maxReaders = 0;
int maxWriters = 0;
int numTries = 20;
void readerFn()
{
for( int i = 0; i < numTries; ++i )
{
synchronized( mutex.reader() )
{
synchronized( synInfo )
{
if( ++numReaders > maxReaders )
maxReaders = numReaders;
}
Thread.sleep( dur!"msecs"(1) );
synchronized( synInfo )
{
--numReaders;
}
}
}
}
void writerFn()
{
for( int i = 0; i < numTries; ++i )
{
synchronized( mutex.writer() )
{
synchronized( synInfo )
{
if( ++numWriters > maxWriters )
maxWriters = numWriters;
}
Thread.sleep( dur!"msecs"(1) );
synchronized( synInfo )
{
--numWriters;
}
}
}
}
auto group = new ThreadGroup;
for( int i = 0; i < numThreads; ++i )
{
group.create( &readerFn );
group.create( &writerFn );
}
group.joinAll();
assert( numReaders < 1 && maxReaders > 1 &&
numWriters < 1 && maxWriters < 2 );
}
unittest
{
testRead( ReadWriteMutex.Policy.PREFER_READERS );
testRead( ReadWriteMutex.Policy.PREFER_WRITERS );
testReadWrite( ReadWriteMutex.Policy.PREFER_READERS );
testReadWrite( ReadWriteMutex.Policy.PREFER_WRITERS );
}
}
| D |
/*
* $Id: rand.d,v 1.2 2005/01/01 12:40:28 kenta Exp $
*
* Copyright 2004 Kenta Cho. Some rights reserved.
*/
module abagames.util.rand;
private import core.stdc.time;
private import std.stream;
private import std.datetime;
/**
* Random number generator.
*/
public class Rand {
public this() {
time_t timer = stdTimeToUnixTime(Clock.currStdTime());
init_genrand(cast(uint) timer);
}
public void setSeed(long n) {
init_genrand(cast(uint) n);
}
public uint nextInt32() {
return genrand_int32();
}
public int nextInt(ulong n) {
if (n == 0)
return 0;
else
return cast(int) (genrand_int32() % n);
}
public int nextSignedInt(int n) {
if (n == 0)
return 0;
else
return genrand_int32() % (n * 2) - n;
}
public float nextFloat(float n) {
return genrand_real1() * n;
}
public float nextSignedFloat(float n) {
return genrand_real1() * (n * 2) - n;
}
/*
MT.d
Mersenne Twister random number generator -- D
Based on code by Makoto Matsumoto, Takuji Nishimura, Shawn Cokus,
Matthe Bellew, and Isaku Wada
Andrew C. Edwards v0.1 30 September 2003 edwardsac@ieee.org
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
Copyright (C) 2003, Andrew C. Edwards
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The original code included the following notice:
Any feedback is very welcome.
http://www.math.keio.ac.jp/matumoto/emt.html
email: matumoto@math.keio.ac.jp
Please CC: edwardsac@ieee.org on all correspondence
*/
/*
Modified by Kenta Cho.
Remove 'static' to wrap with Rand class.
*/
/* Period parameters */
static const int N = 624;
static const int M = 397;
static const uint MATRIX_A = 0x9908b0dfU; /* constant vector a */
static const uint UMASK = 0x80000000U; /* most significant w-r bits */
static const uint LMASK = 0x7fffffffU; /* least significant r bits */
uint MIXBITS(uint u, uint v) { return (u & UMASK) | (v & LMASK); }
uint TWIST(uint u,uint v) { return (MIXBITS(u,v) >> 1) ^ (v&1 ? MATRIX_A : 0); }
uint state[N]; /* the array for the state vector */
int left = 1;
int initf = 0;
uint *next;
/* initializes state[N] with a seed */
void init_genrand(uint s)
{
state[0]= s & 0xffffffffUL;
for (int j=1; j<N; j++) {
state[j] = (1812433253U * (state[j-1] ^ (state[j-1] >> 30)) + j);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array state[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
state[j] &= 0xffffffffU; /* for >32 bit machines */
}
left = 1; initf = 1;
}
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
//uint init_key[];
//uint key_length;
void init_by_array(uint init_key[], uint key_length)
{
int i, j, k;
init_genrand(19650218UL);
i=1; j=0;
k = (N>key_length ? N : key_length);
for (; k; k--) {
state[i] = (state[i] ^ ((state[i-1] ^ (state[i-1] >> 30)) * 1664525U))
+ init_key[j] + j; /* non linear */
state[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++; j++;
if (i>=N) { state[0] = state[N-1]; i=1; }
if (j>=key_length) j=0;
}
for (k=N-1; k; k--) {
state[i] = (state[i] ^ ((state[i-1] ^ (state[i-1] >> 30)) * 1566083941U))
- i; /* non linear */
state[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++;
if (i>=N) { state[0] = state[N-1]; i=1; }
}
state[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
left = 1; initf = 1;
}
void next_state()
{
uint *p=state.ptr;
/* if init_genrand() has not been called, */
/* a default initial seed is used */
if (initf==0) init_genrand(5489UL);
left = N;
next = state.ptr;
for (int j=N-M+1; --j; p++)
*p = p[M] ^ TWIST(p[0], p[1]);
for (int j=M; --j; p++)
*p = p[M-N] ^ TWIST(p[0], p[1]);
*p = p[M-N] ^ TWIST(p[0], state[0]);
}
/* generates a random number on [0,0xffffffff]-interval */
uint genrand_int32()
{
uint y;
if (--left == 0) next_state();
y = *next++;
/* Tempering */
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680UL;
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);
return y;
}
/* generates a random number on [0,0x7fffffff]-interval */
long genrand_int31()
{
uint y;
if (--left == 0) next_state();
y = *next++;
/* Tempering */
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680UL;
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);
return cast(long)(y>>1);
}
/* generates a random number on [0,1]-real-interval */
double genrand_real1()
{
uint y;
if (--left == 0) next_state();
y = *next++;
/* Tempering */
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680UL;
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);
return cast(double)y * (1.0/4294967295.0);
/* divided by 2^32-1 */
}
/* generates a random number on [0,1)-real-interval */
double genrand_real2()
{
uint y;
if (--left == 0) next_state();
y = *next++;
/* Tempering */
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680UL;
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);
return cast(double)y * (1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on (0,1)-real-interval */
double genrand_real3()
{
uint y;
if (--left == 0) next_state();
y = *next++;
/* Tempering */
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680UL;
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);
return (cast(double)y + 0.5) * (1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on [0,1) with 53-bit resolution*/
double genrand_res53()
{
uint a=genrand_int32()>>5, b=genrand_int32()>>6;
return(a*67108864.0+b)*(1.0/9007199254740992.0);
}
}
| D |
/**
Copyright: Copyright (c) 2017, Joakim Brännström. All rights reserved.
License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0)
Author: Joakim Brännström (joakim.brannstrom@gmx.com)
*/
module metric_factory.sqlite3;
import std.datetime : SysTime;
import logger = std.experimental.logger;
import d2sqlite3 : sqlDatabase = Database;
import metric_factory.metric.collector : Collector;
import metric_factory.metric.types : TestHost;
import metric_factory.types : Timestamp, Path;
import metric_factory.plugin : Plugin;
private struct MetricId {
long payload;
alias payload this;
}
private struct BucketId {
long payload;
alias payload this;
}
private struct TestHostId {
long payload;
alias payload this;
}
/**
*
* From the sqlite3 manual $(LINK https://www.sqlite.org/datatype3.html):
* Each value stored in an SQLite database (or manipulated by the database
* engine) has one of the following storage classes:
*
* NULL. The value is a NULL value.
*
* INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes
* depending on the magnitude of the value.
*
* REAL. The value is a floating point value, stored as an 8-byte IEEE floating
* point number.
*
* TEXT. The value is a text string, stored using the database encoding (UTF-8,
* UTF-16BE or UTF-16LE).
*
* BLOB. The value is a blob of data, stored exactly as it was input.
*
* A storage class is more general than a datatype. The INTEGER storage class,
* for example, includes 6 different integer datatypes of different lengths.
* This makes a difference on disk. But as soon as INTEGER values are read off
* of disk and into memory for processing, they are converted to the most
* general datatype (8-byte signed integer). And so for the most part, "storage
* class" is indistinguishable from "datatype" and the two terms can be used
* interchangeably.
*/
struct Database {
import std.typecons : Tuple, Nullable;
import metric_factory.metric.types;
private sqlDatabase db;
private immutable sql_find_bucket = "SELECT id FROM bucket WHERE name == :name";
static auto make(Path p) {
return Database(initializeDB(p));
}
/// Insert a Collector into the DB.
/// Returns: the ID of the metric that where added
MetricId put(const Timestamp ts, Collector coll) {
import std.format : format;
import d2sqlite3;
auto stmt = db.prepare("INSERT INTO metric (timestamp) VALUES (:timestamp)");
stmt.bind(":timestamp", format("%04s-%02s-%02sT%02s:%02s:%02s.%s",
ts.year, cast(ushort) ts.month, ts.day, ts.hour, ts.minute,
ts.second, ts.fracSecs.total!"msecs"));
stmt.execute;
const long metric_id = db.lastInsertRowid;
stmt.reset;
stmt = db.prepare(
"INSERT INTO timer_t (metricid, bucketid, elapsed_ms) VALUES (:mid, :bid, :ms)");
foreach (v; coll.timerRange) {
const long bucket_id = put(v.name);
stmt.bindAll(metric_id, bucket_id, v.value.total!"msecs");
stmt.execute;
stmt.reset;
}
string makeGauge(string range_t) {
import std.format : format;
return format(`stmt = db.prepare(
"INSERT INTO gauge_t (metricid, bucketid, value) VALUES (:mid, :bid, :value)");
foreach (v; coll.%s) {
const long bucket_id = put(v.name);
stmt.bindAll(metric_id, bucket_id, v.value.payload);
stmt.execute;
stmt.reset;
}`, range_t);
}
mixin(makeGauge("gaugeRange"));
mixin(makeGauge("maxRange"));
mixin(makeGauge("minRange"));
stmt = db.prepare(
"INSERT INTO counter_t (metricid, bucketid, change, sampleRate) VALUES (:mid, :bid, :value, :sample_r)");
foreach (v; coll.counterRange) {
const long bucket_id = put(v.name);
stmt.bindAll(metric_id, bucket_id, v.change.payload,
v.sampleRate.isNull ? 1.0 : v.sampleRate.get.payload);
stmt.execute;
stmt.reset;
}
stmt = db.prepare(
"INSERT INTO set_t (metricid, bucketid, value) VALUES (:mid, :bid, :value)");
foreach (v; coll.setRange) {
const long bucket_id = put(v.name);
stmt.bindAll(metric_id, bucket_id, v.value.payload);
stmt.execute;
stmt.reset;
}
return MetricId(metric_id);
}
/// Put a bucket into the database.
/// Returns: its primary key.
BucketId put(const BucketName b) {
auto bucket_stmt = db.prepare(sql_find_bucket);
bucket_stmt.bind(":name", b.payload);
auto res = bucket_stmt.execute;
if (res.empty) {
auto bucket_insert_stmt = db.prepare("INSERT INTO bucket (name) VALUES (:name)");
bucket_insert_stmt.bind(":name", b.payload);
bucket_insert_stmt.execute;
return db.lastInsertRowid.BucketId;
} else {
return res.oneValue!long.BucketId;
}
}
BucketName get(BucketId bid) {
auto bucket_stmt = db.prepare("SELECT name FROM bucket WHERE bucket.id == :bid");
bucket_stmt.bind(":bid", bid.payload);
auto res = bucket_stmt.execute;
return BucketName(res.oneValue!string);
}
void put(const TestHost host, const Timestamp ts, Collector coll) {
import d2sqlite3;
auto metric_id = this.put(ts, coll);
auto stmt = db.prepare("INSERT INTO test_host (host) VALUES (:host)");
stmt.bind(":host", cast(string) host.name);
stmt.execute;
const long test_hostid = db.lastInsertRowid;
stmt.reset;
stmt = db.prepare("UPDATE metric SET test_hostid = :thid WHERE metric.id == :mid");
stmt.bindAll(test_hostid, cast(long) metric_id);
stmt.execute;
}
alias GetMetricResult = Tuple!(MetricId, "id", TestHostId, "testHostId",
Timestamp, "timestamp");
/// Returns: all stored metric ID.
GetMetricResult[] getMetrics() {
import std.array;
import std.algorithm : map;
import d2sqlite3;
// maybe order by timestamp?
auto stmt = db.prepare("SELECT id,test_hostid,timestamp FROM metric ORDER BY id");
auto res = stmt.execute;
return res.map!(a => GetMetricResult(MetricId(a.peek!long(0)),
TestHostId(a.peek!long(1)), Timestamp(a.peek!string(2).fromSqLiteDateTime))).array();
}
Nullable!TestHost getTestHost(TestHostId id) {
import d2sqlite3;
typeof(return) rval;
auto stmt = db.prepare("SELECT host FROM test_host WHERE id == :id");
stmt.bind(":id", id.payload);
auto res = stmt.execute;
if (!res.empty) {
rval = TestHost(TestHost.Value(res.oneValue!string));
}
return rval;
}
Collector get(MetricId mid) {
import core.time : dur;
import d2sqlite3;
import metric_factory.metric.collector : Collector;
auto coll = new Collector;
auto stmt = db.prepare("SELECT bucketid,value FROM set_t WHERE set_t.metricid == :mid");
stmt.bind(":mid", mid.payload);
foreach (v; stmt.execute) {
auto bucket = this.get(BucketId(v.peek!long(0)));
coll.put(Set(bucket, Set.Value(v.peek!long(1))));
}
stmt.reset;
stmt = db.prepare(
"SELECT bucketid,change,sampleRate FROM counter_t WHERE counter_t.metricid == :mid");
stmt.bind(":mid", mid.payload);
foreach (v; stmt.execute) {
auto bucket = this.get(BucketId(v.peek!long(0)));
coll.put(Counter(bucket, Counter.Change(v.peek!long(1)),
Counter.SampleRate(v.peek!double(2))));
}
stmt.reset;
string makeGauge(string kind) {
import std.format : format;
return format(`stmt = db.prepare("SELECT bucketid,value FROM gauge_t WHERE gauge_t.metricid == :mid");
stmt.bind(":mid", mid.payload);
foreach (v; stmt.execute) {
auto bucket = this.get(BucketId(v.peek!long(0)));
coll.put(%s(bucket, %s.Value(v.peek!long(1))));
}
stmt.reset;`,
kind, kind);
}
mixin(makeGauge("Gauge"));
mixin(makeGauge("Max"));
mixin(makeGauge("Min"));
stmt = db.prepare("SELECT bucketid,elapsed_ms FROM timer_t WHERE timer_t.metricid == :mid");
stmt.bind(":mid", mid.payload);
foreach (v; stmt.execute) {
auto bucket = this.get(BucketId(v.peek!long(0)));
coll.put(Timer(bucket, Timer.Value(v.peek!long(1).dur!"msecs")));
}
stmt.reset;
return coll;
}
}
private:
sqlDatabase initializeDB(Path p) {
import d2sqlite3;
if (p.length == 0)
p = Path("metric_factory.sqlite3");
try {
auto db = sqlDatabase(p, SQLITE_OPEN_READWRITE);
return db;
}
catch (Exception e) {
logger.trace(e.msg);
logger.trace("Initializing a new sqlite3 database");
}
auto db = sqlDatabase(p, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
initializeTables(db);
return db;
}
void initializeTables(ref sqlDatabase db) {
// the timestamp shall be in UTC time.
db.run("CREATE TABLE metric (
id INTEGER PRIMARY KEY,
test_hostid INTEGER,
timestamp DATETIME NOT NULL
)");
db.run("CREATE TABLE bucket (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
)");
db.run("CREATE TABLE test_host (
id INTEGER PRIMARY KEY,
host TEXT
)");
db.run("CREATE TABLE counter_t (
id INTEGER PRIMARY KEY,
metricid INTEGER NOT NULL,
bucketid INTEGER NOT NULL,
change INTEGER,
sampleRate REAL,
FOREIGN KEY(bucketid) REFERENCES plugin(id),
FOREIGN KEY(metricid) REFERENCES metric(id)
)");
db.run("CREATE TABLE gauge_t (
id INTEGER PRIMARY KEY,
metricid INTEGER NOT NULL,
bucketid INTEGER NOT NULL,
value INTEGER,
FOREIGN KEY(bucketid) REFERENCES plugin(id),
FOREIGN KEY(metricid) REFERENCES metric(id)
)");
db.run("CREATE TABLE timer_t (
id INTEGER PRIMARY KEY,
metricid INTEGER NOT NULL,
bucketid INTEGER NOT NULL,
elapsed_ms INTEGER,
FOREIGN KEY(bucketid) REFERENCES plugin(id),
FOREIGN KEY(metricid) REFERENCES metric(id)
)");
db.run("CREATE TABLE set_t (
id INTEGER PRIMARY KEY,
metricid INTEGER NOT NULL,
bucketid INTEGER NOT NULL,
value INTEGER,
FOREIGN KEY(bucketid) REFERENCES plugin(id),
FOREIGN KEY(metricid) REFERENCES metric(id)
)");
}
SysTime fromSqLiteDateTime(string raw_dt) {
import core.time : dur;
import std.datetime : DateTime, UTC;
import std.format : formattedRead;
int year, month, day, hour, minute, second, msecs;
formattedRead(raw_dt, "%s-%s-%sT%s:%s:%s.%s", year, month, day, hour, minute, second, msecs);
auto dt = DateTime(year, month, day, hour, minute, second);
return SysTime(dt, msecs.dur!"msecs", UTC());
}
| D |
module client;
/*
* Hunt - A refined core library for D programming language.
*
* Copyright (C) 2018-2019 HuntLabs
*
* Website: https://www.huntlabs.net/
*
* Licensed under the Apache-2.0 License.
*
*/
import std.stdio;
import hunt.event;
import hunt.io.UdpSocket : UdpSocket;
import std.socket;
import std.functional;
import std.exception;
import core.thread;
import core.time;
// http://www.cs.ubbcluj.ro/~dadi/compnet/labs/lab3/udp-broadcast.html
void main()
{
EventLoop loop = new EventLoop();
// UDP Client
UdpSocket udpClient = new UdpSocket(loop);
int count = 3;
Address address = new InternetAddress(InternetAddress.ADDR_ANY, InternetAddress.PORT_ANY);
udpClient.enableBroadcast(true)
.bind(address)
// .bind("10.1.222.120", InternetAddress.PORT_ANY)
.onReceived((in ubyte[] data, Address addr) {
debug writefln("Client => count=%d, server: %s, received: %s", count,
addr, cast(string) data);
if (--count > 0)
{
udpClient.sendTo(data, addr);
}
else
{
udpClient.sendTo(cast(const(void)[]) "bye!", addr);
udpClient.close();
// loop.stop();
}
})
.start();
udpClient.sendTo(cast(const(void)[]) "Hello world!", parseAddress("255.255.255.255", 8080));
// udpClient.sendTo(cast(const(void)[]) "Hello world!", parseAddress("127.0.0.1", 8090));
// udpClient.sendTo(cast(const(void)[]) "Hello world!", parseAddress("10.1.222.120", 8080));
loop.run();
}
| D |
<?xml version="1.0" encoding="ASCII" standalone="no"?>
<di:SashWindowsMngr xmlns:di="http://www.eclipse.org/papyrus/0.7.0/sashdi" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmi:version="2.0">
<pageList>
<availablePage>
<emfPageIdentifier href="VAR_2_banking-2151671726.notation#_copSALmGEeKQQp7P9cQvNQ"/>
</availablePage>
</pageList>
<sashModel currentSelection="//@sashModel/@windows.0/@children.0">
<windows>
<children xsi:type="di:TabFolder">
<children>
<emfPageIdentifier href="VAR_2_banking-2151671726.notation#_copSALmGEeKQQp7P9cQvNQ"/>
</children>
</children>
</windows>
</sashModel>
</di:SashWindowsMngr>
| D |
module xf.platform.osx.DogView;
import xf.platform.osx.objc_class;
import xf.platform.osx.objc_runtime;
import xf.platform.osx.NSObject;
import xf.platform.osx.NSGeometry;
import xf.dog.Common: GL;
class DogView {
static this() {
registerClass("DogView", "NSOpenGLView");
}
this(id window, NSRect rect, id PF, id function(id, SEL, ...) drawFunc) {
_meta = lookUp("DogView");
_obj = createInstance(meta);
selDraw = sel("drawDogView");
selFlush = sel("flushBuffer");
drawMethod.method_count = 1;
drawMethod.method_list[0].method_name = selDraw;
drawMethod.method_list[0].method_imp = drawFunc;
class_removeMethods(meta, &drawMethod);
class_addMethods(meta, &drawMethod);
send(obj, sel("initWithFrame:pixelFormat:"), rect, PF);
send(window, sel("setContentView:"), obj);
_context = send(obj, sel("openGLContext"));
send(context, sel("setView:"), obj);
send(context, sel("makeCurrentContext"));
}
void destroy() {
send(obj, sel("clearGLContext"));
class_removeMethods(meta, &drawMethod);
}
void flush() {
send(context, selFlush);
}
void opCall(void delegate(GL) dg, GL gl) {
send(obj, selDraw, dg, gl);
}
id context() {
return _context;
}
private {
objc_method_list drawMethod;
id _context;
SEL selDraw;
SEL selFlush;
}
mixin NSObject;
}
| D |
/*
* This file is part of gtkD.
*
* gtkD is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* gtkD is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with gtkD; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// generated automatically - do not change
// find conversion definition on APILookup.txt
// implement new conversion functionalities on the wrap.utils pakage
/*
* Conversion parameters:
* inFile = GstBin.html
* outPack = gstreamer
* outFile = Bin
* strct = GstBin
* realStrct=
* ctorStrct=
* clss = Bin
* interf =
* class Code: Yes
* interface Code: No
* template for:
* extend =
* implements:
* prefixes:
* - gst_bin_
* - gst_
* omit structs:
* omit prefixes:
* omit code:
* - gst_bin_new
* omit signals:
* imports:
* - gtkD.glib.Str
* - gtkD.gstreamer.Element
* - gtkD.gstreamer.Iterator
* structWrap:
* - GstBin* -> Bin
* - GstElement* -> Element
* - GstIterator* -> Iterator
* module aliases:
* local aliases:
* overrides:
*/
module gtkD.gstreamer.Bin;
public import gtkD.gstreamerc.gstreamertypes;
private import gtkD.gstreamerc.gstreamer;
private import gtkD.glib.ConstructionException;
private import gtkD.gobject.Signals;
public import gtkD.gtkc.gdktypes;
private import gtkD.glib.Str;
private import gtkD.gstreamer.Element;
private import gtkD.gstreamer.Iterator;
private import gtkD.gstreamer.Element;
/**
* Description
* GstBin is an element that can contain other GstElement, allowing them to be
* managed as a group.
* Pads from the child elements can be ghosted to the bin, see GstGhostPad.
* This makes the bin look like any other elements and enables creation of
* higher-level abstraction elements.
* A new GstBin is created with gst_bin_new(). Use a GstPipeline instead if you
* want to create a toplevel bin because a normal bin doesn't have a bus or
* handle clock distribution of its own.
* After the bin has been created you will typically add elements to it with
* gst_bin_add(). You can remove elements with gst_bin_remove().
* An element can be retrieved from a bin with gst_bin_get_by_name(), using the
* elements name. gst_bin_get_by_name_recurse_up() is mainly used for internal
* purposes and will query the parent bins when the element is not found in the
* current bin.
* An iterator of elements in a bin can be retrieved with
* gst_bin_iterate_elements(). Various other iterators exist to retrieve the
* elements in a bin.
* gst_object_unref() is used to drop your reference to the bin.
* The element-added signal is
* fired whenever a new element is added to the bin. Likewise the element-removed signal is fired
* whenever an element is removed from the bin.
* Notes
* A GstBin internally intercepts every GstMessage posted by its children and
* implements the following default behaviour for each of them:
* GST_MESSAGE_EOS
* This message is only posted by sinks in the PLAYING
* state. If all sinks posted the EOS message, this bin will post and EOS
* message upwards.
* GST_MESSAGE_SEGMENT_START
* just collected and never forwarded upwards.
* The messages are used to decide when all elements have completed playback
* of their segment.
* GST_MESSAGE_SEGMENT_DONE
* Is posted by GstBin when all elements that posted
* a SEGMENT_START have posted a SEGMENT_DONE.
* GST_MESSAGE_DURATION
* Is posted by an element that detected a change
* in the stream duration. The default bin behaviour is to clear any
* cached duration values so that the next duration query will perform
* a full duration recalculation. The duration change is posted to the
* application so that it can refetch the new duration with a duration
* query.
* GST_MESSAGE_CLOCK_LOST
* This message is posted by an element when it
* can no longer provide a clock. The default bin behaviour is to
* check if the lost clock was the one provided by the bin. If so and
* the bin is currently in the PLAYING state, the message is forwarded to
* the bin parent.
* This message is also generated when a clock provider is removed from
* the bin. If this message is received by the application, it should
* PAUSE the pipeline and set it back to PLAYING to force a new clock
* distribution.
* GST_MESSAGE_CLOCK_PROVIDE
* This message is generated when an element
* can provide a clock. This mostly happens when a new clock
* provider is added to the bin. The default behaviour of the bin is to
* mark the currently selected clock as dirty, which will perform a clock
* recalculation the next time the bin is asked to provide a clock.
* This message is never sent tot the application but is forwarded to
* the parent of the bin.
* OTHERS
* posted upwards.
* A GstBin implements the following default behaviour for answering to a
* GstQuery:
* GST_QUERY_DURATION
* If the query has been asked before with the same format
* and the bin is a toplevel bin (ie. has no parent),
* use the cached previous value. If no previous value was cached, the
* query is sent to all sink elements in the bin and the MAXIMUM of all
* values is returned. If the bin is a toplevel bin the value is cached.
* If no sinks are available in the bin, the query fails.
* GST_QUERY_POSITION
* The query is sent to all sink elements in the bin and the
* MAXIMUM of all values is returned. If no sinks are available in the bin,
* the query fails.
* OTHERS
* the query is forwarded to all sink elements, the result
* of the first sink that answers the query successfully is returned. If no
* sink is in the bin, the query fails.
* A GstBin will by default forward any event sent to it to all sink elements.
* If all the sinks return TRUE, the bin will also return TRUE, else FALSE is
* returned. If no sinks are in the bin, the event handler will return TRUE.
* Last reviewed on 2006-04-28 (0.10.6)
*/
public class Bin : Element
{
/** the main Gtk struct */
protected GstBin* gstBin;
public GstBin* getBinStruct()
{
return gstBin;
}
/** the main Gtk struct as a void* */
protected override void* getStruct()
{
return cast(void*)gstBin;
}
/**
* Sets our main struct and passes it to the parent class
*/
public this (GstBin* gstBin)
{
if(gstBin is null)
{
this = null;
return;
}
//Check if there already is a D object for this gtk struct
void* ptr = getDObject(cast(GObject*)gstBin);
if( ptr !is null )
{
this = cast(Bin)ptr;
return;
}
super(cast(GstElement*)gstBin);
this.gstBin = gstBin;
}
/**
* Creates a new bin with the given name.
* Params:
* name = the name of the new bin
* Returns:
* a new GstBin
*/
public this(string name)
{
// GstElement* gst_bin_new (const gchar *name);
this( cast(GstBin*) gst_bin_new(Str.toStringz(name)) );
}
/** */
public this(Element elem)
{
super( elem.getElementStruct() );
this.gstBin = cast(GstBin*)elem.getElementStruct();
}
/**
*/
int[char[]] connectedSignals;
void delegate(Element, Bin)[] onElementAddedListeners;
/**
* Will be emitted after the element was added to the bin.
*/
void addOnElementAdded(void delegate(Element, Bin) dlg, ConnectFlags connectFlags=cast(ConnectFlags)0)
{
if ( !("element-added" in connectedSignals) )
{
Signals.connectData(
getStruct(),
"element-added",
cast(GCallback)&callBackElementAdded,
cast(void*)this,
null,
connectFlags);
connectedSignals["element-added"] = 1;
}
onElementAddedListeners ~= dlg;
}
extern(C) static void callBackElementAdded(GstBin* binStruct, GstElement* element, Bin bin)
{
foreach ( void delegate(Element, Bin) dlg ; bin.onElementAddedListeners )
{
dlg(new Element(element), bin);
}
}
void delegate(Element, Bin)[] onElementRemovedListeners;
/**
* Will be emitted after the element was removed from the bin.
*/
void addOnElementRemoved(void delegate(Element, Bin) dlg, ConnectFlags connectFlags=cast(ConnectFlags)0)
{
if ( !("element-removed" in connectedSignals) )
{
Signals.connectData(
getStruct(),
"element-removed",
cast(GCallback)&callBackElementRemoved,
cast(void*)this,
null,
connectFlags);
connectedSignals["element-removed"] = 1;
}
onElementRemovedListeners ~= dlg;
}
extern(C) static void callBackElementRemoved(GstBin* binStruct, GstElement* element, Bin bin)
{
foreach ( void delegate(Element, Bin) dlg ; bin.onElementRemovedListeners )
{
dlg(new Element(element), bin);
}
}
/**
* Adds the given element to the bin. Sets the element's parent, and thus
* takes ownership of the element. An element can only be added to one bin.
* If the element's pads are linked to other pads, the pads will be unlinked
* before the element is added to the bin.
* MT safe.
* Params:
* element = the GstElement to add
* Returns: TRUE if the element could be added, FALSE ifthe bin does not want to accept the element.
*/
public int add(Element element)
{
// gboolean gst_bin_add (GstBin *bin, GstElement *element);
return gst_bin_add(gstBin, (element is null) ? null : element.getElementStruct());
}
/**
* Removes the element from the bin, unparenting it as well.
* Unparenting the element means that the element will be dereferenced,
* so if the bin holds the only reference to the element, the element
* will be freed in the process of removing it from the bin. If you
* want the element to still exist after removing, you need to call
* gst_object_ref() before removing it from the bin.
* If the element's pads are linked to other pads, the pads will be unlinked
* before the element is removed from the bin.
* MT safe.
* Params:
* element = the GstElement to remove
* Returns: TRUE if the element could be removed, FALSE ifthe bin does not want to remove the element.
*/
public int remove(Element element)
{
// gboolean gst_bin_remove (GstBin *bin, GstElement *element);
return gst_bin_remove(gstBin, (element is null) ? null : element.getElementStruct());
}
/**
* Gets the element with the given name from a bin. This
* function recurses into child bins.
* Returns NULL if no element with the given name is found in the bin.
* MT safe. Caller owns returned reference.
* Params:
* name = the element name to search for
* Returns: the GstElement with the given name, or NULL
*/
public Element getByName(string name)
{
// GstElement* gst_bin_get_by_name (GstBin *bin, const gchar *name);
auto p = gst_bin_get_by_name(gstBin, Str.toStringz(name));
if(p is null)
{
return null;
}
return new Element(cast(GstElement*) p);
}
/**
* Gets the element with the given name from this bin. If the
* element is not found, a recursion is performed on the parent bin.
* Params:
* name = the element name to search for
* Returns: the GstElement with the given name, or NULL
*/
public Element getByNameRecurseUp(string name)
{
// GstElement* gst_bin_get_by_name_recurse_up (GstBin *bin, const gchar *name);
auto p = gst_bin_get_by_name_recurse_up(gstBin, Str.toStringz(name));
if(p is null)
{
return null;
}
return new Element(cast(GstElement*) p);
}
/**
* Looks for an element inside the bin that implements the given
* interface. If such an element is found, it returns the element.
* You can cast this element to the given interface afterwards. If you want
* all elements that implement the interface, use
* gst_bin_iterate_all_by_interface(). This function recurses into child bins.
* MT safe. Caller owns returned reference.
* Params:
* iface = the GType of an interface
* Returns: A GstElement inside the bin implementing the interface
*/
public Element getByInterface(GType iface)
{
// GstElement* gst_bin_get_by_interface (GstBin *bin, GType iface);
auto p = gst_bin_get_by_interface(gstBin, iface);
if(p is null)
{
return null;
}
return new Element(cast(GstElement*) p);
}
/**
* Gets an iterator for the elements in this bin.
* Each element yielded by the iterator will have its refcount increased, so
* unref after use.
* MT safe. Caller owns returned value.
* Returns: a GstIterator of GstElement, or NULL
*/
public Iterator iterateElements()
{
// GstIterator* gst_bin_iterate_elements (GstBin *bin);
auto p = gst_bin_iterate_elements(gstBin);
if(p is null)
{
return null;
}
return new Iterator(cast(GstIterator*) p);
}
/**
* Gets an iterator for the elements in this bin.
* This iterator recurses into GstBin children.
* Each element yielded by the iterator will have its refcount increased, so
* unref after use.
* MT safe. Caller owns returned value.
* Returns: a GstIterator of GstElement, or NULL
*/
public Iterator iterateRecurse()
{
// GstIterator* gst_bin_iterate_recurse (GstBin *bin);
auto p = gst_bin_iterate_recurse(gstBin);
if(p is null)
{
return null;
}
return new Iterator(cast(GstIterator*) p);
}
/**
* Gets an iterator for all elements in the bin that have the
* GST_ELEMENT_IS_SINK flag set.
* Each element yielded by the iterator will have its refcount increased, so
* unref after use.
* MT safe. Caller owns returned value.
* Returns: a GstIterator of GstElement, or NULL
*/
public Iterator iterateSinks()
{
// GstIterator* gst_bin_iterate_sinks (GstBin *bin);
auto p = gst_bin_iterate_sinks(gstBin);
if(p is null)
{
return null;
}
return new Iterator(cast(GstIterator*) p);
}
/**
* Gets an iterator for the elements in this bin in topologically
* sorted order. This means that the elements are returned from
* the most downstream elements (sinks) to the sources.
* This function is used internally to perform the state changes
* of the bin elements.
* Each element yielded by the iterator will have its refcount increased, so
* unref after use.
* MT safe. Caller owns returned value.
* Returns: a GstIterator of GstElement, or NULL
*/
public Iterator iterateSorted()
{
// GstIterator* gst_bin_iterate_sorted (GstBin *bin);
auto p = gst_bin_iterate_sorted(gstBin);
if(p is null)
{
return null;
}
return new Iterator(cast(GstIterator*) p);
}
/**
* Gets an iterator for all elements in the bin that have no sinkpads and have
* the GST_ELEMENT_IS_SINK flag unset.
* Each element yielded by the iterator will have its refcount increased, so
* unref after use.
* MT safe. Caller owns returned value.
* Returns: a GstIterator of GstElement, or NULL
*/
public Iterator iterateSources()
{
// GstIterator* gst_bin_iterate_sources (GstBin *bin);
auto p = gst_bin_iterate_sources(gstBin);
if(p is null)
{
return null;
}
return new Iterator(cast(GstIterator*) p);
}
/**
* Looks for all elements inside the bin that implements the given
* interface. You can safely cast all returned elements to the given interface.
* The function recurses inside child bins. The iterator will yield a series
* of GstElement that should be unreffed after use.
* Each element yielded by the iterator will have its refcount increased, so
* unref after use.
* MT safe. Caller owns returned value.
* Params:
* iface = the GType of an interface
* Returns: a GstIterator of GstElement for all elements in the bin implementing the given interface, or NULL
*/
public Iterator iterateAllByInterface(GType iface)
{
// GstIterator* gst_bin_iterate_all_by_interface (GstBin *bin, GType iface);
auto p = gst_bin_iterate_all_by_interface(gstBin, iface);
if(p is null)
{
return null;
}
return new Iterator(cast(GstIterator*) p);
}
/**
* Recursively looks for elements with an unconnected pad of the given
* direction within the specified bin and returns an unconnected pad
* if one is found, or NULL otherwise. If a pad is found, the caller
* owns a reference to it and should use gst_object_unref() on the
* pad when it is not needed any longer.
* Params:
* direction = whether to look for an unconnected source or sink pad
* Returns: unconnected pad of the given direction, or NULL.Since 0.10.3
*/
public GstPad* findUnconnectedPad(GstPadDirection direction)
{
// GstPad* gst_bin_find_unconnected_pad (GstBin *bin, GstPadDirection direction);
return gst_bin_find_unconnected_pad(gstBin, direction);
}
}
| D |
/Users/Rens/Development/RecoveryJournal/Build/Intermediates/RecoveryJournal.build/Debug/Async.build/Objects-normal/x86_64/DispatchEventLoop.o : /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Socket/SocketSource.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/EventSource.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Kqueue/KqueueEventSource.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Dispatch/DispatchEventSource.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Epoll/EpollEventSource.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/File/FileCache.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/File/File.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/FutureType.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Promise.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/File/DirectoryConfig.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+DoCatch.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Socket/SocketSink.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Global.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Signal.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Stream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/Stream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/DeltaStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/BasicStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/QueueStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/TranscribingStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/TranslatingStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/ConnectingStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/PushStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/DrainStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/MapStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/ByteParserStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/EmitterStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/ByteSerializerStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Socket/SocketStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/InputStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/OutputStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Transform.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Flatten.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Map.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Unwrap.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/EventLoop.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Kqueue/KqueueEventLoop.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Dispatch/DispatchEventLoop.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Epoll/EpollEventLoop.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/File/FileReader.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Worker.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/PromiseError.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Socket/Socket.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+BlockingAwait.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/FutureResult.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/ConnectionContext.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
/Users/Rens/Development/RecoveryJournal/Build/Intermediates/RecoveryJournal.build/Debug/Async.build/Objects-normal/x86_64/DispatchEventLoop~partial.swiftmodule : /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Socket/SocketSource.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/EventSource.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Kqueue/KqueueEventSource.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Dispatch/DispatchEventSource.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Epoll/EpollEventSource.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/File/FileCache.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/File/File.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/FutureType.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Promise.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/File/DirectoryConfig.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+DoCatch.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Socket/SocketSink.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Global.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Signal.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Stream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/Stream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/DeltaStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/BasicStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/QueueStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/TranscribingStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/TranslatingStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/ConnectingStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/PushStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/DrainStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/MapStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/ByteParserStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/EmitterStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/ByteSerializerStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Socket/SocketStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/InputStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/OutputStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Transform.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Flatten.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Map.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Unwrap.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/EventLoop.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Kqueue/KqueueEventLoop.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Dispatch/DispatchEventLoop.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Epoll/EpollEventLoop.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/File/FileReader.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Worker.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/PromiseError.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Socket/Socket.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+BlockingAwait.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/FutureResult.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/ConnectionContext.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
/Users/Rens/Development/RecoveryJournal/Build/Intermediates/RecoveryJournal.build/Debug/Async.build/Objects-normal/x86_64/DispatchEventLoop~partial.swiftdoc : /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Socket/SocketSource.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/EventSource.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Kqueue/KqueueEventSource.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Dispatch/DispatchEventSource.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Epoll/EpollEventSource.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/File/FileCache.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/File/File.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/FutureType.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Promise.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/File/DirectoryConfig.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+DoCatch.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Socket/SocketSink.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Global.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Signal.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Stream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/Stream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/DeltaStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/BasicStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/QueueStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/TranscribingStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/TranslatingStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/ConnectingStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/PushStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/DrainStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/MapStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/ByteParserStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/EmitterStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/ByteSerializerStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Socket/SocketStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/InputStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/OutputStream.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Transform.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Flatten.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Map.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+Unwrap.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/EventLoop.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Kqueue/KqueueEventLoop.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Dispatch/DispatchEventLoop.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Epoll/EpollEventLoop.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/File/FileReader.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/EventLoop/Worker.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/PromiseError.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Socket/Socket.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/Future+BlockingAwait.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Futures/FutureResult.swift /Users/Rens/Development/RecoveryJournal/.build/checkouts/async.git-2335297525913451934/Sources/Async/Streams/ConnectionContext.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
| D |
/mnt/c/Users/Max Kelly/Documents/GitHub/Rust/crawler/target/debug/deps/libsmallvec-88b8356f3b52a647.rlib: /home/Max/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-0.1.8/lib.rs
/mnt/c/Users/Max Kelly/Documents/GitHub/Rust/crawler/target/debug/deps/smallvec-88b8356f3b52a647.d: /home/Max/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-0.1.8/lib.rs
/home/Max/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-0.1.8/lib.rs:
| D |
/Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/Objects-normal/x86_64/MaterialView.o : /Users/ales/Projects/DreamMachine/DreamMachine/MainVC.swift /Users/ales/Projects/DreamMachine/DreamMachine/AppDelegate.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/DreamMachine+CoreDataModel.swift /Users/ales/Projects/DreamMachine/DreamMachine/View/ItemCell.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Image+CoreDataProperties.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/ItemType+CoreDataProperties.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Store+CoreDataProperties.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Item+CoreDataProperties.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Image+CoreDataClass.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/ItemType+CoreDataClass.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Store+CoreDataClass.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Item+CoreDataClass.swift /Users/ales/Projects/DreamMachine/DreamMachine/View/MaterialView.swift /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreData.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/CoreData.framework/Headers/CoreData.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
/Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/Objects-normal/x86_64/MaterialView~partial.swiftmodule : /Users/ales/Projects/DreamMachine/DreamMachine/MainVC.swift /Users/ales/Projects/DreamMachine/DreamMachine/AppDelegate.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/DreamMachine+CoreDataModel.swift /Users/ales/Projects/DreamMachine/DreamMachine/View/ItemCell.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Image+CoreDataProperties.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/ItemType+CoreDataProperties.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Store+CoreDataProperties.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Item+CoreDataProperties.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Image+CoreDataClass.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/ItemType+CoreDataClass.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Store+CoreDataClass.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Item+CoreDataClass.swift /Users/ales/Projects/DreamMachine/DreamMachine/View/MaterialView.swift /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreData.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/CoreData.framework/Headers/CoreData.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
/Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/Objects-normal/x86_64/MaterialView~partial.swiftdoc : /Users/ales/Projects/DreamMachine/DreamMachine/MainVC.swift /Users/ales/Projects/DreamMachine/DreamMachine/AppDelegate.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/DreamMachine+CoreDataModel.swift /Users/ales/Projects/DreamMachine/DreamMachine/View/ItemCell.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Image+CoreDataProperties.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/ItemType+CoreDataProperties.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Store+CoreDataProperties.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Item+CoreDataProperties.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Image+CoreDataClass.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/ItemType+CoreDataClass.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Store+CoreDataClass.swift /Users/ales/Projects/DreamMachine/Build/Intermediates.noindex/DreamMachine.build/Debug-iphonesimulator/DreamMachine.build/DerivedSources/CoreDataGenerated/DreamMachine/Item+CoreDataClass.swift /Users/ales/Projects/DreamMachine/DreamMachine/View/MaterialView.swift /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreData.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/CoreData.framework/Headers/CoreData.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
| D |
//-------- Spell Commands --------
// SPL_DONTINVEST = 0; // Es können keine weiteren Manapunkte investiert werden. Erst durch CTRL loslassen geht der Spell ab
// SPL_RECEIVEINVEST = 1; // Wirkung durchgeführt, es können weitere Invest kommen, zB.bei Heal nach jedem Pöppel
// SPL_SENDCAST = 2; // Starte den Zauber-Effekt (wie CTRL loslassen), automatischer Abbruch
// SPL_SENDSTOP = 3; // Beende Zauber ohne Effekt
// SPL_NEXTLEVEL = 4; // setze den Spruch auf den nächsten Level
func int Spell_Logic_Trf_Meatbug(var int manaInvested)
{
//PrintDebugNpc (PD_MAGIC, "Spell_Logic_Transform");
if (manaInvested >= SPL_SENDCAST_TRF_MEATBUG)
{
var c_npc trans; trans = hlp_getnpc(transformer);
if(CmpNPC(self,trans))
{
//prin/t("I'Z A TRANSFORMER!!!");
GL_MD_TURNHERO2MEATBUG=TRUE;
WLD_SENDTRIGGER("MD_TRANSHERO_2_MEATBUG");
Npc_SetActiveSpellInfo(self, Meatbug);
return SPL_SENDCAST;
};
Npc_SetActiveSpellInfo(self, Meatbug);
return SPL_SENDCAST;
};
return SPL_NEXTLEVEL;
}; | D |
/Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/CDYelpFusionKit.build/Objects-normal/x86_64/CDYelpCenter.o : /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDImage.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpAutoCompleteResponse.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpSearchResponse.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpBusinessResponse.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpEventsResponse.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpReviewsResponse.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpTerm.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpOpen.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpRegion.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpLocation.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpUser.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpCenter.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpRouter.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDColor.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpError.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpHour.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpCoordinates.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpEnums.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpBusiness.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpConstants.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/URL+CDYelpFusionKit.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/UIImage+CDYelpFusionKit.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/String+CDYelpFusionKit.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/UIColor+CDYelpFusionKit.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/Parameters+CDYelpFusionKit.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpAPIClient.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpEvent.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpReview.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpCategory.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Modules/Alamofire.swiftmodule/x86_64.swiftmodule /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/ObjectMapper/ObjectMapper.framework/Modules/ObjectMapper.swiftmodule/x86_64.swiftmodule /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/AlamofireObjectMapper/AlamofireObjectMapper.framework/Modules/AlamofireObjectMapper.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/Target\ Support\ Files/Alamofire/Alamofire-umbrella.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/Target\ Support\ Files/ObjectMapper/ObjectMapper-umbrella.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/Target\ Support\ Files/AlamofireObjectMapper/AlamofireObjectMapper-umbrella.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/Target\ Support\ Files/CDYelpFusionKit/CDYelpFusionKit-umbrella.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-Swift.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/ObjectMapper/ObjectMapper.framework/Headers/ObjectMapper-Swift.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/AlamofireObjectMapper/AlamofireObjectMapper.framework/Headers/AlamofireObjectMapper-Swift.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/CDYelpFusionKit.build/unextended-module.modulemap /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/Alamofire.build/module.modulemap /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/ObjectMapper.build/module.modulemap /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/AlamofireObjectMapper.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
/Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/CDYelpFusionKit.build/Objects-normal/x86_64/CDYelpCenter~partial.swiftmodule : /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDImage.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpAutoCompleteResponse.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpSearchResponse.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpBusinessResponse.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpEventsResponse.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpReviewsResponse.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpTerm.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpOpen.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpRegion.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpLocation.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpUser.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpCenter.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpRouter.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDColor.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpError.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpHour.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpCoordinates.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpEnums.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpBusiness.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpConstants.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/URL+CDYelpFusionKit.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/UIImage+CDYelpFusionKit.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/String+CDYelpFusionKit.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/UIColor+CDYelpFusionKit.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/Parameters+CDYelpFusionKit.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpAPIClient.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpEvent.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpReview.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpCategory.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Modules/Alamofire.swiftmodule/x86_64.swiftmodule /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/ObjectMapper/ObjectMapper.framework/Modules/ObjectMapper.swiftmodule/x86_64.swiftmodule /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/AlamofireObjectMapper/AlamofireObjectMapper.framework/Modules/AlamofireObjectMapper.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/Target\ Support\ Files/Alamofire/Alamofire-umbrella.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/Target\ Support\ Files/ObjectMapper/ObjectMapper-umbrella.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/Target\ Support\ Files/AlamofireObjectMapper/AlamofireObjectMapper-umbrella.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/Target\ Support\ Files/CDYelpFusionKit/CDYelpFusionKit-umbrella.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-Swift.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/ObjectMapper/ObjectMapper.framework/Headers/ObjectMapper-Swift.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/AlamofireObjectMapper/AlamofireObjectMapper.framework/Headers/AlamofireObjectMapper-Swift.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/CDYelpFusionKit.build/unextended-module.modulemap /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/Alamofire.build/module.modulemap /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/ObjectMapper.build/module.modulemap /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/AlamofireObjectMapper.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
/Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/CDYelpFusionKit.build/Objects-normal/x86_64/CDYelpCenter~partial.swiftdoc : /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDImage.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpAutoCompleteResponse.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpSearchResponse.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpBusinessResponse.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpEventsResponse.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpReviewsResponse.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpTerm.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpOpen.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpRegion.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpLocation.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpUser.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpCenter.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpRouter.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDColor.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpError.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpHour.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpCoordinates.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpEnums.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpBusiness.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpConstants.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/URL+CDYelpFusionKit.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/UIImage+CDYelpFusionKit.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/String+CDYelpFusionKit.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/UIColor+CDYelpFusionKit.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/Parameters+CDYelpFusionKit.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpAPIClient.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpEvent.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpReview.swift /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/CDYelpFusionKit/Source/CDYelpCategory.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Modules/Alamofire.swiftmodule/x86_64.swiftmodule /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/ObjectMapper/ObjectMapper.framework/Modules/ObjectMapper.swiftmodule/x86_64.swiftmodule /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/AlamofireObjectMapper/AlamofireObjectMapper.framework/Modules/AlamofireObjectMapper.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/Target\ Support\ Files/Alamofire/Alamofire-umbrella.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/Target\ Support\ Files/ObjectMapper/ObjectMapper-umbrella.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/Target\ Support\ Files/AlamofireObjectMapper/AlamofireObjectMapper-umbrella.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Pods/Target\ Support\ Files/CDYelpFusionKit/CDYelpFusionKit-umbrella.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-Swift.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/ObjectMapper/ObjectMapper.framework/Headers/ObjectMapper-Swift.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Products/Debug-iphonesimulator/AlamofireObjectMapper/AlamofireObjectMapper.framework/Headers/AlamofireObjectMapper-Swift.h /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/CDYelpFusionKit.build/unextended-module.modulemap /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/Alamofire.build/module.modulemap /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/ObjectMapper.build/module.modulemap /Users/nikhilsridhar/Desktop/Shopp/Shopp/Build/Intermediates/Pods.build/Debug-iphonesimulator/AlamofireObjectMapper.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
| D |
import std.stdio;
void main() {
import std.range : sequence, take, dropOne;
auto r = sequence!("n*2").dropOne.take(10);
foreach(i; r) writeln(i);
} | D |
module install;
import std.process : execute;
import std.stdio : writeln;
import std.string : indexOf;
enum InstallError {
Fine,
DockerVersionDied,
DockerRun,
DockerRunTest,
DmdNotInstalled
}
InstallError install() {
auto dockerVersion = execute(["docker", "version"]);
if (dockerVersion.status != 0) {
writeln(dockerVersion.output);
return InstallError.DockerVersionDied;
}
auto dockerEcho = execute(["docker", "run", "ubuntu", "echo", "test"]);
if (dockerEcho.status != 0) {
writeln(dockerVersion.output);
return InstallError.DockerRun;
} else if (dockerEcho.output != "test\n") {
writeln(dockerVersion.output);
return InstallError.DockerRunTest;
}
auto dmdTest = execute(["rdmd", "test.d"]);
if (dmdTest.status != 0) {
writeln(dmdTest.output);
return InstallError.DmdNotInstalled;
}
return InstallError.Fine;
}
| D |
/Users/Rami/Desktop/TaskCompanyUSA/build/Pods.build/Debug-iphonesimulator/ObjectMapper.build/Objects-normal/x86_64/MapError.o : /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/FromJSON.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/ToJSON.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/Mappable.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/ImmutableMappable.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/TransformType.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/TransformOf.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/URLTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/DataTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/DateTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/ISO8601DateTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/EnumTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/NSDecimalNumberTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/DateFormatterTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/HexColorTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/CustomDateFormatTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/DictionaryTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/Map.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/Mapper.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/MapError.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/Operators.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/TransformOperators.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/EnumOperators.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/IntegerOperators.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/Rami/Desktop/TaskCompanyUSA/Pods/Target\ Support\ Files/ObjectMapper/ObjectMapper-umbrella.h /Users/Rami/Desktop/TaskCompanyUSA/build/Pods.build/Debug-iphonesimulator/ObjectMapper.build/unextended-module.modulemap
/Users/Rami/Desktop/TaskCompanyUSA/build/Pods.build/Debug-iphonesimulator/ObjectMapper.build/Objects-normal/x86_64/MapError~partial.swiftmodule : /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/FromJSON.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/ToJSON.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/Mappable.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/ImmutableMappable.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/TransformType.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/TransformOf.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/URLTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/DataTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/DateTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/ISO8601DateTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/EnumTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/NSDecimalNumberTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/DateFormatterTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/HexColorTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/CustomDateFormatTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/DictionaryTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/Map.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/Mapper.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/MapError.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/Operators.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/TransformOperators.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/EnumOperators.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/IntegerOperators.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/Rami/Desktop/TaskCompanyUSA/Pods/Target\ Support\ Files/ObjectMapper/ObjectMapper-umbrella.h /Users/Rami/Desktop/TaskCompanyUSA/build/Pods.build/Debug-iphonesimulator/ObjectMapper.build/unextended-module.modulemap
/Users/Rami/Desktop/TaskCompanyUSA/build/Pods.build/Debug-iphonesimulator/ObjectMapper.build/Objects-normal/x86_64/MapError~partial.swiftdoc : /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/FromJSON.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/ToJSON.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/Mappable.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/ImmutableMappable.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/TransformType.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/TransformOf.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/URLTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/DataTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/DateTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/ISO8601DateTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/EnumTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/NSDecimalNumberTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/DateFormatterTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/HexColorTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/CustomDateFormatTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/DictionaryTransform.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/Map.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/Mapper.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/MapError.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/Operators.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/TransformOperators.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/EnumOperators.swift /Users/Rami/Desktop/TaskCompanyUSA/Pods/ObjectMapper/Sources/IntegerOperators.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/Rami/Desktop/TaskCompanyUSA/Pods/Target\ Support\ Files/ObjectMapper/ObjectMapper-umbrella.h /Users/Rami/Desktop/TaskCompanyUSA/build/Pods.build/Debug-iphonesimulator/ObjectMapper.build/unextended-module.modulemap
| D |
/Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/derived_data/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.build/Objects-normal/x86_64/CombineLatest.o : /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Amb.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Deferred.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Deprecated.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Enumerated.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/Maybe.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Sequence.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Debounce.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Reduce.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Range.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Merge.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Take.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Cancelable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/Completable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/GroupedObservable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/Single.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/AsSingle.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Sample.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Throttle.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ObservableType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ConnectableObservableType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/SchedulerType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ObserverType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Create.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Generate.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DataStructures/Queue.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Reactive.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Materialize.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/AddRef.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DataStructures/Bag.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Using.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Debug.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Catch.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Date+Dispatch.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Switch.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/StartWith.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/Lock.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/RecursiveLock.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Sink.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Optional.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Scan.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/Platform.Darwin.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Do.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Map.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/CompactMap.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Zip.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Skip.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Producer.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Buffer.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Timer.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Filter.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Never.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/AnyObserver.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Error.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/Disposables.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Errors.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/ElementAt.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Concat.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Repeat.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/AtomicInt.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Event.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/TakeLast.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Multicast.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/First.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Just.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Timeout.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Window.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Rx.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/RxMutableBox.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/Platform.Linux.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/GroupBy.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Delay.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/ToArray.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Empty.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/Target\ Support\ Files/RxSwift/RxSwift-umbrella.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/mach-o/dyld.modulemap /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/derived_data/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/mach-o/compact_unwind_encoding.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/derived_data/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.build/Objects-normal/x86_64/CombineLatest~partial.swiftmodule : /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Amb.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Deferred.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Deprecated.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Enumerated.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/Maybe.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Sequence.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Debounce.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Reduce.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Range.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Merge.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Take.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Cancelable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/Completable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/GroupedObservable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/Single.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/AsSingle.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Sample.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Throttle.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ObservableType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ConnectableObservableType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/SchedulerType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ObserverType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Create.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Generate.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DataStructures/Queue.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Reactive.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Materialize.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/AddRef.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DataStructures/Bag.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Using.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Debug.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Catch.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Date+Dispatch.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Switch.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/StartWith.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/Lock.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/RecursiveLock.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Sink.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Optional.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Scan.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/Platform.Darwin.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Do.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Map.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/CompactMap.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Zip.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Skip.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Producer.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Buffer.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Timer.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Filter.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Never.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/AnyObserver.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Error.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/Disposables.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Errors.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/ElementAt.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Concat.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Repeat.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/AtomicInt.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Event.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/TakeLast.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Multicast.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/First.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Just.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Timeout.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Window.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Rx.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/RxMutableBox.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/Platform.Linux.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/GroupBy.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Delay.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/ToArray.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Empty.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/Target\ Support\ Files/RxSwift/RxSwift-umbrella.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/mach-o/dyld.modulemap /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/derived_data/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/mach-o/compact_unwind_encoding.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/derived_data/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.build/Objects-normal/x86_64/CombineLatest~partial.swiftdoc : /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Amb.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Deferred.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Deprecated.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Enumerated.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/Maybe.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Sequence.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Debounce.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Reduce.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Range.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Merge.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Take.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Cancelable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/Completable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/GroupedObservable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/Single.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/AsSingle.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Sample.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Throttle.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ObservableType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ConnectableObservableType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/SchedulerType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ObserverType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Create.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Generate.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DataStructures/Queue.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Reactive.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Materialize.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/AddRef.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DataStructures/Bag.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Using.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Debug.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Catch.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Date+Dispatch.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Switch.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/StartWith.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/Lock.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/RecursiveLock.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Sink.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Optional.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Scan.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/Platform.Darwin.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Do.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Map.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/CompactMap.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Zip.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Skip.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Producer.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Buffer.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Timer.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Filter.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Never.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/AnyObserver.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Error.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/Disposables.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Errors.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/ElementAt.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Concat.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Repeat.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/AtomicInt.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Event.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/TakeLast.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Multicast.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/First.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Just.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Timeout.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Window.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Rx.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/RxMutableBox.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/Platform.Linux.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/GroupBy.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Delay.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/ToArray.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Empty.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/Target\ Support\ Files/RxSwift/RxSwift-umbrella.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/mach-o/dyld.modulemap /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/derived_data/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/mach-o/compact_unwind_encoding.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/derived_data/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.build/Objects-normal/x86_64/CombineLatest~partial.swiftsourceinfo : /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Amb.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Deferred.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Deprecated.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Enumerated.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/Maybe.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Sequence.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Debounce.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Reduce.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Range.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Merge.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Take.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Cancelable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/Completable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/GroupedObservable.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/Single.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/AsSingle.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Sample.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Throttle.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ObservableType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ConnectableObservableType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/SchedulerType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ObserverType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Create.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Generate.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DataStructures/Queue.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Reactive.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Materialize.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/AddRef.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DataStructures/Bag.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Using.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Debug.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Catch.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Date+Dispatch.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Switch.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/StartWith.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/Lock.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/RecursiveLock.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Sink.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Optional.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Scan.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/Platform.Darwin.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Do.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Map.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/CompactMap.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Zip.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Skip.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Producer.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Buffer.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Timer.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Filter.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Never.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/AnyObserver.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Error.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Disposables/Disposables.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Errors.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/ElementAt.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Concat.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Repeat.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/AtomicInt.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Event.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/TakeLast.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Multicast.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/First.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Just.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Timeout.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Window.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Rx.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/RxMutableBox.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/Platform/Platform.Linux.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/GroupBy.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Delay.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/ToArray.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/Empty.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/Pods/Target\ Support\ Files/RxSwift/RxSwift-umbrella.h /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/mach-o/dyld.modulemap /Users/nalousnguyen/Documents/FinalSDK/CredifyIOS/CredifyCore/derived_data/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/mach-o/compact_unwind_encoding.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
| D |
import net;
debug import std.stdio;
/**
* A port on a network node to a network that responds to new messages on the Net.
* Messages are added to the NetPort's internal buffer.
* This base class can be implemented to add direct support to higher level
* protocols at the same level as IP rather than simply raw data.
* Note: In the observer patter, this is the observer.
*/
class NetPort {
private Net net;
// Used by derived classes.
final Net getNet() {
return net;
}
/// Called by a Net when being attached.
final void setNet(Net net) {
this.net = net;
}
/// Respond to messages from the Net.
abstract void update();
/// Indicates whether a read operation may be performed.
abstract bool hasData();
} | D |
void main() { runSolver(); }
void problem() {
auto N = scan!long;
auto solve() {
if (N <= 125) return 4;
if (N <= 211) return 6;
return 8;
}
outputForAtCoder(&solve);
}
// ----------------------------------------------
import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) { if (!m) return [[]]; if (s.empty) return []; return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
void outputForAtCoder(T)(T delegate() fn) {
static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
else static if (is(T == void)) fn();
else static if (is(T == string)) fn().writeln;
else static if (isInputRange!T) {
static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
else foreach(r; fn()) r.writeln;
}
else fn().writeln;
}
void runSolver() {
enum BORDER = "==================================";
debug { BORDER.writeln; while(true) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
else problem();
}
enum YESNO = [true: "Yes", false: "No"];
// -----------------------------------------------
| D |
/*
TEST_OUTPUT:
---
fail_compilation/fail3672.d(27): Error: read-modify-write operations are not allowed for `shared` variables. Use `core.atomic.atomicOp!"+="(*p, 1)` instead.
fail_compilation/fail3672.d(31): Error: none of the `opOpAssign` overloads of `SF` are callable for `*sfp` of type `shared(SF)`
---
*/
struct SF // should fail
{
void opOpAssign(string op, T)(T rhs)
{
}
}
struct SK // ok
{
void opOpAssign(string op, T)(T rhs) shared
{
}
}
void main()
{
shared int x;
auto p = &x;
*p += 1; // fail
shared SF sf;
auto sfp = &sf;
*sfp += 1; // fail
shared SK sk;
auto skp = &sk;
sk += 1; // ok
*skp += 1; // ok
}
| D |
PLONG PLAT ED95 KD LOMAGAGE HIMAGAGE SLAT SLONG RESULTNO DP DM WT ROCKTYPE
269.100006 76.3000031 4.30000019 66.6999969 0 3 32.4000015 70.9000015 404 2.9000001 5 0.43 sediments
255.5 73.5999985 0 0 0 2 32.2999992 70.6999969 831 0 0 0.645 sediments
247.5 75.9000015 0 0 0 3 32.5 70.5999985 830 0 0 0.43 sediments
295.700012 66.9000015 4 30.2000008 1 3 33.5 73.0999985 600 2.4000001 4.4000001 0.645 sediments
279.899994 75.8000031 4.30000019 826 1 14 32.7999992 72.5 1137 2.9000001 5 0.786538462 sediments
281.799988 77.5999985 5.5 53.5999985 1 5 33 73 1135 3.9000001 6.5999999 1 sediments
326.600006 57.4000015 4.69999981 380.799988 1 14 32.7999992 73.1999969 1136 3.0999999 5.4000001 0.786538462 sediments
267.5 72.1999969 2 13 1 13 28 82 6129 1.10000002 2.0999999 0.852083333 sediments, sandstones
| D |
/Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Intermediates/RWPickFlavor.build/Debug-iphonesimulator/RWPickFlavor.build/Objects-normal/x86_64/PickFlavorDataSource.o : /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/FlavorFactory.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/ScoopView.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/RGBAColorFromString.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/ScoopCell.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/Flavor.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/PickFlavorDataSource.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/PickFlavorViewController.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/IceCreamView.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/RWPickFlavor.h /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Intermediates/RWPickFlavor.build/Debug-iphonesimulator/RWPickFlavor.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Alamofire.framework/Modules/Alamofire.swiftmodule/x86_64.swiftmodule /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Alamofire.framework/Headers/Alamofire-Swift.h /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Alamofire.framework/Headers/Alamofire-umbrella.h /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Alamofire.framework/Modules/module.modulemap /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/MBProgressHUD.framework/Headers/MBProgressHUD.h /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/MBProgressHUD.framework/Headers/MBProgressHUD-umbrella.h /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/MBProgressHUD.framework/Modules/module.modulemap
/Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Intermediates/RWPickFlavor.build/Debug-iphonesimulator/RWPickFlavor.build/Objects-normal/x86_64/PickFlavorDataSource~partial.swiftmodule : /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/FlavorFactory.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/ScoopView.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/RGBAColorFromString.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/ScoopCell.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/Flavor.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/PickFlavorDataSource.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/PickFlavorViewController.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/IceCreamView.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/RWPickFlavor.h /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Intermediates/RWPickFlavor.build/Debug-iphonesimulator/RWPickFlavor.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Alamofire.framework/Modules/Alamofire.swiftmodule/x86_64.swiftmodule /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Alamofire.framework/Headers/Alamofire-Swift.h /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Alamofire.framework/Headers/Alamofire-umbrella.h /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Alamofire.framework/Modules/module.modulemap /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/MBProgressHUD.framework/Headers/MBProgressHUD.h /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/MBProgressHUD.framework/Headers/MBProgressHUD-umbrella.h /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/MBProgressHUD.framework/Modules/module.modulemap
/Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Intermediates/RWPickFlavor.build/Debug-iphonesimulator/RWPickFlavor.build/Objects-normal/x86_64/PickFlavorDataSource~partial.swiftdoc : /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/FlavorFactory.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/ScoopView.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/RGBAColorFromString.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/ScoopCell.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/Flavor.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/PickFlavorDataSource.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/PickFlavorViewController.swift /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/IceCreamView.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/Ntokozo/Documents/Libraries/RWPickFlavor/RWPickFlavor/RWPickFlavor.h /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Intermediates/RWPickFlavor.build/Debug-iphonesimulator/RWPickFlavor.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Alamofire.framework/Modules/Alamofire.swiftmodule/x86_64.swiftmodule /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Alamofire.framework/Headers/Alamofire-Swift.h /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Alamofire.framework/Headers/Alamofire-umbrella.h /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Alamofire.framework/Modules/module.modulemap /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/MBProgressHUD.framework/Headers/MBProgressHUD.h /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/MBProgressHUD.framework/Headers/MBProgressHUD-umbrella.h /Users/Ntokozo/Documents/Libraries/RWPickFlavor/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/MBProgressHUD.framework/Modules/module.modulemap
| D |
// written in the D programming language
module samples.Tumble;
import dchip.all;
import samples.ChipmunkDemo;
static cpSpace *space;
static cpBody *staticBody;
static void
update(int ticks)
{
enum int steps = 3;
enum cpFloat dt = 1.0f/60.0f/cast(cpFloat)steps;
for(int i=0; i<steps; i++){
cpSpaceStep(space, dt);
// Manually update the position of the static shape so that
// the box rotates.
cpBodyUpdatePosition(staticBody, dt);
// Because the box was added as a static shape and we moved it
// we need to manually rehash the static spatial hash.
cpSpaceReindexStatic(space);
}
}
static cpSpace *
init()
{
staticBody = cpBodyNew(INFINITY, INFINITY);
cpResetShapeIdCounter();
space = cpSpaceNew();
space.gravity = cpv(0, -600);
cpBody *_body;
cpShape *shape;
// Vertexes for the bricks
int num = 4;
cpVect verts[] = [
cpv(-30,-15),
cpv(-30, 15),
cpv( 30, 15),
cpv( 30,-15),
];
// Set up the static box.
cpVect a = cpv(-200, -200);
cpVect b = cpv(-200, 200);
cpVect c = cpv( 200, 200);
cpVect d = cpv( 200, -200);
shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, a, b, 0.0f));
shape.e = 1.0f; shape.u = 1.0f;
shape.layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, b, c, 0.0f));
shape.e = 1.0f; shape.u = 1.0f;
shape.layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, c, d, 0.0f));
shape.e = 1.0f; shape.u = 1.0f;
shape.layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, d, a, 0.0f));
shape.e = 1.0f; shape.u = 1.0f;
shape.layers = NOT_GRABABLE_MASK;
// Give the box a little spin.
// Because staticBody is never added to the space, we will need to
// update it ourselves. (see above).
// NOTE: Normally you would want to add the segments as normal and not static shapes.
// I'm just doing it to demonstrate the cpSpaceReindexStatic() function.
staticBody.w = 0.4f;
// Add the bricks.
for(int i=0; i<3; i++){
for(int j=0; j<7; j++){
_body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts.ptr, cpvzero)));
_body.p = cpv(i*60 - 150, j*30 - 150);
shape = cpSpaceAddShape(space, cpPolyShapeNew(_body, num, verts.ptr, cpvzero));
shape.e = 0.0f; shape.u = 0.7f;
}
}
return space;
}
static void
destroy()
{
cpBodyFree(staticBody);
ChipmunkDemoFreeSpaceChildren(space);
cpSpaceFree(space);
}
chipmunkDemo Tumble = {
"Tumble",
null,
&init,
&update,
&destroy,
};
| D |
/*
* This file is part of gtkD.
*
* gtkD is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* gtkD is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with gtkD; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// generated automatically - do not change
// find conversion definition on APILookup.txt
// implement new conversion functionalities on the wrap.utils pakage
/*
* Conversion parameters:
* inFile = GtkSeparator.html
* outPack = gtk
* outFile = Separator
* strct = GtkSeparator
* realStrct=
* ctorStrct=
* clss = Separator
* interf =
* class Code: Yes
* interface Code: No
* template for:
* extend =
* implements:
* - OrientableIF
* prefixes:
* - gtk_separator
* - gtk_
* omit structs:
* omit prefixes:
* omit code:
* omit signals:
* imports:
* - gtkD.gtk.OrientableIF
* - gtkD.gtk.OrientableT
* structWrap:
* module aliases:
* local aliases:
* overrides:
*/
module gtkD.gtk.Separator;
public import gtkD.gtkc.gtktypes;
private import gtkD.gtkc.gtk;
private import gtkD.glib.ConstructionException;
private import gtkD.gtk.OrientableIF;
private import gtkD.gtk.OrientableT;
private import gtkD.gtk.Widget;
/**
* Description
* The GtkSeparator widget is an abstract class, used only for deriving the
* subclasses GtkHSeparator and GtkVSeparator.
*/
public class Separator : Widget, OrientableIF
{
/** the main Gtk struct */
protected GtkSeparator* gtkSeparator;
public GtkSeparator* getSeparatorStruct()
{
return gtkSeparator;
}
/** the main Gtk struct as a void* */
protected override void* getStruct()
{
return cast(void*)gtkSeparator;
}
/**
* Sets our main struct and passes it to the parent class
*/
public this (GtkSeparator* gtkSeparator)
{
if(gtkSeparator is null)
{
this = null;
return;
}
//Check if there already is a D object for this gtk struct
void* ptr = getDObject(cast(GObject*)gtkSeparator);
if( ptr !is null )
{
this = cast(Separator)ptr;
return;
}
super(cast(GtkWidget*)gtkSeparator);
this.gtkSeparator = gtkSeparator;
}
// add the Orientable capabilities
mixin OrientableT!(GtkSeparator);
/**
*/
}
| D |
/home/pangpangguy/Ensimag/ProjetRust/learnrust/rustTDTP/TD3/sujetTD/Ex1_2/target/rls/debug/deps/sujet_TD-691e7853b66ceadc.rmeta: src/main.rs
/home/pangpangguy/Ensimag/ProjetRust/learnrust/rustTDTP/TD3/sujetTD/Ex1_2/target/rls/debug/deps/sujet_TD-691e7853b66ceadc.d: src/main.rs
src/main.rs:
| D |
import std.stdio, std.algorithm, std.typecons, std.container, std.array;
auto encode(alias eq, R)(Group!(eq, R) sf) /*pure nothrow @safe*/ {
auto heap = sf.map!(s => tuple(s[1], [tuple(s[0], "")]))
.array.heapify!q{b < a};
while (heap.length > 1) {
auto lo = heap.front; heap.removeFront;
auto hi = heap.front; heap.removeFront;
lo[1].each!((ref pair) => pair[1] = '0' ~ pair[1]);
hi[1].each!((ref pair) => pair[1] = '1' ~ pair[1]);
heap.insert(tuple(lo[0] + hi[0], lo[1] ~ hi[1]));
}
return heap.front[1].schwartzSort!q{ tuple(a[1].length, a[0]) };
}
void main() /*@safe*/ {
immutable s = "this is an example for huffman encoding"d;
foreach (const p; s.dup.sort().group.encode)
writefln("'%s' %s", p[]);
}
| D |
### BEGIN INIT INFO
# Provides: gluu-gateway
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start daemon at boot time
# Description: Enable service provided by daemon.
### END INIT INFO
SERVICE_NAME=gluu-gateway
PID_PATH_NAME=/var/run/gluu-gateway.pid
TMP_PID_PATH_NAME=/tmp/gluu-gateway.pid
BASEDIR=/opt/gluu-gateway/konga/
GLUU_GATEWAY_INIT_LOG=/var/log/gluu-gateway.log
get_pid() {
if [ -f $PID_PATH_NAME ]; then
PID_NUM=$(cat $PID_PATH_NAME)
echo "$PID_NUM"
else
OTHER_GATEWAY_PID="`ps -eaf|grep -i node|grep -v grep|grep -i 'app.js'|awk '{print $2}'`"
###For one more possible bug, find and kill oxd
if [ "x$OTHER_GATEWAY_PID" != "x" ]; then
echo "$OTHER_GATEWAY_PID"
fi
fi
}
do_start () {
PID_NUM=`get_pid`
if [ "x$PID_NUM" = "x" ]; then
echo "Starting $SERVICE_NAME ..."
cd $BASEDIR
nohup node --harmony app.js >> $GLUU_GATEWAY_INIT_LOG 2>&1 &
echo $! > $TMP_PID_PATH_NAME
START_STATUS=`tail -n 12 $GLUU_GATEWAY_INIT_LOG|grep -i 'To see your app, visit'`
ERROR_STATUS=`tail -n 10 $GLUU_GATEWAY_INIT_LOG|grep -i 'Error'`
if [ "x$START_STATUS" = "x" ]; then
###If by chance log file doesn't provide necessary string, sleep another 10 seconds and check again PID of process
sleep 5
PID_NUM=`get_pid`
if [ "x$PID_NUM" = "x" ]; then
### Since error occurred, we should remove the PID file at this point itself.
echo "Some error encountered..."
echo "See log below: "
echo ""
echo "$ERROR_STATUS"
echo ""
echo "For details please check $GLUU_GATEWAY_INIT_LOG ."
echo "Exiting..."
exit 255
fi
fi
mv $TMP_PID_PATH_NAME $PID_PATH_NAME
PID_NUM=$(cat $PID_PATH_NAME)
else
echo "$SERVICE_NAME is already running ..."
fi
echo "PID: [$PID_NUM]"
}
do_stop () {
PID_NUM=`get_pid`
if [ "x$PID_NUM" != "x" ]; then
echo "$SERVICE_NAME stoping ..."
kill -s 9 $PID_NUM;
rm -f $PID_PATH_NAME
else
echo "$SERVICE_NAME is not running ..."
fi
}
case $1 in
start)
do_start
;;
stop)
do_stop
;;
restart)
do_stop
do_start
;;
status)
if [ -f $PID_PATH_NAME ]; then
echo "$SERVICE_NAME is running ...";
PID_NUM=$(cat $PID_PATH_NAME)
echo "PID: [$PID_NUM]"
else
echo "$SERVICE_NAME is not running ..."
fi
;;
*)
echo "Usage: $0 {start|stop|status|restart}"
RETVAL=2
;;
esac
| D |
/*
DIrrlicht - D Bindings for Irrlicht Engine
Copyright (C) 2014- Danyal Zia (catofdanyal@yahoo.com)
This software is provided 'as-is', without any express or
implied warranty. In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
*/
module dirrlicht.io.attributeexchangingobject;
import dirrlicht.io.attributes;
import std.string : toStringz;
/// Enumeration flags passed through SAttributeReadWriteOptions to the IAttributeExchangingObject object
enum AttributeReadWriteFlag {
/// Serialization/Deserializion is done for an xml file
ForFile = 0x00000001,
/// Serialization/Deserializion is done for an editor property box
ForEditor = 0x00000002,
/// When writing filenames, relative paths should be used
UseRelativePaths = 0x00000004
}
/// struct holding data describing options
struct AttributeReadWriteOptions {
/// Combination of E_ATTRIBUTE_READ_WRITE_FLAGS or other, custom ones
int Flags;
/// Optional filename
string Filename;
//@property irr_SAttributeReadWriteOptions ptr() {
//irr_SAttributeReadWriteOptions temp;
//temp.Flags = Flags;
//temp.Filename = Filename.toStringz;
//return temp;
//}
}
/// An object which is able to serialize and deserialize its attributes into an attributes object
class AttributeExchangingObject {
public:
/// Writes attributes of the object.
/** Implement this to expose the attributes of your scene node animator for
scripting languages, editors, debuggers or xml serialization purposes.
*/
void serializeAttributes(out Attributes att, AttributeReadWriteOptions options=AttributeReadWriteOptions(0, null)) {}
/// Reads attributes of the object.
/** Implement this to set the attributes of your scene node animator for
scripting languages, editors, debuggers or xml deserialization purposes.
*/
void deserializeAttributes(in Attributes att, AttributeReadWriteOptions options=AttributeReadWriteOptions(0, null)) {}
}
package extern (C):
struct irr_SAttributeReadWriteOptions {
int Flags;
const char* Filename;
}
| D |
module UnrealScript.Engine.PrefabInstance;
import ScriptClasses;
import UnrealScript.Helpers;
import UnrealScript.Engine.Prefab;
import UnrealScript.Engine.Actor;
import UnrealScript.Core.UObject;
import UnrealScript.Engine.PrefabSequence;
extern(C++) interface PrefabInstance : Actor
{
public extern(D):
private static __gshared ScriptClass mStaticClass;
@property final static ScriptClass StaticClass() { mixin(MGSCC("Class Engine.PrefabInstance")); }
private static __gshared PrefabInstance mDefaultProperties;
@property final static PrefabInstance DefaultProperties() { mixin(MGDPC("PrefabInstance", "PrefabInstance Engine.Default__PrefabInstance")); }
@property final auto ref
{
ScriptArray!(ubyte) PI_Bytes() { mixin(MGPC("ScriptArray!(ubyte)", 556)); }
ScriptArray!(UObject) PI_CompleteObjects() { mixin(MGPC("ScriptArray!(UObject)", 568)); }
ScriptArray!(UObject) PI_ReferencedObjects() { mixin(MGPC("ScriptArray!(UObject)", 580)); }
ScriptArray!(ScriptString) PI_SavedNames() { mixin(MGPC("ScriptArray!(ScriptString)", 592)); }
// ERROR: Unsupported object class 'MapProperty' for the property named 'PI_ObjectMap'!
int PI_LicenseePackageVersion() { mixin(MGPC("int", 552)); }
int PI_PackageVersion() { mixin(MGPC("int", 548)); }
PrefabSequence SequenceInstance() { mixin(MGPC("PrefabSequence", 544)); }
// ERROR: Unsupported object class 'MapProperty' for the property named 'ArchetypeToInstanceMap'!
int TemplateVersion() { mixin(MGPC("int", 480)); }
Prefab TemplatePrefab() { mixin(MGPC("Prefab", 476)); }
}
}
| D |
import hmm;
int main() {
gnaa();
return 0;
}
| D |
// Written in the D programming language.
/**
* Templates with which to extract information about types and symbols at
* compile time.
*
* Macros:
* WIKI = Phobos/StdTraits
*
* Copyright: Copyright Digital Mars 2005 - 2009.
* License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
* Authors: $(WEB digitalmars.com, Walter Bright),
* Tomasz Stachowiak ($(D isExpressionTuple)),
* $(WEB erdani.org, Andrei Alexandrescu),
* Shin Fujishiro,
* $(WEB octarineparrot.com, Robert Clipsham)
* Source: $(PHOBOSSRC std/_traits.d)
*/
/* Copyright Digital Mars 2005 - 2009.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
module std.traits;
import std.algorithm;
import std.typetuple;
import std.typecons;
import core.vararg;
///////////////////////////////////////////////////////////////////////////////
// Functions
///////////////////////////////////////////////////////////////////////////////
// Petit demangler
// (this or similar thing will eventually go to std.demangle if necessary
// ctfe stuffs are available)
private
{
struct Demangle(T)
{
T value; // extracted information
string rest;
}
/* Demangles mstr as the storage class part of Argument. */
Demangle!uint demangleParameterStorageClass(string mstr)
{
uint pstc = 0; // parameter storage class
// Argument --> Argument2 | M Argument2
if (mstr.length > 0 && mstr[0] == 'M')
{
pstc |= ParameterStorageClass.scope_;
mstr = mstr[1 .. $];
}
// Argument2 --> Type | J Type | K Type | L Type
ParameterStorageClass stc2;
switch (mstr.length ? mstr[0] : char.init)
{
case 'J': stc2 = ParameterStorageClass.out_; break;
case 'K': stc2 = ParameterStorageClass.ref_; break;
case 'L': stc2 = ParameterStorageClass.lazy_; break;
default : break;
}
if (stc2 != ParameterStorageClass.init)
{
pstc |= stc2;
mstr = mstr[1 .. $];
}
return Demangle!uint(pstc, mstr);
}
/* Demangles mstr as FuncAttrs. */
Demangle!uint demangleFunctionAttributes(string mstr)
{
enum LOOKUP_ATTRIBUTE =
[
'a': FunctionAttribute.pure_,
'b': FunctionAttribute.nothrow_,
'c': FunctionAttribute.ref_,
'd': FunctionAttribute.property,
'e': FunctionAttribute.trusted,
'f': FunctionAttribute.safe
];
uint atts = 0;
// FuncAttrs --> FuncAttr | FuncAttr FuncAttrs
// FuncAttr --> empty | Na | Nb | Nc | Nd | Ne | Nf
while (mstr.length >= 2 && mstr[0] == 'N')
{
if (FunctionAttribute att = LOOKUP_ATTRIBUTE[ mstr[1] ])
{
atts |= att;
mstr = mstr[2 .. $];
}
else assert(0);
}
return Demangle!uint(atts, mstr);
}
}
/**
* Get the full package name for the given symbol.
* Example:
* ---
* import std.traits;
* static assert(packageName!(packageName) == "std");
* ---
*/
template packageName(alias T)
{
static if (T.stringof.length >= 9 && T.stringof[0..8] == "package ")
{
static if (is(typeof(__traits(parent, T))))
{
enum packageName = packageName!(__traits(parent, T)) ~ '.' ~ T.stringof[8..$];
}
else
{
enum packageName = T.stringof[8..$];
}
}
else static if (is(typeof(__traits(parent, T))))
alias packageName!(__traits(parent, T)) packageName;
else
static assert(false, T.stringof ~ " has no parent");
}
unittest
{
import etc.c.curl;
static assert(packageName!(packageName) == "std");
static assert(packageName!(curl_httppost) == "etc.c");
}
/**
* Get the module name (including package) for the given symbol.
* Example:
* ---
* import std.traits;
* static assert(moduleName!(moduleName) == "std.traits");
* ---
*/
template moduleName(alias T)
{
static if (T.stringof.length >= 9)
static assert(T.stringof[0..8] != "package ", "cannot get the module name for a package");
static if (T.stringof.length >= 8 && T.stringof[0..7] == "module ")
enum moduleName = packageName!(T) ~ '.' ~ T.stringof[7..$];
else
alias moduleName!(__traits(parent, T)) moduleName;
}
unittest
{
import etc.c.curl;
static assert(moduleName!(moduleName) == "std.traits");
static assert(moduleName!(curl_httppost) == "etc.c.curl");
}
/**
* Get the fully qualified name of a symbol.
* Example:
* ---
* import std.traits;
* static assert(fullyQualifiedName!(fullyQualifiedName) == "std.traits.fullyQualifiedName");
* ---
*/
template fullyQualifiedName(alias T)
{
static if (is(typeof(__traits(parent, T))))
{
static if (T.stringof.length >= 9 && T.stringof[0..8] == "package ")
{
enum fullyQualifiedName = fullyQualifiedName!(__traits(parent, T)) ~ '.' ~ T.stringof[8..$];
}
else static if (T.stringof.length >= 8 && T.stringof[0..7] == "module ")
{
enum fullyQualifiedName = fullyQualifiedName!(__traits(parent, T)) ~ '.' ~ T.stringof[7..$];
}
else static if (T.stringof.countUntil('(') == -1)
{
enum fullyQualifiedName = fullyQualifiedName!(__traits(parent, T)) ~ '.' ~ T.stringof;
}
else
enum fullyQualifiedName = fullyQualifiedName!(__traits(parent, T)) ~ '.' ~ T.stringof[0..T.stringof.countUntil('(')];
}
else
{
static if (T.stringof.length >= 9 && T.stringof[0..8] == "package ")
{
enum fullyQualifiedName = T.stringof[8..$];
}
else static if (T.stringof.length >= 8 && T.stringof[0..7] == "module ")
{
enum fullyQualifiedName = T.stringof[7..$];
}
else static if (T.stringof.countUntil('(') == -1)
{
enum fullyQualifiedName = T.stringof;
}
else
enum fullyQualifiedName = T.stringof[0..T.stringof.countUntil('(')];
}
}
unittest
{
import etc.c.curl;
static assert(fullyQualifiedName!(fullyQualifiedName) == "std.traits.fullyQualifiedName");
static assert(fullyQualifiedName!(curl_httppost) == "etc.c.curl.curl_httppost");
}
/***
* Get the type of the return value from a function,
* a pointer to function, a delegate, a struct
* with an opCall, a pointer to a struct with an opCall,
* or a class with an opCall.
* Example:
* ---
* import std.traits;
* int foo();
* ReturnType!(foo) x; // x is declared as int
* ---
*/
template ReturnType(func...)
if (func.length == 1 && isCallable!(func))
{
static if (is(FunctionTypeOf!(func) R == return))
alias R ReturnType;
else
static assert(0, "argument has no return type");
}
unittest
{
struct G
{
int opCall (int i) { return 1;}
}
alias ReturnType!(G) ShouldBeInt;
static assert(is(ShouldBeInt == int));
G g;
static assert(is(ReturnType!(g) == int));
G* p;
alias ReturnType!(p) pg;
static assert(is(pg == int));
class C
{
int opCall (int i) { return 1;}
}
static assert(is(ReturnType!(C) == int));
C c;
static assert(is(ReturnType!(c) == int));
class Test
{
int prop() @property { return 0; }
}
alias ReturnType!(Test.prop) R_Test_prop;
static assert(is(R_Test_prop == int));
alias ReturnType!((int a) { return a; }) R_dglit;
static assert(is(R_dglit == int));
}
/***
Get, as a tuple, the types of the parameters to a function, a pointer
to function, a delegate, a struct with an $(D opCall), a pointer to a
struct with an $(D opCall), or a class with an $(D opCall).
Example:
---
import std.traits;
int foo(int, long);
void bar(ParameterTypeTuple!(foo)); // declares void bar(int, long);
void abc(ParameterTypeTuple!(foo)[1]); // declares void abc(long);
---
*/
template ParameterTypeTuple(func...)
if (func.length == 1 && isCallable!(func))
{
static if (is(FunctionTypeOf!(func) P == function))
alias P ParameterTypeTuple;
else
static assert(0, "argument has no parameters");
}
unittest
{
int foo(int i, bool b) { return 0; }
static assert (is(ParameterTypeTuple!(foo) == TypeTuple!(int, bool)));
static assert (is(ParameterTypeTuple!(typeof(&foo))
== TypeTuple!(int, bool)));
struct S { real opCall(real r, int i) { return 0.0; } }
S s;
static assert (is(ParameterTypeTuple!(S) == TypeTuple!(real, int)));
static assert (is(ParameterTypeTuple!(S*) == TypeTuple!(real, int)));
static assert (is(ParameterTypeTuple!(s) == TypeTuple!(real, int)));
class Test
{
int prop() @property { return 0; }
}
alias ParameterTypeTuple!(Test.prop) P_Test_prop;
static assert(P_Test_prop.length == 0);
alias ParameterTypeTuple!((int a){}) P_dglit;
static assert(P_dglit.length == 1);
static assert(is(P_dglit[0] == int));
}
/**
Returns a tuple consisting of the storage classes of the parameters of a
function $(D func).
Example:
--------------------
alias ParameterStorageClass STC; // shorten the enum name
void func(ref int ctx, out real result, real param)
{
}
alias ParameterStorageClassTuple!(func) pstc;
static assert(pstc.length == 3); // three parameters
static assert(pstc[0] == STC.ref_);
static assert(pstc[1] == STC.out_);
static assert(pstc[2] == STC.none);
--------------------
*/
enum ParameterStorageClass : uint
{
/**
* These flags can be bitwise OR-ed together to represent complex storage
* class.
*/
none = 0, /// ditto
scope_ = 0b000_1, /// ditto
out_ = 0b001_0, /// ditto
ref_ = 0b010_0, /// ditto
lazy_ = 0b100_0, /// ditto
}
/// ditto
template ParameterStorageClassTuple(func...)
if (func.length == 1 && isCallable!(func))
{
alias ParameterStorageClassTupleImpl!(Unqual!(FunctionTypeOf!(func))).Result
ParameterStorageClassTuple;
}
private template ParameterStorageClassTupleImpl(Func)
{
/*
* TypeFuncion:
* CallConvention FuncAttrs Arguments ArgClose Type
*/
alias ParameterTypeTuple!(Func) Params;
// chop off CallConvention and FuncAttrs
enum margs = demangleFunctionAttributes(mangledName!(Func)[1 .. $]).rest;
// demangle Arguments and store parameter storage classes in a tuple
template demangleNextParameter(string margs, size_t i = 0)
{
static if (i < Params.length)
{
enum demang = demangleParameterStorageClass(margs);
enum skip = mangledName!(Params[i]).length; // for bypassing Type
enum rest = demang.rest;
alias TypeTuple!(
demang.value + 0, // workaround: "not evaluatable at ..."
demangleNextParameter!(rest[skip .. $], i + 1).Result
) Result;
}
else // went thru all the parameters
{
alias TypeTuple!() Result;
}
}
alias demangleNextParameter!(margs).Result Result;
}
unittest
{
alias ParameterStorageClass STC;
void noparam() {}
static assert(ParameterStorageClassTuple!(noparam).length == 0);
void test(scope int, ref int, out int, lazy int, int) { }
alias ParameterStorageClassTuple!(test) test_pstc;
static assert(test_pstc.length == 5);
static assert(test_pstc[0] == STC.scope_);
static assert(test_pstc[1] == STC.ref_);
static assert(test_pstc[2] == STC.out_);
static assert(test_pstc[3] == STC.lazy_);
static assert(test_pstc[4] == STC.none);
interface Test
{
void test_const(int) const;
void test_sharedconst(int) shared const;
}
Test testi;
alias ParameterStorageClassTuple!(Test.test_const) test_const_pstc;
static assert(test_const_pstc.length == 1);
static assert(test_const_pstc[0] == STC.none);
alias ParameterStorageClassTuple!(testi.test_sharedconst) test_sharedconst_pstc;
static assert(test_sharedconst_pstc.length == 1);
static assert(test_sharedconst_pstc[0] == STC.none);
alias ParameterStorageClassTuple!((ref int a) {}) dglit_pstc;
static assert(dglit_pstc.length == 1);
static assert(dglit_pstc[0] == STC.ref_);
}
/**
Returns the attributes attached to a function $(D func).
Example:
--------------------
alias FunctionAttribute FA; // shorten the enum name
real func(real x) pure nothrow @safe
{
return x;
}
static assert(functionAttributes!(func) & FA.pure_);
static assert(functionAttributes!(func) & FA.safe);
static assert(!(functionAttributes!(func) & FA.trusted)); // not @trusted
--------------------
*/
enum FunctionAttribute : uint
{
/**
* These flags can be bitwise OR-ed together to represent complex attribute.
*/
none = 0, /// ditto
pure_ = 0b00000001, /// ditto
nothrow_ = 0b00000010, /// ditto
ref_ = 0b00000100, /// ditto
property = 0b00001000, /// ditto
trusted = 0b00010000, /// ditto
safe = 0b00100000, /// ditto
}
/// ditto
template functionAttributes(func...)
if (func.length == 1 && isCallable!(func))
{
enum uint functionAttributes = demangleFunctionAttributes(
mangledName!(Unqual!(FunctionTypeOf!(func)))[1 .. $] ).value;
}
unittest
{
alias FunctionAttribute FA;
interface Set
{
int pureF() pure;
int nothrowF() nothrow;
ref int refF();
int propertyF() @property;
int trustedF() @trusted;
int safeF() @safe;
}
static assert(functionAttributes!(Set.pureF) == FA.pure_);
static assert(functionAttributes!(Set.nothrowF) == FA.nothrow_);
static assert(functionAttributes!(Set.refF) == FA.ref_);
static assert(functionAttributes!(Set.propertyF) == FA.property);
static assert(functionAttributes!(Set.trustedF) == FA.trusted);
static assert(functionAttributes!(Set.safeF) == FA.safe);
static assert(!(functionAttributes!(Set.safeF) & FA.trusted));
int pure_nothrow() pure nothrow { return 0; }
static assert(functionAttributes!(pure_nothrow) == (FA.pure_ | FA.nothrow_));
static ref int static_ref_property() @property { return *(new int); }
static assert(functionAttributes!(static_ref_property) == (FA.ref_ | FA.property));
ref int ref_property() @property { return *(new int); }
static assert(functionAttributes!(ref_property) == (FA.ref_ | FA.property));
void safe_nothrow() @safe nothrow { }
static assert(functionAttributes!(safe_nothrow) == (FA.safe | FA.nothrow_));
interface Test2
{
int pure_const() pure const;
int pure_sharedconst() pure shared const;
}
static assert(functionAttributes!(Test2.pure_const) == FA.pure_);
static assert(functionAttributes!(Test2.pure_sharedconst) == FA.pure_);
static assert(functionAttributes!((int a) {}) == (FA.safe | FA.pure_ | FA.nothrow_));
}
private @safe void dummySafeFunc(alias func)()
{
alias ParameterTypeTuple!func Params;
static if (Params.length)
{
Params args;
func(args);
}
else
{
func();
}
}
/**
Checks the func that is @safe or @trusted
Example:
--------------------
@system int add(int a, int b) {return a+b;}
@safe int sub(int a, int b) {return a-b;}
@trusted int mul(int a, int b) {return a*b;}
bool a = isSafe!(add);
assert(a == false);
bool b = isSafe!(sub);
assert(b == true);
bool c = isSafe!(mul);
assert(c == true);
--------------------
*/
template isSafe(alias func)
{
static if (is(typeof(func) == function))
{
enum isSafe = (functionAttributes!(func) == FunctionAttribute.safe
|| functionAttributes!(func) == FunctionAttribute.trusted);
}
else
{
enum isSafe = is(typeof({dummySafeFunc!func();}()));
}
}
@safe
unittest
{
interface Set
{
int systemF() @system;
int trustedF() @trusted;
int safeF() @safe;
}
static assert(isSafe!((int a){}));
static assert(isSafe!(Set.safeF));
static assert(isSafe!(Set.trustedF));
static assert(!isSafe!(Set.systemF));
}
/**
Checks the all functions are @safe or @trusted
Example:
--------------------
@system int add(int a, int b) {return a+b;}
@safe int sub(int a, int b) {return a-b;}
@trusted int mul(int a, int b) {return a*b;}
bool a = areAllSafe!(add, sub);
assert(a == false);
bool b = areAllSafe!(sub, mul);
assert(b == true);
--------------------
*/
template areAllSafe(funcs...)
if (funcs.length > 0)
{
static if (funcs.length == 1)
{
enum areAllSafe = isSafe!(funcs[0]);
}
else static if (isSafe!(funcs[0]))
{
enum areAllSafe = areAllSafe!(funcs[1..$]);
}
else
{
enum areAllSafe = false;
}
}
@safe
unittest
{
interface Set
{
int systemF() @system;
int trustedF() @trusted;
int safeF() @safe;
}
static assert(areAllSafe!((int a){}, Set.safeF));
static assert(!areAllSafe!(Set.trustedF, Set.systemF));
}
/**
Checks the func that is @system
Example:
--------------------
@system int add(int a, int b) {return a+b;}
@safe int sub(int a, int b) {return a-b;}
@trusted int mul(int a, int b) {return a*b;}
bool a = isUnsafe!(add);
assert(a == true);
bool b = isUnsafe!(sub);
assert(b == false);
bool c = isUnsafe!(mul);
assert(c == false);
--------------------
*/
template isUnsafe(alias func)
{
enum isUnsafe = !isSafe!func;
}
@safe
unittest
{
interface Set
{
int systemF() @system;
int trustedF() @trusted;
int safeF() @safe;
}
static assert(!isUnsafe!((int a){}));
static assert(!isUnsafe!(Set.safeF));
static assert(!isUnsafe!(Set.trustedF));
static assert(isUnsafe!(Set.systemF));
}
/**
Returns the calling convention of function as a string.
Example:
--------------------
string a = functionLinkage!(writeln!(string, int));
assert(a == "D"); // extern(D)
auto fp = &printf;
string b = functionLinkage!(fp);
assert(b == "C"); // extern(C)
--------------------
*/
template functionLinkage(func...)
if (func.length == 1 && isCallable!(func))
{
enum string functionLinkage =
LOOKUP_LINKAGE[ mangledName!(Unqual!(FunctionTypeOf!(func)))[0] ];
}
private enum LOOKUP_LINKAGE =
[
'F': "D",
'U': "C",
'W': "Windows",
'V': "Pascal",
'R': "C++"
];
unittest
{
extern(D) void Dfunc() {}
extern(C) void Cfunc() {}
static assert(functionLinkage!(Dfunc) == "D");
static assert(functionLinkage!(Cfunc) == "C");
interface Test
{
void const_func() const;
void sharedconst_func() shared const;
}
static assert(functionLinkage!(Test.const_func) == "D");
static assert(functionLinkage!(Test.sharedconst_func) == "D");
static assert(functionLinkage!((int a){}) == "D");
}
/**
Determines what kind of variadic parameters function has.
Example:
--------------------
void func() {}
static assert(variadicFunctionStyle!(func) == Variadic.no);
extern(C) int printf(in char*, ...);
static assert(variadicFunctionStyle!(printf) == Variadic.c);
--------------------
*/
enum Variadic
{
no, /// Function is not variadic.
c, /// Function is a _C-style variadic function.
/// Function is a _D-style variadic function, which uses
d, /// __argptr and __arguments.
typesafe, /// Function is a typesafe variadic function.
}
/// ditto
template variadicFunctionStyle(func...)
if (func.length == 1 && isCallable!(func))
{
enum Variadic variadicFunctionStyle =
determineVariadicity!( Unqual!(FunctionTypeOf!(func)) )();
}
private Variadic determineVariadicity(Func)()
{
// TypeFuncion --> CallConvention FuncAttrs Arguments ArgClose Type
immutable callconv = functionLinkage!(Func);
immutable mfunc = mangledName!(Func);
immutable mtype = mangledName!(ReturnType!(Func));
debug assert(mfunc[$ - mtype.length .. $] == mtype, mfunc ~ "|" ~ mtype);
immutable argclose = mfunc[$ - mtype.length - 1];
final switch (argclose)
{
case 'X': return Variadic.typesafe;
case 'Y': return (callconv == "C") ? Variadic.c : Variadic.d;
case 'Z': return Variadic.no;
}
}
unittest
{
extern(D) void novar() {}
extern(C) void cstyle(int, ...) {}
extern(D) void dstyle(...) {}
extern(D) void typesafe(int[]...) {}
static assert(variadicFunctionStyle!(novar) == Variadic.no);
static assert(variadicFunctionStyle!(cstyle) == Variadic.c);
static assert(variadicFunctionStyle!(dstyle) == Variadic.d);
static assert(variadicFunctionStyle!(typesafe) == Variadic.typesafe);
static assert(variadicFunctionStyle!((int[] a...) {}) == Variadic.typesafe);
}
/**
Get the function type from a callable object $(D func).
Using builtin $(D typeof) on a property function yields the types of the
property value, not of the property function itself. Still,
$(D FunctionTypeOf) is able to obtain function types of properties.
--------------------
class C {
int value() @property;
}
static assert(is( typeof(C.value) == int ));
static assert(is( FunctionTypeOf!(C.value) == function ));
--------------------
Note:
Do not confuse function types with function pointer types; function types are
usually used for compile-time reflection purposes.
*/
template FunctionTypeOf(func...)
if (func.length == 1 && isCallable!(func))
{
static if (is(typeof(& func[0]) Fsym : Fsym*) && is(Fsym == function) || is(typeof(& func[0]) Fsym == delegate))
{
alias Fsym FunctionTypeOf; // HIT: (nested) function symbol
}
else static if (is(typeof(& func[0].opCall) Fobj == delegate))
{
alias Fobj FunctionTypeOf; // HIT: callable object
}
else static if (is(typeof(& func[0].opCall) Ftyp : Ftyp*) && is(Ftyp == function))
{
alias Ftyp FunctionTypeOf; // HIT: callable type
}
else static if (is(func[0] T) || is(typeof(func[0]) T))
{
static if (is(T == function))
alias T FunctionTypeOf; // HIT: function
else static if (is(T Fptr : Fptr*) && is(Fptr == function))
alias Fptr FunctionTypeOf; // HIT: function pointer
else static if (is(T Fdlg == delegate))
alias Fdlg FunctionTypeOf; // HIT: delegate
else static assert(0);
}
else static assert(0);
}
unittest
{
int test(int a) { return 0; }
int propGet() @property { return 0; }
int propSet(int a) @property { return 0; }
int function(int) test_fp;
int delegate(int) test_dg;
static assert(is( typeof(test) == FunctionTypeOf!(typeof(test)) ));
static assert(is( typeof(test) == FunctionTypeOf!(test) ));
static assert(is( typeof(test) == FunctionTypeOf!(test_fp) ));
static assert(is( typeof(test) == FunctionTypeOf!(test_dg) ));
alias int GetterType() @property;
alias int SetterType(int) @property;
static assert(is( FunctionTypeOf!(propGet) == GetterType ));
static assert(is( FunctionTypeOf!(propSet) == SetterType ));
interface Prop { int prop() @property; }
Prop prop;
static assert(is( FunctionTypeOf!(Prop.prop) == GetterType ));
static assert(is( FunctionTypeOf!(prop.prop) == GetterType ));
class Callable { int opCall(int) { return 0; } }
auto call = new Callable;
static assert(is( FunctionTypeOf!(call) == typeof(test) ));
struct StaticCallable { static int opCall(int) { return 0; } }
StaticCallable stcall_val;
StaticCallable* stcall_ptr;
static assert(is( FunctionTypeOf!(stcall_val) == typeof(test) ));
static assert(is( FunctionTypeOf!(stcall_ptr) == typeof(test) ));
interface Overloads {
void test(string);
real test(real);
int test();
int test() @property;
}
alias TypeTuple!(__traits(getVirtualFunctions, Overloads, "test")) ov;
alias FunctionTypeOf!(ov[0]) F_ov0;
alias FunctionTypeOf!(ov[1]) F_ov1;
alias FunctionTypeOf!(ov[2]) F_ov2;
alias FunctionTypeOf!(ov[3]) F_ov3;
static assert(is(F_ov0* == void function(string)));
static assert(is(F_ov1* == real function(real)));
static assert(is(F_ov2* == int function()));
static assert(is(F_ov3* == int function() @property));
alias FunctionTypeOf!((int a){ return a; }) F_dglit;
static assert(is(F_dglit* : int function(int)));
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// Aggregate Types
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
/***
* Get the types of the fields of a struct or class.
* This consists of the fields that take up memory space,
* excluding the hidden fields like the virtual function
* table pointer.
*/
template FieldTypeTuple(S)
{
static if (is(S == struct) || is(S == class) || is(S == union))
alias typeof(S.tupleof) FieldTypeTuple;
else
alias TypeTuple!(S) FieldTypeTuple;
//static assert(0, "argument is not struct or class");
}
// // FieldOffsetsTuple
// private template FieldOffsetsTupleImpl(size_t n, T...)
// {
// static if (T.length == 0)
// {
// alias TypeTuple!() Result;
// }
// else
// {
// //private alias FieldTypeTuple!(T[0]) Types;
// private enum size_t myOffset =
// ((n + T[0].alignof - 1) / T[0].alignof) * T[0].alignof;
// static if (is(T[0] == struct))
// {
// alias FieldTypeTuple!(T[0]) MyRep;
// alias FieldOffsetsTupleImpl!(myOffset, MyRep, T[1 .. $]).Result
// Result;
// }
// else
// {
// private enum size_t mySize = T[0].sizeof;
// alias TypeTuple!(myOffset) Head;
// static if (is(T == union))
// {
// alias FieldOffsetsTupleImpl!(myOffset, T[1 .. $]).Result
// Tail;
// }
// else
// {
// alias FieldOffsetsTupleImpl!(myOffset + mySize,
// T[1 .. $]).Result
// Tail;
// }
// alias TypeTuple!(Head, Tail) Result;
// }
// }
// }
// template FieldOffsetsTuple(T...)
// {
// alias FieldOffsetsTupleImpl!(0, T).Result FieldOffsetsTuple;
// }
// unittest
// {
// alias FieldOffsetsTuple!(int) T1;
// assert(T1.length == 1 && T1[0] == 0);
// //
// struct S2 { char a; int b; char c; double d; char e, f; }
// alias FieldOffsetsTuple!(S2) T2;
// //pragma(msg, T2);
// static assert(T2.length == 6
// && T2[0] == 0 && T2[1] == 4 && T2[2] == 8 && T2[3] == 16
// && T2[4] == 24&& T2[5] == 25);
// //
// class C { int a, b, c, d; }
// struct S3 { char a; C b; char c; }
// alias FieldOffsetsTuple!(S3) T3;
// //pragma(msg, T2);
// static assert(T3.length == 3
// && T3[0] == 0 && T3[1] == 4 && T3[2] == 8);
// //
// struct S4 { char a; union { int b; char c; } int d; }
// alias FieldOffsetsTuple!(S4) T4;
// //pragma(msg, FieldTypeTuple!(S4));
// static assert(T4.length == 4
// && T4[0] == 0 && T4[1] == 4 && T4[2] == 8);
// }
// /***
// Get the offsets of the fields of a struct or class.
// */
// template FieldOffsetsTuple(S)
// {
// static if (is(S == struct) || is(S == class))
// alias typeof(S.tupleof) FieldTypeTuple;
// else
// static assert(0, "argument is not struct or class");
// }
/***
Get the primitive types of the fields of a struct or class, in
topological order.
Example:
----
struct S1 { int a; float b; }
struct S2 { char[] a; union { S1 b; S1 * c; } }
alias RepresentationTypeTuple!(S2) R;
assert(R.length == 4
&& is(R[0] == char[]) && is(R[1] == int)
&& is(R[2] == float) && is(R[3] == S1*));
----
*/
template RepresentationTypeTuple(T)
{
static if (is(T == struct) || is(T == union) || is(T == class))
{
alias RepresentationTypeTupleImpl!(FieldTypeTuple!T)
RepresentationTypeTuple;
}
else static if (is(T U == typedef))
{
alias RepresentationTypeTuple!U RepresentationTypeTuple;
}
else
{
alias RepresentationTypeTupleImpl!T
RepresentationTypeTuple;
}
}
private template RepresentationTypeTupleImpl(T...)
{
static if (T.length == 0)
{
alias TypeTuple!() RepresentationTypeTupleImpl;
}
else
{
static if (is(T[0] R: Rebindable!R))
alias .RepresentationTypeTupleImpl!(RepresentationTypeTupleImpl!R,
T[1 .. $])
RepresentationTypeTupleImpl;
else static if (is(T[0] == struct) || is(T[0] == union))
// @@@BUG@@@ this should work
// alias .RepresentationTypes!(T[0].tupleof)
// RepresentationTypes;
alias .RepresentationTypeTupleImpl!(FieldTypeTuple!(T[0]),
T[1 .. $])
RepresentationTypeTupleImpl;
else static if (is(T[0] U == typedef))
{
alias .RepresentationTypeTupleImpl!(FieldTypeTuple!(U),
T[1 .. $])
RepresentationTypeTupleImpl;
}
else
{
alias TypeTuple!(T[0], RepresentationTypeTupleImpl!(T[1 .. $]))
RepresentationTypeTupleImpl;
}
}
}
unittest
{
alias RepresentationTypeTuple!(int) S1;
static assert(is(S1 == TypeTuple!(int)));
struct S2 { int a; }
static assert(is(RepresentationTypeTuple!(S2) == TypeTuple!(int)));
struct S3 { int a; char b; }
static assert(is(RepresentationTypeTuple!(S3) == TypeTuple!(int, char)));
struct S4 { S1 a; int b; S3 c; }
static assert(is(RepresentationTypeTuple!(S4) ==
TypeTuple!(int, int, int, char)));
struct S11 { int a; float b; }
struct S21 { char[] a; union { S11 b; S11 * c; } }
alias RepresentationTypeTuple!(S21) R;
assert(R.length == 4
&& is(R[0] == char[]) && is(R[1] == int)
&& is(R[2] == float) && is(R[3] == S11*));
class C { int a; float b; }
alias RepresentationTypeTuple!C R1;
static assert(R1.length == 2 && is(R1[0] == int) && is(R1[1] == float));
/* Issue 6642 */
struct S5 { int a; Rebindable!(immutable Object) b; }
alias RepresentationTypeTuple!S5 R2;
static assert(R2.length == 2 && is(R2[0] == int) && is(R2[1] == immutable(Object)));
}
/*
RepresentationOffsets
*/
// private template Repeat(size_t n, T...)
// {
// static if (n == 0) alias TypeTuple!() Repeat;
// else alias TypeTuple!(T, Repeat!(n - 1, T)) Repeat;
// }
// template RepresentationOffsetsImpl(size_t n, T...)
// {
// static if (T.length == 0)
// {
// alias TypeTuple!() Result;
// }
// else
// {
// private enum size_t myOffset =
// ((n + T[0].alignof - 1) / T[0].alignof) * T[0].alignof;
// static if (!is(T[0] == union))
// {
// alias Repeat!(n, FieldTypeTuple!(T[0])).Result
// Head;
// }
// static if (is(T[0] == struct))
// {
// alias .RepresentationOffsetsImpl!(n, FieldTypeTuple!(T[0])).Result
// Head;
// }
// else
// {
// alias TypeTuple!(myOffset) Head;
// }
// alias TypeTuple!(Head,
// RepresentationOffsetsImpl!(
// myOffset + T[0].sizeof, T[1 .. $]).Result)
// Result;
// }
// }
// template RepresentationOffsets(T)
// {
// alias RepresentationOffsetsImpl!(0, T).Result
// RepresentationOffsets;
// }
// unittest
// {
// struct S1 { char c; int i; }
// alias RepresentationOffsets!(S1) Offsets;
// static assert(Offsets[0] == 0);
// //pragma(msg, Offsets[1]);
// static assert(Offsets[1] == 4);
// }
// hasRawAliasing
private template hasRawPointerImpl(T...)
{
static if (T.length == 0)
{
enum result = false;
}
else
{
static if (is(T[0] foo : U*, U) && !isFunctionPointer!(T[0]))
enum hasRawAliasing = !is(U == immutable);
else static if (is(T[0] foo : U[], U) && !isStaticArray!(T[0]))
enum hasRawAliasing = !is(U == immutable);
else static if (isAssociativeArray!(T[0]))
enum hasRawAliasing = !is(T[0] == immutable);
else
enum hasRawAliasing = false;
enum result = hasRawAliasing || hasRawPointerImpl!(T[1 .. $]).result;
}
}
private template HasRawLocalPointerImpl(T...)
{
static if (T.length == 0)
{
enum result = false;
}
else
{
static if (is(T[0] foo : U*, U) && !isFunctionPointer!(T[0]))
enum hasRawLocalAliasing = !is(U == immutable) && !is(U == shared);
else static if (is(T[0] foo : U[], U) && !isStaticArray!(T[0]))
enum hasRawLocalAliasing = !is(U == immutable) && !is(U == shared);
else static if (isAssociativeArray!(T[0]))
enum hasRawLocalAliasing = !is(T[0] == immutable) && !is(T[0] == shared);
else
enum hasRawLocalAliasing = false;
enum result = hasRawLocalAliasing || HasRawLocalPointerImpl!(T[1 .. $]).result;
}
}
/*
Statically evaluates to $(D true) if and only if $(D T)'s
representation contains at least one field of pointer or array type.
Members of class types are not considered raw pointers. Pointers to
immutable objects are not considered raw aliasing.
Example:
---
// simple types
static assert(!hasRawAliasing!(int));
static assert(hasRawAliasing!(char*));
// references aren't raw pointers
static assert(!hasRawAliasing!(Object));
// built-in arrays do contain raw pointers
static assert(hasRawAliasing!(int[]));
// aggregate of simple types
struct S1 { int a; double b; }
static assert(!hasRawAliasing!(S1));
// indirect aggregation
struct S2 { S1 a; double b; }
static assert(!hasRawAliasing!(S2));
// struct with a pointer member
struct S3 { int a; double * b; }
static assert(hasRawAliasing!(S3));
// struct with an indirect pointer member
struct S4 { S3 a; double b; }
static assert(hasRawAliasing!(S4));
----
*/
private template hasRawAliasing(T...)
{
enum hasRawAliasing
= hasRawPointerImpl!(RepresentationTypeTuple!T).result;
}
unittest
{
// simple types
static assert(!hasRawAliasing!(int));
static assert(hasRawAliasing!(char*));
// references aren't raw pointers
static assert(!hasRawAliasing!(Object));
static assert(!hasRawAliasing!(int));
struct S1 { int z; }
static assert(!hasRawAliasing!(S1));
struct S2 { int* z; }
static assert(hasRawAliasing!(S2));
struct S3 { int a; int* z; int c; }
static assert(hasRawAliasing!(S3));
struct S4 { int a; int z; int c; }
static assert(!hasRawAliasing!(S4));
struct S5 { int a; Object z; int c; }
static assert(!hasRawAliasing!(S5));
union S6 { int a; int b; }
static assert(!hasRawAliasing!(S6));
union S7 { int a; int * b; }
static assert(hasRawAliasing!(S7));
//typedef int* S8;
//static assert(hasRawAliasing!(S8));
enum S9 { a }
static assert(!hasRawAliasing!(S9));
// indirect members
struct S10 { S7 a; int b; }
static assert(hasRawAliasing!(S10));
struct S11 { S6 a; int b; }
static assert(!hasRawAliasing!(S11));
static assert(hasRawAliasing!(int[string]));
static assert(!hasRawAliasing!(immutable(int[string])));
}
/*
Statically evaluates to $(D true) if and only if $(D T)'s
representation contains at least one non-shared field of pointer or
array type. Members of class types are not considered raw pointers.
Pointers to immutable objects are not considered raw aliasing.
Example:
---
// simple types
static assert(!hasRawLocalAliasing!(int));
static assert(hasRawLocalAliasing!(char*));
static assert(!hasRawLocalAliasing!(shared char*));
// references aren't raw pointers
static assert(!hasRawLocalAliasing!(Object));
// built-in arrays do contain raw pointers
static assert(hasRawLocalAliasing!(int[]));
static assert(!hasRawLocalAliasing!(shared int[]));
// aggregate of simple types
struct S1 { int a; double b; }
static assert(!hasRawLocalAliasing!(S1));
// indirect aggregation
struct S2 { S1 a; double b; }
static assert(!hasRawLocalAliasing!(S2));
// struct with a pointer member
struct S3 { int a; double * b; }
static assert(hasRawLocalAliasing!(S3));
struct S4 { int a; shared double * b; }
static assert(hasRawLocalAliasing!(S4));
// struct with an indirect pointer member
struct S5 { S3 a; double b; }
static assert(hasRawLocalAliasing!(S5));
struct S6 { S4 a; double b; }
static assert(!hasRawLocalAliasing!(S6));
----
*/
private template hasRawUnsharedAliasing(T...)
{
enum hasRawUnsharedAliasing
= HasRawLocalPointerImpl!(RepresentationTypeTuple!(T)).result;
}
unittest
{
// simple types
static assert(!hasRawUnsharedAliasing!(int));
static assert(hasRawUnsharedAliasing!(char*));
static assert(!hasRawUnsharedAliasing!(shared char*));
// references aren't raw pointers
static assert(!hasRawUnsharedAliasing!(Object));
static assert(!hasRawUnsharedAliasing!(int));
struct S1 { int z; }
static assert(!hasRawUnsharedAliasing!(S1));
struct S2 { int* z; }
static assert(hasRawUnsharedAliasing!(S2));
struct S3 { shared int* z; }
static assert(!hasRawUnsharedAliasing!(S3));
struct S4 { int a; int* z; int c; }
static assert(hasRawUnsharedAliasing!(S4));
struct S5 { int a; shared int* z; int c; }
static assert(!hasRawUnsharedAliasing!(S5));
struct S6 { int a; int z; int c; }
static assert(!hasRawUnsharedAliasing!(S6));
struct S7 { int a; Object z; int c; }
static assert(!hasRawUnsharedAliasing!(S7));
union S8 { int a; int b; }
static assert(!hasRawUnsharedAliasing!(S8));
union S9 { int a; int * b; }
static assert(hasRawUnsharedAliasing!(S9));
union S10 { int a; shared int * b; }
static assert(!hasRawUnsharedAliasing!(S10));
//typedef int* S11;
//static assert(hasRawUnsharedAliasing!(S11));
//typedef shared int* S12;
//static assert(hasRawUnsharedAliasing!(S12));
enum S13 { a }
static assert(!hasRawUnsharedAliasing!(S13));
// indirect members
struct S14 { S9 a; int b; }
static assert(hasRawUnsharedAliasing!(S14));
struct S15 { S10 a; int b; }
static assert(!hasRawUnsharedAliasing!(S15));
struct S16 { S6 a; int b; }
static assert(!hasRawUnsharedAliasing!(S16));
static assert(hasRawUnsharedAliasing!(int[string]));
static assert(!hasRawUnsharedAliasing!(shared(int[string])));
static assert(!hasRawUnsharedAliasing!(immutable(int[string])));
}
/*
Statically evaluates to $(D true) if and only if $(D T)'s
representation includes at least one non-immutable object reference.
*/
private template hasObjects(T...)
{
static if (T.length == 0)
{
enum hasObjects = false;
}
else static if (is(T[0] U == typedef))
{
enum hasObjects = hasObjects!(U, T[1 .. $]);
}
else static if (is(T[0] == struct))
{
enum hasObjects = hasObjects!(
RepresentationTypeTuple!(T[0]), T[1 .. $]);
}
else
{
enum hasObjects = ((is(T[0] == class) || is(T[0] == interface))
&& !is(T[0] == immutable)) || hasObjects!(T[1 .. $]);
}
}
/*
Statically evaluates to $(D true) if and only if $(D T)'s
representation includes at least one non-immutable non-shared object
reference.
*/
private template hasUnsharedObjects(T...)
{
static if (T.length == 0)
{
enum hasUnsharedObjects = false;
}
else static if (is(T[0] U == typedef))
{
enum hasUnsharedObjects = hasUnsharedObjects!(U, T[1 .. $]);
}
else static if (is(T[0] == struct))
{
enum hasUnsharedObjects = hasUnsharedObjects!(
RepresentationTypeTuple!(T[0]), T[1 .. $]);
}
else
{
enum hasUnsharedObjects = ((is(T[0] == class) || is(T[0] == interface)) &&
!is(T[0] == immutable) && !is(T[0] == shared)) ||
hasUnsharedObjects!(T[1 .. $]);
}
}
/**
Returns $(D true) if and only if $(D T)'s representation includes at
least one of the following: $(OL $(LI a raw pointer $(D U*) and $(D U)
is not immutable;) $(LI an array $(D U[]) and $(D U) is not
immutable;) $(LI a reference to a class or interface type $(D C) and $(D C) is
not immutable.) $(LI an associative array that is not immutable.)
$(LI a delegate.))
*/
template hasAliasing(T...)
{
enum hasAliasing = hasRawAliasing!(T) || hasObjects!(T) ||
anySatisfy!(isDelegate, T);
}
// Specialization to special-case std.typecons.Rebindable.
template hasAliasing(R : Rebindable!R)
{
enum hasAliasing = hasAliasing!R;
}
unittest
{
struct S1 { int a; Object b; }
static assert(hasAliasing!(S1));
struct S2 { string a; }
static assert(!hasAliasing!(S2));
struct S3 { int a; immutable Object b; }
static assert(!hasAliasing!(S3));
struct X { float[3] vals; }
static assert(!hasAliasing!X);
static assert(hasAliasing!(uint[uint]));
static assert(!hasAliasing!(immutable(uint[uint])));
static assert(hasAliasing!(void delegate()));
static assert(!hasAliasing!(void function()));
interface I;
static assert(hasAliasing!I);
static assert(hasAliasing!(Rebindable!(const Object)));
static assert(!hasAliasing!(Rebindable!(immutable Object)));
static assert(hasAliasing!(Rebindable!(shared Object)));
static assert(hasAliasing!(Rebindable!(Object)));
}
/**
Returns $(D true) if and only if $(D T)'s representation includes at
least one of the following: $(OL $(LI a raw pointer $(D U*);) $(LI an
array $(D U[]);) $(LI a reference to a class type $(D C).)
$(LI an associative array.) $(LI a delegate.))
*/
template hasIndirections(T)
{
enum hasIndirections = hasIndirectionsImpl!(RepresentationTypeTuple!T);
}
template hasIndirectionsImpl(T...)
{
static if (!T.length)
{
enum hasIndirectionsImpl = false;
}
else static if(isFunctionPointer!(T[0]))
{
enum hasIndirectionsImpl = hasIndirectionsImpl!(T[1 .. $]);
}
else static if(isStaticArray!(T[0]))
{
enum hasIndirectionsImpl = hasIndirectionsImpl!(T[1 .. $]) ||
hasIndirectionsImpl!(RepresentationTypeTuple!(typeof(T[0].init[0])));
}
else
{
enum hasIndirectionsImpl = isPointer!(T[0]) || isDynamicArray!(T[0]) ||
is (T[0] : const(Object)) || isAssociativeArray!(T[0]) ||
isDelegate!(T[0]) || is(T[0] == interface)
|| hasIndirectionsImpl!(T[1 .. $]);
}
}
unittest
{
struct S1 { int a; Object b; }
static assert(hasIndirections!(S1));
struct S2 { string a; }
static assert(hasIndirections!(S2));
struct S3 { int a; immutable Object b; }
static assert(hasIndirections!(S3));
static assert(hasIndirections!(int[string]));
static assert(hasIndirections!(void delegate()));
interface I;
static assert(hasIndirections!I);
static assert(!hasIndirections!(void function()));
static assert(hasIndirections!(void*[1]));
static assert(!hasIndirections!(byte[1]));
}
// These are for backwards compatibility, are intentionally lacking ddoc,
// and should eventually be deprecated.
alias hasUnsharedAliasing hasLocalAliasing;
alias hasRawUnsharedAliasing hasRawLocalAliasing;
alias hasUnsharedObjects hasLocalObjects;
/**
Returns $(D true) if and only if $(D T)'s representation includes at
least one of the following: $(OL $(LI a raw pointer $(D U*) and $(D U)
is not immutable or shared;) $(LI an array $(D U[]) and $(D U) is not
immutable or shared;) $(LI a reference to a class type $(D C) and
$(D C) is not immutable or shared.) $(LI an associative array that is not
immutable or shared.) $(LI a delegate that is not shared.))
*/
template hasUnsharedAliasing(T...)
{
static if (!T.length)
{
enum hasUnsharedAliasing = false;
}
else static if (is(T[0] R: Rebindable!R))
{
enum hasUnsharedAliasing = hasUnsharedAliasing!R;
}
else
{
enum hasUnsharedAliasing =
hasRawUnsharedAliasing!(T[0]) ||
anySatisfy!(unsharedDelegate, T[0]) ||
hasUnsharedObjects!(T[0]) ||
hasUnsharedAliasing!(T[1..$]);
}
}
private template unsharedDelegate(T)
{
enum bool unsharedDelegate = isDelegate!T && !is(T == shared);
}
unittest
{
struct S1 { int a; Object b; }
static assert(hasUnsharedAliasing!(S1));
struct S2 { string a; }
static assert(!hasUnsharedAliasing!(S2));
struct S3 { int a; immutable Object b; }
static assert(!hasUnsharedAliasing!(S3));
struct S4 { int a; shared Object b; }
static assert(!hasUnsharedAliasing!(S4));
struct S5 { char[] a; }
static assert(hasUnsharedAliasing!(S5));
struct S6 { shared char[] b; }
static assert(!hasUnsharedAliasing!(S6));
struct S7 { float[3] vals; }
static assert(!hasUnsharedAliasing!(S7));
/* Issue 6642 */
struct S8 { int a; Rebindable!(immutable Object) b; }
static assert(!hasUnsharedAliasing!(S8));
static assert(hasUnsharedAliasing!(uint[uint]));
static assert(hasUnsharedAliasing!(void delegate()));
static assert(!hasUnsharedAliasing!(shared(void delegate())));
static assert(!hasUnsharedAliasing!(void function()));
interface I {}
static assert(hasUnsharedAliasing!I);
static assert(hasUnsharedAliasing!(Rebindable!(const Object)));
static assert(!hasUnsharedAliasing!(Rebindable!(immutable Object)));
static assert(!hasUnsharedAliasing!(Rebindable!(shared Object)));
static assert(hasUnsharedAliasing!(Rebindable!(Object)));
/* Issue 6979 */
static assert(!hasUnsharedAliasing!(int, shared(int)*));
static assert(hasUnsharedAliasing!(int, int*));
static assert(hasUnsharedAliasing!(int, const(int)[]));
static assert(hasUnsharedAliasing!(int, shared(int)*, Rebindable!(Object)));
static assert(!hasUnsharedAliasing!(shared(int)*, Rebindable!(shared Object)));
static assert(!hasUnsharedAliasing!());
}
/**
True if $(D S) or any type embedded directly in the representation of $(D S)
defines an elaborate copy constructor. Elaborate copy constructors are
introduced by defining $(D this(this)) for a $(D struct). (Non-struct types
never have elaborate copy constructors.)
*/
template hasElaborateCopyConstructor(S)
{
static if(!is(S == struct))
{
enum bool hasElaborateCopyConstructor = false;
}
else
{
enum hasElaborateCopyConstructor = is(typeof({
S s;
return &s.__postblit;
})) || anySatisfy!(.hasElaborateCopyConstructor, typeof(S.tupleof));
}
}
unittest
{
static assert(!hasElaborateCopyConstructor!int);
struct S
{
this(this) {}
}
static assert(hasElaborateCopyConstructor!S);
struct S2
{
uint num;
}
struct S3
{
uint num;
S s;
}
static assert(!hasElaborateCopyConstructor!S2);
static assert(hasElaborateCopyConstructor!S3);
}
/**
True if $(D S) or any type directly embedded in the representation of $(D S)
defines an elaborate assignmentq. Elaborate assignments are introduced by
defining $(D opAssign(typeof(this))) or $(D opAssign(ref typeof(this)))
for a $(D struct). (Non-struct types never have elaborate assignments.)
*/
template hasElaborateAssign(S)
{
static if(!is(S == struct))
{
enum bool hasElaborateAssign = false;
}
else
{
enum hasElaborateAssign = is(typeof(S.init.opAssign(S.init))) ||
is(typeof(S.init.opAssign({ return S.init; }()))) ||
anySatisfy!(.hasElaborateAssign, typeof(S.tupleof));
}
}
unittest
{
static assert(!hasElaborateAssign!int);
struct S { void opAssign(S) {} }
static assert(hasElaborateAssign!S);
struct S1 { void opAssign(ref S1) {} }
static assert(hasElaborateAssign!S1);
struct S2 { void opAssign(S1) {} }
static assert(!hasElaborateAssign!S2);
struct S3 { S s; }
static assert(hasElaborateAssign!S3);
struct S4 {
void opAssign(U)(auto ref U u)
if (!__traits(isRef, u))
{}
}
static assert(hasElaborateAssign!S4);
}
/**
True if $(D S) or any type directly embedded in the representation
of $(D S) defines an elaborate destructor. Elaborate destructors
are introduced by defining $(D ~this()) for a $(D
struct). (Non-struct types never have elaborate destructors, even
though classes may define $(D ~this()).)
*/
template hasElaborateDestructor(S)
{
static if(!is(S == struct))
{
enum bool hasElaborateDestructor = false;
}
else
{
enum hasElaborateDestructor = is(typeof({S s; return &s.__dtor;}))
|| anySatisfy!(.hasElaborateDestructor, typeof(S.tupleof));
}
}
unittest
{
static assert(!hasElaborateDestructor!int);
static struct S1 { }
static assert(!hasElaborateDestructor!S1);
static struct S2 { ~this() {} }
static assert(hasElaborateDestructor!S2);
static struct S3 { S2 field; }
static assert(hasElaborateDestructor!S3);
}
/**
Yields $(D true) if and only if $(D T) is an aggregate that defines
a symbol called $(D name).
*/
template hasMember(T, string name)
{
static if (is(T == struct) || is(T == class) || is(T == union) || is(T == interface))
{
enum bool hasMember =
staticIndexOf!(name, __traits(allMembers, T)) != -1;
}
else
{
enum bool hasMember = false;
}
}
unittest
{
//pragma(msg, __traits(allMembers, void delegate()));
static assert(!hasMember!(int, "blah"));
struct S1 { int blah; }
static assert(hasMember!(S1, "blah"));
struct S2 { int blah(); }
static assert(hasMember!(S2, "blah"));
struct C1 { int blah; }
static assert(hasMember!(C1, "blah"));
struct C2 { int blah(); }
static assert(hasMember!(C2, "blah"));
// 6973
import std.range;
static assert(isOutputRange!(OutputRange!int, int));
}
/**
Retrieves the members of an enumerated type $(D enum E).
Params:
E = An enumerated type. $(D E) may have duplicated values.
Returns:
Static tuple composed of the members of the enumerated type $(D E).
The members are arranged in the same order as declared in $(D E).
Note:
Returned values are strictly typed with $(D E). Thus, the following code
does not work without the explicit cast:
--------------------
enum E : int { a, b, c }
int[] abc = cast(int[]) [ EnumMembers!E ];
--------------------
Cast is not necessary if the type of the variable is inferred. See the
example below.
Examples:
Creating an array of enumerated values:
--------------------
enum Sqrts : real
{
one = 1,
two = 1.41421,
three = 1.73205,
}
auto sqrts = [ EnumMembers!Sqrts ];
assert(sqrts == [ Sqrts.one, Sqrts.two, Sqrts.three ]);
--------------------
A generic function $(D rank(v)) in the following example uses this
template for finding a member $(D e) in an enumerated type $(D E).
--------------------
// Returns i if e is the i-th enumerator of E.
size_t rank(E)(E e)
if (is(E == enum))
{
foreach (i, member; EnumMembers!E)
{
if (e == member)
return i;
}
assert(0, "Not an enum member");
}
enum Mode
{
read = 1,
write = 2,
map = 4,
}
assert(rank(Mode.read ) == 0);
assert(rank(Mode.write) == 1);
assert(rank(Mode.map ) == 2);
--------------------
*/
template EnumMembers(E)
if (is(E == enum))
{
alias EnumSpecificMembers!(E, __traits(allMembers, E)) EnumMembers;
}
private template EnumSpecificMembers(Enum, names...)
{
static if (names.length > 0)
{
alias TypeTuple!(
WithIdentifier!(names[0])
.Symbolize!(__traits(getMember, Enum, names[0])),
EnumSpecificMembers!(Enum, names[1 .. $])
) EnumSpecificMembers;
}
else
{
alias TypeTuple!() EnumSpecificMembers;
}
}
unittest
{
enum A { a }
static assert([ EnumMembers!A ] == [ A.a ]);
enum B { a, b, c, d, e }
static assert([ EnumMembers!B ] == [ B.a, B.b, B.c, B.d, B.e ]);
}
unittest // typed enums
{
enum A : string { a = "alpha", b = "beta" }
static assert([ EnumMembers!A ] == [ A.a, A.b ]);
static struct S
{
int value;
int opCmp(S rhs) const nothrow { return value - rhs.value; }
}
enum B : S { a = S(1), b = S(2), c = S(3) }
static assert([ EnumMembers!B ] == [ B.a, B.b, B.c ]);
}
unittest // duplicated values
{
enum A
{
a = 0, b = 0,
c = 1, d = 1, e
}
static assert([ EnumMembers!A ] == [ A.a, A.b, A.c, A.d, A.e ]);
}
// Supply the specified identifier to an constant value.
private template WithIdentifier(string ident)
{
static if (ident == "Symbolize")
{
template Symbolize(alias value)
{
enum Symbolize = value;
}
}
else
{
mixin("template Symbolize(alias "~ ident ~")"
~"{"
~"alias "~ ident ~" Symbolize;"
~"}");
}
}
unittest
{
enum E { member, a = 0, b = 0 }
static assert(__traits(identifier, EnumMembers!E[0]) == "member");
static assert(__traits(identifier, EnumMembers!E[1]) == "a");
static assert(__traits(identifier, EnumMembers!E[2]) == "b");
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// Classes and Interfaces
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
/***
* Get a $(D_PARAM TypeTuple) of the base class and base interfaces of
* this class or interface. $(D_PARAM BaseTypeTuple!(Object)) returns
* the empty type tuple.
*
* Example:
* ---
* import std.traits, std.typetuple, std.stdio;
* interface I { }
* class A { }
* class B : A, I { }
*
* void main()
* {
* alias BaseTypeTuple!(B) TL;
* writeln(typeid(TL)); // prints: (A,I)
* }
* ---
*/
template BaseTypeTuple(A)
{
static if (is(A P == super))
alias P BaseTypeTuple;
else
static assert(0, "argument is not a class or interface");
}
unittest
{
interface I1 { }
interface I2 { }
interface I12 : I1, I2 { }
static assert(is(BaseTypeTuple!I12 == TypeTuple!(I1, I2)));
interface I3 : I1 { }
interface I123 : I1, I2, I3 { }
static assert(is(BaseTypeTuple!I123 == TypeTuple!(I1, I2, I3)));
}
unittest
{
interface I1 { }
interface I2 { }
class A { }
class C : A, I1, I2 { }
alias BaseTypeTuple!(C) TL;
assert(TL.length == 3);
assert(is (TL[0] == A));
assert(is (TL[1] == I1));
assert(is (TL[2] == I2));
assert(BaseTypeTuple!(Object).length == 0);
}
/**
* Get a $(D_PARAM TypeTuple) of $(I all) base classes of this class,
* in decreasing order. Interfaces are not included. $(D_PARAM
* BaseClassesTuple!(Object)) yields the empty type tuple.
*
* Example:
* ---
* import std.traits, std.typetuple, std.stdio;
* interface I { }
* class A { }
* class B : A, I { }
* class C : B { }
*
* void main()
* {
* alias BaseClassesTuple!(C) TL;
* writeln(typeid(TL)); // prints: (B,A,Object)
* }
* ---
*/
template BaseClassesTuple(T)
{
static if (is(T == Object))
{
alias TypeTuple!() BaseClassesTuple;
}
static if (is(BaseTypeTuple!(T)[0] == Object))
{
alias TypeTuple!(Object) BaseClassesTuple;
}
else
{
alias TypeTuple!(BaseTypeTuple!(T)[0],
BaseClassesTuple!(BaseTypeTuple!(T)[0]))
BaseClassesTuple;
}
}
/**
* Get a $(D_PARAM TypeTuple) of $(I all) interfaces directly or
* indirectly inherited by this class or interface. Interfaces do not
* repeat if multiply implemented. $(D_PARAM InterfacesTuple!(Object))
* yields the empty type tuple.
*
* Example:
* ---
* import std.traits, std.typetuple, std.stdio;
* interface I1 { }
* interface I2 { }
* class A : I1, I2 { }
* class B : A, I1 { }
* class C : B { }
*
* void main()
* {
* alias InterfacesTuple!(C) TL;
* writeln(typeid(TL)); // prints: (I1, I2)
* }
* ---
*/
template InterfacesTuple(T)
{
static if (is(T S == super) && S.length)
alias NoDuplicates!(InterfacesTuple_Flatten!(S))
InterfacesTuple;
else
alias TypeTuple!() InterfacesTuple;
}
// internal
private template InterfacesTuple_Flatten(H, T...)
{
static if (T.length)
{
alias TypeTuple!(
InterfacesTuple_Flatten!(H),
InterfacesTuple_Flatten!(T))
InterfacesTuple_Flatten;
}
else
{
static if (is(H == interface))
alias TypeTuple!(H, InterfacesTuple!(H))
InterfacesTuple_Flatten;
else
alias InterfacesTuple!(H) InterfacesTuple_Flatten;
}
}
unittest
{
struct Test1_WorkaroundForBug2986 {
// doc example
interface I1 {}
interface I2 {}
class A : I1, I2 { }
class B : A, I1 { }
class C : B { }
alias InterfacesTuple!(C) TL;
static assert(is(TL[0] == I1) && is(TL[1] == I2));
}
struct Test2_WorkaroundForBug2986 {
interface Iaa {}
interface Iab {}
interface Iba {}
interface Ibb {}
interface Ia : Iaa, Iab {}
interface Ib : Iba, Ibb {}
interface I : Ia, Ib {}
interface J {}
class B : J {}
class C : B, Ia, Ib {}
static assert(is(InterfacesTuple!(I) ==
TypeTuple!(Ia, Iaa, Iab, Ib, Iba, Ibb)));
static assert(is(InterfacesTuple!(C) ==
TypeTuple!(J, Ia, Iaa, Iab, Ib, Iba, Ibb)));
}
}
/**
* Get a $(D_PARAM TypeTuple) of $(I all) base classes of $(D_PARAM
* T), in decreasing order, followed by $(D_PARAM T)'s
* interfaces. $(D_PARAM TransitiveBaseTypeTuple!(Object)) yields the
* empty type tuple.
*
* Example:
* ---
* import std.traits, std.typetuple, std.stdio;
* interface I { }
* class A { }
* class B : A, I { }
* class C : B { }
*
* void main()
* {
* alias TransitiveBaseTypeTuple!(C) TL;
* writeln(typeid(TL)); // prints: (B,A,Object,I)
* }
* ---
*/
template TransitiveBaseTypeTuple(T)
{
static if (is(T == Object))
alias TypeTuple!() TransitiveBaseTypeTuple;
else
alias TypeTuple!(BaseClassesTuple!(T),
InterfacesTuple!(T))
TransitiveBaseTypeTuple;
}
unittest
{
interface J1 {}
interface J2 {}
class B1 {}
class B2 : B1, J1, J2 {}
class B3 : B2, J1 {}
alias TransitiveBaseTypeTuple!(B3) TL;
assert(TL.length == 5);
assert(is (TL[0] == B2));
assert(is (TL[1] == B1));
assert(is (TL[2] == Object));
assert(is (TL[3] == J1));
assert(is (TL[4] == J2));
assert(TransitiveBaseTypeTuple!(Object).length == 0);
}
/**
Returns a tuple of non-static functions with the name $(D name) declared in the
class or interface $(D C). Covariant duplicates are shrunk into the most
derived one.
Example:
--------------------
interface I { I foo(); }
class B
{
real foo(real v) { return v; }
}
class C : B, I
{
override C foo() { return this; } // covariant overriding of I.foo()
}
alias MemberFunctionsTuple!(C, "foo") foos;
static assert(foos.length == 2);
static assert(__traits(isSame, foos[0], C.foo));
static assert(__traits(isSame, foos[1], B.foo));
--------------------
*/
template MemberFunctionsTuple(C, string name)
if (is(C == class) || is(C == interface))
{
static if (__traits(hasMember, C, name))
alias MemberFunctionTupleImpl!(C, name).result MemberFunctionsTuple;
else
alias TypeTuple!() MemberFunctionsTuple;
}
private template MemberFunctionTupleImpl(C, string name)
{
/*
* First, collect all overloads in the class hierarchy.
*/
template CollectOverloads(Node)
{
static if (__traits(hasMember, Node, name) && __traits(compiles, __traits(getMember, Node, name)))
{
// Get all overloads in sight (not hidden).
alias TypeTuple!(__traits(getVirtualFunctions, Node, name)) inSight;
// And collect all overloads in ancestor classes to reveal hidden
// methods. The result may contain duplicates.
template walkThru(Parents...)
{
static if (Parents.length > 0)
alias TypeTuple!(
CollectOverloads!(Parents[0]).result,
walkThru!(Parents[1 .. $])
) walkThru;
else
alias TypeTuple!() walkThru;
}
static if (is(Node Parents == super))
alias TypeTuple!(inSight, walkThru!(Parents)) result;
else
alias TypeTuple!(inSight) result;
}
else
alias TypeTuple!() result; // no overloads in this hierarchy
}
// duplicates in this tuple will be removed by shrink()
alias CollectOverloads!(C).result overloads;
/*
* Now shrink covariant overloads into one.
*/
template shrink(overloads...)
{
static if (overloads.length > 0)
{
alias shrinkOne!(overloads).result temp;
alias TypeTuple!(temp[0], shrink!(temp[1 .. $]).result) result;
}
else
alias TypeTuple!() result; // done
}
// .result[0] = the most derived one in the covariant siblings of target
// .result[1..$] = non-covariant others
template shrinkOne(/+ alias target, rest... +/ args...)
{
alias args[0 .. 1] target; // prevent property functions from being evaluated
alias args[1 .. $] rest;
static if (rest.length > 0)
{
alias FunctionTypeOf!(target) Target;
alias FunctionTypeOf!(rest[0]) Rest0;
static if (isCovariantWith!(Target, Rest0))
// target overrides rest[0] -- erase rest[0].
alias shrinkOne!(target, rest[1 .. $]).result result;
else static if (isCovariantWith!(Rest0, Target))
// rest[0] overrides target -- erase target.
alias shrinkOne!(rest[0], rest[1 .. $]).result result;
else
// target and rest[0] are distinct.
alias TypeTuple!(
shrinkOne!(target, rest[1 .. $]).result,
rest[0] // keep
) result;
}
else
alias TypeTuple!(target) result; // done
}
// done.
alias shrink!(overloads).result result;
}
unittest
{
interface I { I test(); }
interface J : I { J test(); }
interface K { K test(int); }
class B : I, K
{
K test(int) { return this; }
B test() { return this; }
static void test(string) { }
}
class C : B, J
{
override C test() { return this; }
}
alias MemberFunctionsTuple!(C, "test") test;
static assert(test.length == 2);
static assert(is(FunctionTypeOf!(test[0]) == FunctionTypeOf!(C.test)));
static assert(is(FunctionTypeOf!(test[1]) == FunctionTypeOf!(K.test)));
alias MemberFunctionsTuple!(C, "noexist") noexist;
static assert(noexist.length == 0);
interface L { int prop() @property; }
alias MemberFunctionsTuple!(L, "prop") prop;
static assert(prop.length == 1);
interface Test_I
{
void foo();
void foo(int);
void foo(int, int);
}
interface Test : Test_I {}
alias MemberFunctionsTuple!(Test, "foo") Test_foo;
static assert(Test_foo.length == 3);
static assert(is(typeof(&Test_foo[0]) == void function()));
static assert(is(typeof(&Test_foo[2]) == void function(int)));
static assert(is(typeof(&Test_foo[1]) == void function(int, int)));
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// Type Conversion
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
/**
Get the type that all types can be implicitly converted to. Useful
e.g. in figuring out an array type from a bunch of initializing
values. Returns $(D_PARAM void) if passed an empty list, or if the
types have no common type.
Example:
----
alias CommonType!(int, long, short) X;
assert(is(X == long));
alias CommonType!(int, char[], short) Y;
assert(is(Y == void));
----
*/
template CommonType(T...)
{
static if (!T.length)
alias void CommonType;
else static if (T.length == 1)
{
static if(is(typeof(T[0])))
{
alias typeof(T[0]) CommonType;
}
else
{
alias T[0] CommonType;
}
}
else static if (is(typeof(true ? T[0].init : T[1].init) U))
alias CommonType!(U, T[2 .. $]) CommonType;
else
alias void CommonType;
}
unittest
{
alias CommonType!(int, long, short) X;
static assert(is(X == long));
alias CommonType!(char[], int, long, short) Y;
static assert(is(Y == void), Y.stringof);
static assert(is(CommonType!(3) == int));
static assert(is(CommonType!(double, 4, float) == double));
static assert(is(CommonType!(string, char[]) == const(char)[]));
static assert(is(CommonType!(3, 3U) == uint));
}
/**
* Returns a tuple with all possible target types of an implicit
* conversion of a value of type $(D_PARAM T).
*
* Important note:
*
* The possible targets are computed more conservatively than the D
* 2.005 compiler does, eliminating all dangerous conversions. For
* example, $(D_PARAM ImplicitConversionTargets!(double)) does not
* include $(D_PARAM float).
*/
template ImplicitConversionTargets(T)
{
static if (is(T == bool))
alias TypeTuple!(byte, ubyte, short, ushort, int, uint, long, ulong,
float, double, real, char, wchar, dchar)
ImplicitConversionTargets;
else static if (is(T == byte))
alias TypeTuple!(short, ushort, int, uint, long, ulong,
float, double, real, char, wchar, dchar)
ImplicitConversionTargets;
else static if (is(T == ubyte))
alias TypeTuple!(short, ushort, int, uint, long, ulong,
float, double, real, char, wchar, dchar)
ImplicitConversionTargets;
else static if (is(T == short))
alias TypeTuple!(ushort, int, uint, long, ulong,
float, double, real)
ImplicitConversionTargets;
else static if (is(T == ushort))
alias TypeTuple!(int, uint, long, ulong, float, double, real)
ImplicitConversionTargets;
else static if (is(T == int))
alias TypeTuple!(long, ulong, float, double, real)
ImplicitConversionTargets;
else static if (is(T == uint))
alias TypeTuple!(long, ulong, float, double, real)
ImplicitConversionTargets;
else static if (is(T == long))
alias TypeTuple!(float, double, real)
ImplicitConversionTargets;
else static if (is(T == ulong))
alias TypeTuple!(float, double, real)
ImplicitConversionTargets;
else static if (is(T == float))
alias TypeTuple!(double, real)
ImplicitConversionTargets;
else static if (is(T == double))
alias TypeTuple!(real)
ImplicitConversionTargets;
else static if (is(T == char))
alias TypeTuple!(wchar, dchar, byte, ubyte, short, ushort,
int, uint, long, ulong, float, double, real)
ImplicitConversionTargets;
else static if (is(T == wchar))
alias TypeTuple!(wchar, dchar, short, ushort, int, uint, long, ulong,
float, double, real)
ImplicitConversionTargets;
else static if (is(T == dchar))
alias TypeTuple!(wchar, dchar, int, uint, long, ulong,
float, double, real)
ImplicitConversionTargets;
else static if (is(T : typeof(null)))
alias TypeTuple!(typeof(null)) ImplicitConversionTargets;
else static if(is(T : Object))
alias TransitiveBaseTypeTuple!(T) ImplicitConversionTargets;
// @@@BUG@@@ this should work
// else static if (isDynamicArray!T && !is(typeof(T.init[0]) == const))
// alias TypeTuple!(const(typeof(T.init[0]))[]) ImplicitConversionTargets;
else static if (is(T == char[]))
alias TypeTuple!(const(char)[]) ImplicitConversionTargets;
else static if (isDynamicArray!T && !is(typeof(T.init[0]) == const))
alias TypeTuple!(const(typeof(T.init[0]))[]) ImplicitConversionTargets;
else static if (is(T : void*))
alias TypeTuple!(void*) ImplicitConversionTargets;
else
alias TypeTuple!() ImplicitConversionTargets;
}
unittest
{
assert(is(ImplicitConversionTargets!(double)[0] == real));
}
/**
Is $(D From) implicitly convertible to $(D To)?
*/
template isImplicitlyConvertible(From, To)
{
enum bool isImplicitlyConvertible = is(typeof({
void fun(ref From v) {
void gun(To) {}
gun(v);
}
}()));
}
unittest
{
static assert(isImplicitlyConvertible!(immutable(char), char));
static assert(isImplicitlyConvertible!(const(char), char));
static assert(isImplicitlyConvertible!(char, wchar));
static assert(!isImplicitlyConvertible!(wchar, char));
// bug6197
static assert(!isImplicitlyConvertible!(const(ushort), ubyte));
static assert(!isImplicitlyConvertible!(const(uint), ubyte));
static assert(!isImplicitlyConvertible!(const(ulong), ubyte));
// from std.conv.implicitlyConverts
assert(!isImplicitlyConvertible!(const(char)[], string));
assert(isImplicitlyConvertible!(string, const(char)[]));
}
/**
Returns $(D true) iff a value of type $(D Rhs) can be assigned to a variable of
type $(D Lhs).
Examples:
---
static assert(isAssignable!(long, int));
static assert(!isAssignable!(int, long));
static assert(isAssignable!(const(char)[], string));
static assert(!isAssignable!(string, char[]));
---
*/
template isAssignable(Lhs, Rhs) {
enum bool isAssignable = is(typeof({
Lhs l;
Rhs r;
l = r;
return l;
}));
}
unittest {
static assert(isAssignable!(long, int));
static assert(!isAssignable!(int, long));
static assert(isAssignable!(const(char)[], string));
static assert(!isAssignable!(string, char[]));
}
/*
Works like $(D isImplicitlyConvertible), except this cares only about storage
classes of the arguments.
*/
private template isStorageClassImplicitlyConvertible(From, To)
{
enum isStorageClassImplicitlyConvertible = isImplicitlyConvertible!(
ModifyTypePreservingSTC!(Pointify, From),
ModifyTypePreservingSTC!(Pointify, To) );
}
private template Pointify(T) { alias void* Pointify; }
unittest
{
static assert(isStorageClassImplicitlyConvertible!( int, const int));
static assert(isStorageClassImplicitlyConvertible!(immutable int, const int));
static assert(! isStorageClassImplicitlyConvertible!(const int, int));
static assert(! isStorageClassImplicitlyConvertible!(const int, immutable int));
static assert(! isStorageClassImplicitlyConvertible!(int, shared int));
static assert(! isStorageClassImplicitlyConvertible!(shared int, int));
}
/**
Determines whether the function type $(D F) is covariant with $(D G), i.e.,
functions of the type $(D F) can override ones of the type $(D G).
Example:
--------------------
interface I { I clone(); }
interface J { J clone(); }
class C : I
{
override C clone() // covariant overriding of I.clone()
{
return new C;
}
}
// C.clone() can override I.clone(), indeed.
static assert(isCovariantWith!(typeof(C.clone), typeof(I.clone)));
// C.clone() can't override J.clone(); the return type C is not implicitly
// convertible to J.
static assert(isCovariantWith!(typeof(C.clone), typeof(J.clone)));
--------------------
*/
template isCovariantWith(F, G)
if (is(F == function) && is(G == function))
{
static if (is(F : G))
enum isCovariantWith = true;
else
enum isCovariantWith = isCovariantWithImpl!(F, G).yes;
}
private template isCovariantWithImpl(Upr, Lwr)
{
/*
* Check for calling convention: require exact match.
*/
template checkLinkage()
{
enum ok = functionLinkage!(Upr) == functionLinkage!(Lwr);
}
/*
* Check for variadic parameter: require exact match.
*/
template checkVariadicity()
{
enum ok = variadicFunctionStyle!(Upr) == variadicFunctionStyle!(Lwr);
}
/*
* Check for function storage class:
* - overrider can have narrower storage class than base
*/
template checkSTC()
{
// Note the order of arguments. The convertion order Lwr -> Upr is
// correct since Upr should be semantically 'narrower' than Lwr.
enum ok = isStorageClassImplicitlyConvertible!(Lwr, Upr);
}
/*
* Check for function attributes:
* - require exact match for ref and @property
* - overrider can add pure and nothrow, but can't remove them
* - @safe and @trusted are covariant with each other, unremovable
*/
template checkAttributes()
{
alias FunctionAttribute FA;
enum uprAtts = functionAttributes!(Upr);
enum lwrAtts = functionAttributes!(Lwr);
//
enum wantExact = FA.ref_ | FA.property;
enum safety = FA.safe | FA.trusted;
enum ok =
( (uprAtts & wantExact) == (lwrAtts & wantExact)) &&
( (uprAtts & FA.pure_ ) >= (lwrAtts & FA.pure_ )) &&
( (uprAtts & FA.nothrow_) >= (lwrAtts & FA.nothrow_)) &&
(!!(uprAtts & safety ) >= !!(lwrAtts & safety )) ;
}
/*
* Check for return type: usual implicit convertion.
*/
template checkReturnType()
{
enum ok = is(ReturnType!(Upr) : ReturnType!(Lwr));
}
/*
* Check for parameters:
* - require exact match for types (cf. bugzilla 3075)
* - require exact match for in, out, ref and lazy
* - overrider can add scope, but can't remove
*/
template checkParameters()
{
alias ParameterStorageClass STC;
alias ParameterTypeTuple!(Upr) UprParams;
alias ParameterTypeTuple!(Lwr) LwrParams;
alias ParameterStorageClassTuple!(Upr) UprPSTCs;
alias ParameterStorageClassTuple!(Lwr) LwrPSTCs;
//
template checkNext(size_t i)
{
static if (i < UprParams.length)
{
enum uprStc = UprPSTCs[i];
enum lwrStc = LwrPSTCs[i];
//
enum wantExact = STC.out_ | STC.ref_ | STC.lazy_;
enum ok =
((uprStc & wantExact ) == (lwrStc & wantExact )) &&
((uprStc & STC.scope_) >= (lwrStc & STC.scope_)) &&
checkNext!(i + 1).ok;
}
else
enum ok = true; // done
}
static if (UprParams.length == LwrParams.length)
enum ok = is(UprParams == LwrParams) && checkNext!(0).ok;
else
enum ok = false;
}
/* run all the checks */
enum bool yes =
checkLinkage !().ok &&
checkVariadicity!().ok &&
checkSTC !().ok &&
checkAttributes !().ok &&
checkReturnType !().ok &&
checkParameters !().ok ;
}
version (unittest) private template isCovariantWith(alias f, alias g)
{
enum bool isCovariantWith = isCovariantWith!(typeof(f), typeof(g));
}
unittest
{
// covariant return type
interface I {}
interface J : I {}
interface BaseA { const(I) test(int); }
interface DerivA_1 : BaseA { override const(J) test(int); }
interface DerivA_2 : BaseA { override J test(int); }
static assert(isCovariantWith!(DerivA_1.test, BaseA.test));
static assert(isCovariantWith!(DerivA_2.test, BaseA.test));
static assert(! isCovariantWith!(BaseA.test, DerivA_1.test));
static assert(! isCovariantWith!(BaseA.test, DerivA_2.test));
static assert(isCovariantWith!(BaseA.test, BaseA.test));
static assert(isCovariantWith!(DerivA_1.test, DerivA_1.test));
static assert(isCovariantWith!(DerivA_2.test, DerivA_2.test));
// scope parameter
interface BaseB { void test( int, int); }
interface DerivB_1 : BaseB { override void test(scope int, int); }
interface DerivB_2 : BaseB { override void test( int, scope int); }
interface DerivB_3 : BaseB { override void test(scope int, scope int); }
static assert(isCovariantWith!(DerivB_1.test, BaseB.test));
static assert(isCovariantWith!(DerivB_2.test, BaseB.test));
static assert(isCovariantWith!(DerivB_3.test, BaseB.test));
static assert(! isCovariantWith!(BaseB.test, DerivB_1.test));
static assert(! isCovariantWith!(BaseB.test, DerivB_2.test));
static assert(! isCovariantWith!(BaseB.test, DerivB_3.test));
// function storage class
interface BaseC { void test() ; }
interface DerivC_1 : BaseC { override void test() const; }
static assert(isCovariantWith!(DerivC_1.test, BaseC.test));
static assert(! isCovariantWith!(BaseC.test, DerivC_1.test));
// increasing safety
interface BaseE { void test() ; }
interface DerivE_1 : BaseE { override void test() @safe ; }
interface DerivE_2 : BaseE { override void test() @trusted; }
static assert(isCovariantWith!(DerivE_1.test, BaseE.test));
static assert(isCovariantWith!(DerivE_2.test, BaseE.test));
static assert(! isCovariantWith!(BaseE.test, DerivE_1.test));
static assert(! isCovariantWith!(BaseE.test, DerivE_2.test));
// @safe and @trusted
interface BaseF
{
void test1() @safe;
void test2() @trusted;
}
interface DerivF : BaseF
{
override void test1() @trusted;
override void test2() @safe;
}
static assert(isCovariantWith!(DerivF.test1, BaseF.test1));
static assert(isCovariantWith!(DerivF.test2, BaseF.test2));
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// isSomething
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
/**
* Detect whether T is a built-in integral type. Types $(D bool), $(D
* char), $(D wchar), and $(D dchar) are not considered integral.
*/
template isIntegral(T)
{
enum bool isIntegral = staticIndexOf!(Unqual!(T), byte,
ubyte, short, ushort, int, uint, long, ulong) >= 0;
}
unittest
{
static assert(isIntegral!(byte));
static assert(isIntegral!(const(byte)));
static assert(isIntegral!(immutable(byte)));
static assert(isIntegral!(shared(byte)));
static assert(isIntegral!(shared(const(byte))));
static assert(isIntegral!(ubyte));
static assert(isIntegral!(const(ubyte)));
static assert(isIntegral!(immutable(ubyte)));
static assert(isIntegral!(shared(ubyte)));
static assert(isIntegral!(shared(const(ubyte))));
static assert(isIntegral!(short));
static assert(isIntegral!(const(short)));
static assert(isIntegral!(immutable(short)));
static assert(isIntegral!(shared(short)));
static assert(isIntegral!(shared(const(short))));
static assert(isIntegral!(ushort));
static assert(isIntegral!(const(ushort)));
static assert(isIntegral!(immutable(ushort)));
static assert(isIntegral!(shared(ushort)));
static assert(isIntegral!(shared(const(ushort))));
static assert(isIntegral!(int));
static assert(isIntegral!(const(int)));
static assert(isIntegral!(immutable(int)));
static assert(isIntegral!(shared(int)));
static assert(isIntegral!(shared(const(int))));
static assert(isIntegral!(uint));
static assert(isIntegral!(const(uint)));
static assert(isIntegral!(immutable(uint)));
static assert(isIntegral!(shared(uint)));
static assert(isIntegral!(shared(const(uint))));
static assert(isIntegral!(long));
static assert(isIntegral!(const(long)));
static assert(isIntegral!(immutable(long)));
static assert(isIntegral!(shared(long)));
static assert(isIntegral!(shared(const(long))));
static assert(isIntegral!(ulong));
static assert(isIntegral!(const(ulong)));
static assert(isIntegral!(immutable(ulong)));
static assert(isIntegral!(shared(ulong)));
static assert(isIntegral!(shared(const(ulong))));
static assert(!isIntegral!(float));
}
/**
* Detect whether T is a built-in floating point type.
*/
template isFloatingPoint(T)
{
enum bool isFloatingPoint = staticIndexOf!(Unqual!(T),
float, double, real) >= 0;
}
unittest
{
foreach (F; TypeTuple!(float, double, real))
{
F a = 5.5;
static assert(isFloatingPoint!(typeof(a)));
const F b = 5.5;
static assert(isFloatingPoint!(typeof(b)));
immutable F c = 5.5;
static assert(isFloatingPoint!(typeof(c)));
}
foreach (T; TypeTuple!(int, long, char))
{
T a;
static assert(!isFloatingPoint!(typeof(a)));
const T b = 0;
static assert(!isFloatingPoint!(typeof(b)));
immutable T c = 0;
static assert(!isFloatingPoint!(typeof(c)));
}
}
/**
Detect whether T is a built-in numeric type (integral or floating
point).
*/
template isNumeric(T)
{
enum bool isNumeric = isIntegral!(T) || isFloatingPoint!(T);
}
/**
Detect whether $(D T) is a built-in unsigned numeric type.
*/
template isUnsigned(T)
{
enum bool isUnsigned = staticIndexOf!(Unqual!T,
ubyte, ushort, uint, ulong) >= 0;
}
/**
Detect whether $(D T) is a built-in signed numeric type.
*/
template isSigned(T)
{
enum bool isSigned = staticIndexOf!(Unqual!T,
byte, short, int, long, float, double, real) >= 0;
}
/**
Detect whether T is one of the built-in string types
*/
template isSomeString(T)
{
enum isSomeString = isNarrowString!T || is(T : const(dchar[]));
}
unittest
{
static assert(!isSomeString!(int));
static assert(!isSomeString!(int[]));
static assert(!isSomeString!(byte[]));
static assert(isSomeString!(char[]));
static assert(isSomeString!(dchar[]));
static assert(isSomeString!(string));
static assert(isSomeString!(wstring));
static assert(isSomeString!(dstring));
static assert(isSomeString!(char[4]));
}
template isNarrowString(T)
{
enum isNarrowString = is(T : const(char[])) || is(T : const(wchar[]));
}
unittest
{
static assert(!isNarrowString!(int));
static assert(!isNarrowString!(int[]));
static assert(!isNarrowString!(byte[]));
static assert(isNarrowString!(char[]));
static assert(!isNarrowString!(dchar[]));
static assert(isNarrowString!(string));
static assert(isNarrowString!(wstring));
static assert(!isNarrowString!(dstring));
static assert(isNarrowString!(char[4]));
}
/**
Detect whether T is one of the built-in character types
*/
template isSomeChar(T)
{
enum isSomeChar = staticIndexOf!(Unqual!T, char, wchar, dchar) >= 0;
}
unittest
{
static assert(!isSomeChar!(int));
static assert(!isSomeChar!(int));
static assert(!isSomeChar!(byte));
static assert(isSomeChar!(char));
static assert(isSomeChar!(dchar));
static assert(!isSomeChar!(string));
static assert(!isSomeChar!(wstring));
static assert(!isSomeChar!(dstring));
static assert(!isSomeChar!(char[4]));
static assert(isSomeChar!(immutable(char)));
}
/**
* Detect whether T is an associative array type
*/
template isAssociativeArray(T)
{
enum bool isAssociativeArray = __traits(isAssociativeArray, T);
}
unittest
{
struct Foo {
@property uint[] keys() {
return null;
}
@property uint[] values() {
return null;
}
}
static assert(!isAssociativeArray!(Foo));
static assert(!isAssociativeArray!(int));
static assert(!isAssociativeArray!(int[]));
static assert(isAssociativeArray!(int[int]));
static assert(isAssociativeArray!(int[string]));
static assert(isAssociativeArray!(immutable(char[5])[int]));
}
/**
* Detect whether type T is a static array.
*/
template isStaticArray(T : U[N], U, size_t N)
{
enum bool isStaticArray = true;
}
template isStaticArray(T)
{
enum bool isStaticArray = false;
}
unittest
{
static assert (isStaticArray!(int[51]));
static assert (isStaticArray!(int[][2]));
static assert (isStaticArray!(char[][int][11]));
static assert (!isStaticArray!(const(int)[]));
static assert (!isStaticArray!(immutable(int)[]));
static assert (!isStaticArray!(const(int)[4][]));
static assert (!isStaticArray!(int[]));
static assert (!isStaticArray!(int[char]));
static assert (!isStaticArray!(int[1][]));
static assert (isStaticArray!(immutable char[13u]));
static assert (isStaticArray!(const(real)[1]));
static assert (isStaticArray!(const(real)[1][1]));
static assert (isStaticArray!(void[0]));
static assert (!isStaticArray!(int[int]));
static assert (!isStaticArray!(int));
}
/**
* Detect whether type T is a dynamic array.
*/
template isDynamicArray(T, U = void)
{
enum bool isDynamicArray = false;
}
template isDynamicArray(T : U[], U)
{
enum bool isDynamicArray = !isStaticArray!(T);
}
unittest
{
static assert(isDynamicArray!(int[]));
static assert(!isDynamicArray!(int[5]));
}
/**
* Detect whether type T is an array.
*/
template isArray(T)
{
enum bool isArray = isStaticArray!(T) || isDynamicArray!(T);
}
unittest
{
static assert(isArray!(int[]));
static assert(isArray!(int[5]));
static assert(!isArray!(uint));
static assert(!isArray!(uint[uint]));
static assert(isArray!(void[]));
}
/**
* Detect whether type $(D T) is a pointer.
*/
template isPointer(T)
{
static if (is(T P == U*, U))
{
enum bool isPointer = true;
}
else
{
enum bool isPointer = false;
}
}
unittest
{
static assert(isPointer!(int*));
static assert(!isPointer!(uint));
static assert(!isPointer!(uint[uint]));
static assert(!isPointer!(char[]));
static assert(isPointer!(void*));
}
/**
Returns the target type of a pointer.
*/
template pointerTarget(T : T*) {
alias T pointerTarget;
}
unittest {
static assert(is(pointerTarget!(int*) == int));
static assert(!is(pointerTarget!int));
static assert(is(pointerTarget!(long*) == long));
}
/**
* Returns $(D true) if T can be iterated over using a $(D foreach) loop with
* a single loop variable of automatically inferred type, regardless of how
* the $(D foreach) loop is implemented. This includes ranges, structs/classes
* that define $(D opApply) with a single loop variable, and builtin dynamic,
* static and associative arrays.
*/
template isIterable(T)
{
static if (is(typeof({foreach(elem; T.init) {}}))) {
enum bool isIterable = true;
} else {
enum bool isIterable = false;
}
}
unittest {
struct OpApply
{
int opApply(int delegate(ref uint) dg) { assert(0); }
}
struct Range
{
@property uint front() { assert(0); }
void popFront() { assert(0); }
enum bool empty = false;
}
static assert(isIterable!(uint[]));
static assert(!isIterable!(uint));
static assert(isIterable!(OpApply));
static assert(isIterable!(uint[string]));
static assert(isIterable!(Range));
}
/*
* Returns true if T is not const or immutable. Note that isMutable is true for
* string, or immutable(char)[], because the 'head' is mutable.
*/
template isMutable(T)
{
enum isMutable = !is(T == const) && !is(T == immutable);
}
unittest
{
static assert(isMutable!int);
static assert(isMutable!string);
static assert(isMutable!(shared int));
static assert(isMutable!(shared const(int)[]));
static assert(!isMutable!(const int));
static assert(!isMutable!(shared(const int)));
static assert(!isMutable!(immutable string));
}
/**
* Tells whether the tuple T is an expression tuple.
*/
template isExpressionTuple(T ...)
{
static if (T.length > 0)
enum bool isExpressionTuple =
!is(T[0]) && __traits(compiles, { auto ex = T[0]; }) &&
isExpressionTuple!(T[1 .. $]);
else
enum bool isExpressionTuple = true; // default
}
unittest
{
void foo();
static int bar() { return 42; }
enum aa = [ 1: -1 ];
alias int myint;
static assert(isExpressionTuple!(42));
static assert(isExpressionTuple!(aa));
static assert(isExpressionTuple!("cattywampus", 2.7, aa));
static assert(isExpressionTuple!(bar()));
static assert(! isExpressionTuple!(isExpressionTuple));
static assert(! isExpressionTuple!(foo));
static assert(! isExpressionTuple!( (a) { } ));
static assert(! isExpressionTuple!(int));
static assert(! isExpressionTuple!(myint));
}
/**
Detect whether tuple $(D T) is a type tuple.
*/
template isTypeTuple(T...)
{
static if (T.length > 0)
enum bool isTypeTuple = is(T[0]) && isTypeTuple!(T[1 .. $]);
else
enum bool isTypeTuple = true; // default
}
unittest
{
class C {}
void func(int) {}
auto c = new C;
enum CONST = 42;
static assert(isTypeTuple!(int));
static assert(isTypeTuple!(string));
static assert(isTypeTuple!(C));
static assert(isTypeTuple!(typeof(func)));
static assert(isTypeTuple!(int, char, double));
static assert(! isTypeTuple!(c));
static assert(! isTypeTuple!(isTypeTuple));
static assert(! isTypeTuple!(CONST));
}
/**
Detect whether symbol or type $(D T) is a function pointer.
*/
template isFunctionPointer(T...)
if (T.length == 1)
{
static if (is(T[0] U) || is(typeof(T[0]) U))
{
static if (is(U F : F*) && is(F == function))
enum bool isFunctionPointer = true;
else
enum bool isFunctionPointer = false;
}
else
enum bool isFunctionPointer = false;
}
unittest
{
static void foo() {}
void bar() {}
auto fpfoo = &foo;
static assert(isFunctionPointer!(fpfoo));
static assert(isFunctionPointer!(void function()));
auto dgbar = &bar;
static assert(! isFunctionPointer!(dgbar));
static assert(! isFunctionPointer!(void delegate()));
static assert(! isFunctionPointer!(foo));
static assert(! isFunctionPointer!(bar));
static assert(isFunctionPointer!((int a) {}));
}
/**
Detect whether $(D T) is a delegate.
*/
template isDelegate(T...)
if(T.length == 1)
{
enum bool isDelegate = is(T[0] == delegate);
}
unittest
{
static assert(isDelegate!(void delegate()));
static assert(isDelegate!(uint delegate(uint)));
static assert(isDelegate!(shared uint delegate(uint)));
static assert(!isDelegate!(uint));
static assert(!isDelegate!(void function()));
}
/**
Detect whether symbol or type $(D T) is a function, a function pointer or a delegate.
*/
template isSomeFunction(T...)
if (T.length == 1)
{
static if (is(typeof(& T[0]) U : U*) && is(U == function) || is(typeof(& T[0]) U == delegate))
{
// T is a (nested) function symbol.
enum bool isSomeFunction = true;
}
else static if (is(T[0] W) || is(typeof(T[0]) W))
{
// T is an expression or a type. Take the type of it and examine.
static if (is(W F : F*) && is(F == function))
enum bool isSomeFunction = true; // function pointer
else
enum bool isSomeFunction = is(W == function) || is(W == delegate);
}
else
enum bool isSomeFunction = false;
}
unittest
{
static real func(ref int) { return 0; }
static void prop() @property { }
void nestedFunc() { }
void nestedProp() @property { }
class C
{
real method(ref int) { return 0; }
real prop() @property { return 0; }
}
auto c = new C;
auto fp = &func;
auto dg = &c.method;
real val;
static assert(isSomeFunction!(func));
static assert(isSomeFunction!(prop));
static assert(isSomeFunction!(nestedFunc));
static assert(isSomeFunction!(nestedProp));
static assert(isSomeFunction!(C.method));
static assert(isSomeFunction!(C.prop));
static assert(isSomeFunction!(c.prop));
static assert(isSomeFunction!(c.prop));
static assert(isSomeFunction!(fp));
static assert(isSomeFunction!(dg));
static assert(isSomeFunction!(typeof(func)));
static assert(isSomeFunction!(real function(ref int)));
static assert(isSomeFunction!(real delegate(ref int)));
static assert(! isSomeFunction!(int));
static assert(! isSomeFunction!(val));
static assert(! isSomeFunction!(isSomeFunction));
static assert(isSomeFunction!((int a) { return a; }));
}
/**
Detect whether $(D T) is a callable object, which can be called with the
function call operator $(D $(LPAREN)...$(RPAREN)).
*/
template isCallable(T...)
if (T.length == 1)
{
static if (is(typeof(& T[0].opCall) == delegate))
// T is a object which has a member function opCall().
enum bool isCallable = true;
else static if (is(typeof(& T[0].opCall) V : V*) && is(V == function))
// T is a type which has a static member function opCall().
enum bool isCallable = true;
else
enum bool isCallable = isSomeFunction!(T);
}
unittest
{
interface I { real value() @property; }
struct S { static int opCall(int) { return 0; } }
class C { int opCall(int) { return 0; } }
auto c = new C;
static assert( isCallable!(c));
static assert( isCallable!(S));
static assert( isCallable!(c.opCall));
static assert( isCallable!(I.value));
static assert(!isCallable!(I));
static assert(isCallable!((int a) { return a; }));
}
/**
Exactly the same as the builtin traits:
$(D ___traits(_isAbstractFunction, method)).
*/
template isAbstractFunction(method...)
if (method.length == 1)
{
enum bool isAbstractFunction = __traits(isAbstractFunction, method[0]);
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// General Types
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
/**
Removes all qualifiers, if any, from type $(D T).
Example:
----
static assert(is(Unqual!(int) == int));
static assert(is(Unqual!(const int) == int));
static assert(is(Unqual!(immutable int) == int));
static assert(is(Unqual!(shared int) == int));
static assert(is(Unqual!(shared(const int)) == int));
----
*/
template Unqual(T)
{
version (none) // Error: recursive alias declaration @@@BUG1308@@@
{
static if (is(T U == const U)) alias Unqual!U Unqual;
else static if (is(T U == immutable U)) alias Unqual!U Unqual;
else static if (is(T U == inout U)) alias Unqual!U Unqual;
else static if (is(T U == shared U)) alias Unqual!U Unqual;
else alias T Unqual;
}
else // workaround
{
static if (is(T U == shared(const U))) alias U Unqual;
else static if (is(T U == const U )) alias U Unqual;
else static if (is(T U == immutable U )) alias U Unqual;
else static if (is(T U == inout U )) alias U Unqual;
else static if (is(T U == shared U )) alias U Unqual;
else alias T Unqual;
}
}
unittest
{
static assert(is(Unqual!(int) == int));
static assert(is(Unqual!(const int) == int));
static assert(is(Unqual!(immutable int) == int));
static assert(is(Unqual!(inout int) == int));
static assert(is(Unqual!(shared int) == int));
static assert(is(Unqual!(shared(const int)) == int));
alias immutable(int[]) ImmIntArr;
static assert(is(Unqual!(ImmIntArr) == immutable(int)[]));
}
// [For internal use]
private template ModifyTypePreservingSTC(alias Modifier, T)
{
static if (is(T U == shared(const U))) alias shared(const Modifier!U) ModifyTypePreservingSTC;
else static if (is(T U == const U )) alias const(Modifier!U) ModifyTypePreservingSTC;
else static if (is(T U == immutable U )) alias immutable(Modifier!U) ModifyTypePreservingSTC;
else static if (is(T U == shared U )) alias shared(Modifier!U) ModifyTypePreservingSTC;
else alias Modifier!T ModifyTypePreservingSTC;
}
unittest
{
static assert(is(ModifyTypePreservingSTC!(Intify, const real) == const int));
static assert(is(ModifyTypePreservingSTC!(Intify, immutable real) == immutable int));
static assert(is(ModifyTypePreservingSTC!(Intify, shared real) == shared int));
static assert(is(ModifyTypePreservingSTC!(Intify, shared(const real)) == shared(const int)));
}
version (unittest) private template Intify(T) { alias int Intify; }
/*
*/
template StringTypeOf(T) if (isSomeString!T)
{
alias typeof(T.init[]) StringTypeOf;
}
unittest
{
foreach (Ch; TypeTuple!(char, wchar, dchar))
{
foreach (Char; TypeTuple!(Ch, const(Ch), immutable(Ch)))
{
foreach (Str; TypeTuple!(Char[], const(Char)[], immutable(Char)[]))
{
class C(Str) { Str val; alias val this; }
struct S(Str) { Str val; alias val this; }
static assert(is(StringTypeOf!(C!Str) == Str));
static assert(is(StringTypeOf!(S!Str) == Str));
}
}
}
}
/**
Returns the inferred type of the loop variable when a variable of type T
is iterated over using a $(D foreach) loop with a single loop variable and
automatically inferred return type. Note that this may not be the same as
$(D std.range.ElementType!(Range)) in the case of narrow strings, or if T
has both opApply and a range interface.
*/
template ForeachType(T)
{
alias ReturnType!(typeof(
{
foreach(elem; T.init) {
return elem;
}
assert(0);
})) ForeachType;
}
unittest
{
static assert(is(ForeachType!(uint[]) == uint));
static assert(is(ForeachType!(string) == immutable(char)));
static assert(is(ForeachType!(string[string]) == string));
}
/**
Strips off all $(D typedef)s (including $(D enum) ones) from type $(D T).
Example:
--------------------
enum E : int { a }
typedef E F;
typedef const F G;
static assert(is(OriginalType!G == const int));
--------------------
*/
template OriginalType(T)
{
alias ModifyTypePreservingSTC!(OriginalTypeImpl, T) OriginalType;
}
private template OriginalTypeImpl(T)
{
static if (is(T U == typedef)) alias OriginalType!U OriginalTypeImpl;
else static if (is(T U == enum)) alias OriginalType!U OriginalTypeImpl;
else alias T OriginalTypeImpl;
}
unittest
{
//typedef real T;
//typedef T U;
//enum V : U { a }
//static assert(is(OriginalType!T == real));
//static assert(is(OriginalType!U == real));
//static assert(is(OriginalType!V == real));
enum E : real { a }
enum F : E { a = E.a }
//typedef const F G;
static assert(is(OriginalType!E == real));
static assert(is(OriginalType!F == real));
//static assert(is(OriginalType!G == const real));
}
/**
* Returns the corresponding unsigned type for T. T must be a numeric
* integral type, otherwise a compile-time error occurs.
*/
template Unsigned(T)
{
alias ModifyTypePreservingSTC!(UnsignedImpl, OriginalType!T) Unsigned;
}
private template UnsignedImpl(T)
{
static if (isUnsigned!(T)) alias T UnsignedImpl;
else static if (is(T == byte)) alias ubyte UnsignedImpl;
else static if (is(T == short)) alias ushort UnsignedImpl;
else static if (is(T == int)) alias uint UnsignedImpl;
else static if (is(T == long)) alias ulong UnsignedImpl;
else static assert(false, "Type " ~ T.stringof
~ " does not have an Unsigned counterpart");
}
unittest
{
alias Unsigned!(int) U;
assert(is(U == uint));
alias Unsigned!(const(int)) U1;
assert(is(U1 == const(uint)), U1.stringof);
alias Unsigned!(immutable(int)) U2;
assert(is(U2 == immutable(uint)), U2.stringof);
//struct S {}
//alias Unsigned!(S) U2;
//alias Unsigned!(double) U3;
}
/**
Returns the largest type, i.e. T such that T.sizeof is the largest. If more
than one type is of the same size, the leftmost argument of these in will be
returned.
*/
template Largest(T...) if(T.length >= 1) {
static if(T.length == 1) {
alias T[0] Largest;
} static if(T.length == 2) {
static if(T[0].sizeof >= T[1].sizeof) {
alias T[0] Largest;
} else {
alias T[1] Largest;
}
} else {
alias Largest!(Largest!(T[0], T[1]), T[2..$]) Largest;
}
}
unittest {
static assert(is(Largest!(uint, ubyte, ulong, real) == real));
static assert(is(Largest!(ulong, double) == ulong));
static assert(is(Largest!(double, ulong) == double));
static assert(is(Largest!(uint, byte, double, short) == double));
}
/**
Returns the corresponding signed type for T. T must be a numeric integral type,
otherwise a compile-time error occurs.
*/
template Signed(T)
{
alias ModifyTypePreservingSTC!(SignedImpl, OriginalType!T) Signed;
}
private template SignedImpl(T)
{
static if (isSigned!(T)) alias T SignedImpl;
else static if (is(T == ubyte)) alias byte SignedImpl;
else static if (is(T == ushort)) alias short SignedImpl;
else static if (is(T == uint)) alias int SignedImpl;
else static if (is(T == ulong)) alias long SignedImpl;
else static assert(false, "Type " ~ T.stringof
~ " does not have an Signed counterpart");
}
unittest
{
alias Signed!(uint) S;
assert(is(S == int));
alias Signed!(const(uint)) S1;
assert(is(S1 == const(int)), S1.stringof);
alias Signed!(immutable(uint)) S2;
assert(is(S2 == immutable(int)), S2.stringof);
}
/**
* Returns the corresponding unsigned value for $(D x), e.g. if $(D x)
* has type $(D int), returns $(D cast(uint) x). The advantage
* compared to the cast is that you do not need to rewrite the cast if
* $(D x) later changes type to e.g. $(D long).
*/
auto unsigned(T)(T x) if (isIntegral!T)
{
static if (is(Unqual!T == byte)) return cast(ubyte) x;
else static if (is(Unqual!T == short)) return cast(ushort) x;
else static if (is(Unqual!T == int)) return cast(uint) x;
else static if (is(Unqual!T == long)) return cast(ulong) x;
else
{
static assert(T.min == 0, "Bug in either unsigned or isIntegral");
return x;
}
}
unittest
{
static assert(is(typeof(unsigned(1 + 1)) == uint));
}
auto unsigned(T)(T x) if (isSomeChar!T)
{
// All characters are unsigned
static assert(T.min == 0);
return x;
}
/**
Returns the most negative value of the numeric type T.
*/
template mostNegative(T)
{
static if (is(typeof(T.min_normal))) enum mostNegative = -T.max;
else static if (T.min == 0) enum byte mostNegative = 0;
else enum mostNegative = T.min;
}
unittest
{
static assert(mostNegative!(float) == -float.max);
static assert(mostNegative!(uint) == 0);
static assert(mostNegative!(long) == long.min);
}
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// Misc.
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
/**
Returns the mangled name of symbol or type $(D sth).
$(D mangledName) is the same as builtin $(D .mangleof) property, except that
the correct names of property functions are obtained.
--------------------
module test;
import std.traits : mangledName;
class C {
int value() @property;
}
pragma(msg, C.value.mangleof); // prints "i"
pragma(msg, mangledName!(C.value)); // prints "_D4test1C5valueMFNdZi"
--------------------
*/
template mangledName(sth...)
if (sth.length == 1)
{
enum string mangledName = removeDummyEnvelope(Dummy!(sth).Hook.mangleof);
}
private template Dummy(T...) { struct Hook {} }
private string removeDummyEnvelope(string s)
{
// remove --> S3std6traits ... Z4Hook
s = s[12 .. $ - 6];
// remove --> DIGIT+ __T5Dummy
foreach (i, c; s)
{
if (c < '0' || '9' < c)
{
s = s[i .. $];
break;
}
}
s = s[9 .. $]; // __T5Dummy
// remove --> T | V | S
immutable kind = s[0];
s = s[1 .. $];
if (kind == 'S') // it's a symbol
{
/*
* The mangled symbol name is packed in LName --> Number Name. Here
* we are chopping off the useless preceding Number, which is the
* length of Name in decimal notation.
*
* NOTE: n = m + Log(m) + 1; n = LName.length, m = Name.length.
*/
immutable n = s.length;
size_t m_upb = 10;
foreach (k; 1 .. 5) // k = Log(m_upb)
{
if (n < m_upb + k + 1)
{
// Now m_upb/10 <= m < m_upb; hence k = Log(m) + 1.
s = s[k .. $];
break;
}
m_upb *= 10;
}
}
return s;
}
unittest
{
//typedef int MyInt;
//MyInt test() { return 0; }
class C { int value() @property { return 0; } }
static assert(mangledName!(int) == int.mangleof);
static assert(mangledName!(C) == C.mangleof);
//static assert(mangledName!(MyInt)[$ - 7 .. $] == "T5MyInt"); // XXX depends on bug 4237
//static assert(mangledName!(test)[$ - 7 .. $] == "T5MyInt");
static assert(mangledName!(C.value)[$ - 12 .. $] == "5valueMFNdZi");
static assert(mangledName!(mangledName) == "3std6traits11mangledName");
static assert(mangledName!(removeDummyEnvelope) ==
"_D3std6traits19removeDummyEnvelopeFAyaZAya");
int x;
static assert(mangledName!((int a) { return a+x; })[$ - 9 .. $] == "MFNbNfiZi"); // nothrow safe
}
/*
workaround for @@@BUG2997@@@ "allMembers does not return interface members"
*/
package template traits_allMembers(Agg)
{
static if (is(Agg == class) || is(Agg == interface))
alias NoDuplicates!( __traits(allMembers, Agg),
traits_allMembers_ifaces!(InterfacesTuple!(Agg)) )
traits_allMembers;
else
alias TypeTuple!(__traits(allMembers, Agg)) traits_allMembers;
}
private template traits_allMembers_ifaces(I...)
{
static if (I.length > 0)
alias TypeTuple!( __traits(allMembers, I[0]),
traits_allMembers_ifaces!(I[1 .. $]) )
traits_allMembers_ifaces;
else
alias TypeTuple!() traits_allMembers_ifaces;
}
unittest
{
interface I { void test(); }
interface J : I { }
interface K : J { }
alias traits_allMembers!(K) names;
static assert(names.length == 1);
static assert(names[0] == "test");
}
// XXX Select & select should go to another module. (functional or algorithm?)
/**
Aliases itself to $(D T) if the boolean $(D condition) is $(D true)
and to $(D F) otherwise.
Example:
----
alias Select!(size_t.sizeof == 4, int, long) Int;
----
*/
template Select(bool condition, T, F)
{
static if (condition) alias T Select;
else alias F Select;
}
unittest
{
static assert(is(Select!(true, int, long) == int));
static assert(is(Select!(false, int, long) == long));
}
/**
If $(D cond) is $(D true), returns $(D a) without evaluating $(D
b). Otherwise, returns $(D b) without evaluating $(D a).
*/
A select(bool cond : true, A, B)(A a, lazy B b) { return a; }
/// Ditto
B select(bool cond : false, A, B)(lazy A a, B b) { return b; }
unittest
{
real pleasecallme() { return 0; }
int dontcallme() { assert(0); }
auto a = select!true(pleasecallme(), dontcallme());
auto b = select!false(dontcallme(), pleasecallme());
static assert(is(typeof(a) == real));
static assert(is(typeof(b) == real));
}
| D |
instance Mod_1200_SLD_Soeldner_NW (Npc_Default)
{
// ------ NSC ------
name = "Hock";
guild = GIL_mil;
id = 1200;
voice = 34;
flags = 2; //NPC_FLAG_IMMORTAL oder 0
npctype = NPCTYPE_MAIN;
// ------ Attribute ------
B_SetAttributesToChapter (self, 4); //setzt Attribute und LEVEL entsprechend dem angegebenen Kapitel (1-6)
// ------ Kampf-Taktik ------
fight_tactic = FAI_HUMAN_STRONG; // MASTER / STRONG / COWARD
// ------ Equippte Waffen ------
EquipItem (self, ItMw_GrobesKurzschwert);
EquipItem (self, ItRw_Sld_Bow);
// ------ Inventory ------
B_CreateAmbientInv (self);
// ------ visuals ------ //Muss NACH Attributen kommen, weil in B_SetNpcVisual die Breite abh. v. STR skaliert wird
B_SetNpcVisual (self, MALE, "Hum_Head_Bald", Face_N_Normal05, BodyTex_N, ITAR_SLD_L);
Mdl_SetModelFatness (self, 0);
Mdl_ApplyOverlayMds (self, "Humans_Relaxed.mds"); // Tired / Militia / Mage / Arrogance / Relaxed
// ------ NSC-relevante Talente vergeben ------
B_GiveNpcTalents (self);
// ------ Kampf-Talente ------ //Der enthaltene B_AddFightSkill setzt Talent-Ani abhängig von TrefferChance% - alle Kampftalente werden gleichhoch gesetzt
B_SetFightSkills (self, 50); //Grenzen für Talent-Level liegen bei 30 und 60
// ------ TA anmelden ------
daily_routine = Rtn_Start_1200;
};
FUNC VOID Rtn_Start_1200 ()
{
TA_Sit_Campfire (08,00,22,00,"NW_BIGFARM_VORPOSTEN1_01");
TA_Sit_Campfire (22,00,08,00,"NW_BIGFARM_VORPOSTEN1_01");
};
FUNC VOID Rtn_Dung_1200 ()
{
TA_Sleep (07,30,23,30,"NW_BIGFARM_HOUSE_08");
TA_Sleep (23,30,07,30,"NW_BIGFARM_HOUSE_08");
};
FUNC VOID Rtn_Hexen_1200()
{
TA_Stand_WP (08,00,20,00,"NW_BIGFARM_CROSS");
TA_Stand_WP (20,00,08,00,"NW_BIGFARM_CROSS");
};
FUNC VOID Rtn_Diener_1200()
{
TA_RunToWP (08,00,20,00,"NW_FARM4_WOOD_MONSTER_MORE_03");
TA_RunToWP (20,00,08,00,"NW_FARM4_WOOD_MONSTER_MORE_03");
};
FUNC VOID Rtn_Knucker_1200()
{
TA_RunToWP (08,00,20,00,"WP_DRAGON_KNUCKERUNDCO_SMALLTALK");
TA_RunToWP (20,00,08,00,"WP_DRAGON_KNUCKERUNDCO_SMALLTALK");
};
FUNC VOID Rtn_Daemonisch_1200()
{
TA_Stand_Eating (08,00,20,00,"NW_BIGFARM_KITCHEN_09");
TA_Stand_Eating (20,00,08,00,"NW_BIGFARM_KITCHEN_09");
};
FUNC VOID Rtn_Weg_1200()
{
TA_RunToWP (08,00,20,00,"NW_PASS_ORKS_18");
TA_RunToWP (20,00,08,00,"NW_PASS_ORKS_18");
};
FUNC VOID Rtn_Harad_1200()
{
TA_RunToWP (08,00,20,00,"NW_BIGFARM_PATH_04");
TA_RunToWP (20,00,08,00,"NW_BIGFARM_PATH_04");
}; | D |
void main() {
auto S = rs;
string s;
foreach(i; 1..6) {
s ~= "hi";
if(S == s) {
writeln("Yes");
return;
}
}
writeln("No");
}
// ===================================
import std.stdio;
import std.string;
import std.functional;
import std.algorithm;
import std.range;
import std.traits;
import std.math;
import std.container;
import std.bigint;
import std.numeric;
import std.conv;
import std.typecons;
import std.uni;
import std.ascii;
import std.bitmanip;
import core.bitop;
T readAs(T)() if (isBasicType!T) {
return readln.chomp.to!T;
}
T readAs(T)() if (isArray!T) {
return readln.split.to!T;
}
T[][] readMatrix(T)(uint height, uint width) if (!isSomeChar!T) {
auto res = new T[][](height, width);
foreach(i; 0..height) {
res[i] = readAs!(T[]);
}
return res;
}
T[][] readMatrix(T)(uint height, uint width) if (isSomeChar!T) {
auto res = new T[][](height, width);
foreach(i; 0..height) {
auto s = rs;
foreach(j; 0..width) res[i][j] = s[j].to!T;
}
return res;
}
int ri() {
return readAs!int;
}
double rd() {
return readAs!double;
}
string rs() {
return readln.chomp;
} | D |
instance STRF_1136_Addon_Sklave (Npc_Default)
{
// ------ NSC ------
name = NAME_Addon_Sklave;
guild = GIL_BDT;
id = 1136;
voice = 3;
flags = 0;
npctype = NPCTYPE_BL_AMBIENT;
//aivars
aivar[AIV_NoFightParker] = TRUE;
aivar[AIV_IgnoresArmor] = TRUE;
// ------ Attribute ------
B_SetAttributesToChapter (self, 2);
// ------ Kampf-Taktik ------
fight_tactic = FAI_HUMAN_COWARD;
// ------ Inventory ------
B_CreateAmbientInv (self);
// ------ visuals ------
B_SetNpcVisual (self, MALE, "Hum_Head_Psionic", Face_N_Weak_Asghan, BodyTex_N, ITAR_Prisoner);
Mdl_SetModelFatness (self, -1);
Mdl_ApplyOverlayMds (self, "Humans_Tired.mds");
// ------ NSC-relevante Talente vergeben ------
B_GiveNpcTalents (self);
// ------ Kampf-Talente ------
B_SetFightSkills (self, 10);
// ------ TA anmelden ------
daily_routine = Rtn_Start_1136;
};
FUNC VOID Rtn_Start_1136 ()
{
TA_Pick_Ore (08,00,23,00,"ADW_MINE_PICK_05");
TA_Pick_Ore (23,00,08,00,"ADW_MINE_PICK_05");
};
| D |
/Users/zebra/Zla/Dev/Tests/ken_git_space/Events-Explorer/Events\ Explorer/Build/Intermediates.noindex/Alamofire.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/AlamofireExtended.o : /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/MultipartFormData.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/MultipartUpload.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/AlamofireExtended.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Protected.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/HTTPMethod.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/URLConvertible+URLRequestConvertible.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Combine.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/DispatchQueue+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/OperationQueue+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/StringEncoding+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/URLSessionConfiguration+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Result+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/URLRequest+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Response.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/SessionDelegate.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/ParameterEncoding.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Session.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Validation.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/ServerTrustEvaluation.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/ResponseSerialization.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/RequestTaskMap.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/URLEncodedFormEncoder.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/ParameterEncoder.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/NetworkReachabilityManager.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/CachedResponseHandler.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/RedirectHandler.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/AFError.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/EventMonitor.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/AuthenticationInterceptor.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/RequestInterceptor.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Notifications.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/HTTPHeaders.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Request.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/RetryPolicy.swift /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/Swift.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/ObjectiveC.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Dispatch.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Darwin.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Foundation.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/CoreFoundation.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/CoreGraphics.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Swift.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/SwiftOnoneSupport.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/include/mach-o/dyld.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/include/mach-o/compact_unwind_encoding.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/zebra/Zla/Dev/Tests/ken_git_space/Events-Explorer/Events\ Explorer/Build/Intermediates.noindex/Alamofire.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/AlamofireExtended~partial.swiftmodule : /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/MultipartFormData.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/MultipartUpload.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/AlamofireExtended.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Protected.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/HTTPMethod.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/URLConvertible+URLRequestConvertible.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Combine.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/DispatchQueue+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/OperationQueue+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/StringEncoding+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/URLSessionConfiguration+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Result+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/URLRequest+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Response.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/SessionDelegate.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/ParameterEncoding.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Session.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Validation.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/ServerTrustEvaluation.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/ResponseSerialization.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/RequestTaskMap.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/URLEncodedFormEncoder.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/ParameterEncoder.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/NetworkReachabilityManager.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/CachedResponseHandler.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/RedirectHandler.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/AFError.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/EventMonitor.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/AuthenticationInterceptor.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/RequestInterceptor.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Notifications.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/HTTPHeaders.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Request.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/RetryPolicy.swift /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/Swift.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/ObjectiveC.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Dispatch.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Darwin.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Foundation.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/CoreFoundation.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/CoreGraphics.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Swift.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/SwiftOnoneSupport.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/include/mach-o/dyld.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/include/mach-o/compact_unwind_encoding.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/zebra/Zla/Dev/Tests/ken_git_space/Events-Explorer/Events\ Explorer/Build/Intermediates.noindex/Alamofire.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/AlamofireExtended~partial.swiftdoc : /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/MultipartFormData.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/MultipartUpload.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/AlamofireExtended.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Protected.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/HTTPMethod.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/URLConvertible+URLRequestConvertible.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Combine.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/DispatchQueue+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/OperationQueue+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/StringEncoding+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/URLSessionConfiguration+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Result+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/URLRequest+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Response.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/SessionDelegate.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/ParameterEncoding.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Session.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Validation.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/ServerTrustEvaluation.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/ResponseSerialization.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/RequestTaskMap.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/URLEncodedFormEncoder.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/ParameterEncoder.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/NetworkReachabilityManager.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/CachedResponseHandler.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/RedirectHandler.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/AFError.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/EventMonitor.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/AuthenticationInterceptor.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/RequestInterceptor.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Notifications.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/HTTPHeaders.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Request.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/RetryPolicy.swift /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/Swift.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/ObjectiveC.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Dispatch.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Darwin.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Foundation.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/CoreFoundation.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/CoreGraphics.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Swift.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/SwiftOnoneSupport.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/include/mach-o/dyld.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/include/mach-o/compact_unwind_encoding.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/zebra/Zla/Dev/Tests/ken_git_space/Events-Explorer/Events\ Explorer/Build/Intermediates.noindex/Alamofire.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/AlamofireExtended~partial.swiftsourceinfo : /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/MultipartFormData.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/MultipartUpload.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/AlamofireExtended.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Protected.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/HTTPMethod.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/URLConvertible+URLRequestConvertible.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Combine.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/DispatchQueue+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/OperationQueue+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/StringEncoding+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/URLSessionConfiguration+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Result+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/URLRequest+Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Alamofire.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Response.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/SessionDelegate.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/ParameterEncoding.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Session.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Validation.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/ServerTrustEvaluation.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/ResponseSerialization.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/RequestTaskMap.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/URLEncodedFormEncoder.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/ParameterEncoder.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/NetworkReachabilityManager.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/CachedResponseHandler.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/RedirectHandler.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/AFError.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/EventMonitor.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/AuthenticationInterceptor.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/RequestInterceptor.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Notifications.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/HTTPHeaders.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/Request.swift /Users/zebra/Library/Developer/Xcode/DerivedData/Events_Explorer-bqjodyvqcrhghjasuqyfuasrxsdn/SourcePackages/checkouts/Alamofire/Source/RetryPolicy.swift /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/Swift.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/ObjectiveC.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Dispatch.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Darwin.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Foundation.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/CoreFoundation.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/CoreGraphics.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/Swift.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/14.5/SwiftOnoneSupport.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/include/mach-o/dyld.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/include/mach-o/compact_unwind_encoding.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.5.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
| D |
// https://dpaste.dzfl.pl/7a77355acaec
/*
Event Loop would be nices:
* add on idle - runs when nothing else happens
* send messages without a recipient window
* setTimeout
* setInterval
*/
/*
Text layout needs a lot of work. Plain drawText is useful but too
limited. It will need some kind of text context thing which it will
update and you can pass it on and get more details out of it.
It will need a bounding box, a current cursor location that is updated
as drawing continues, and various changable facts (which can also be
changed on the painter i guess) like font, color, size, background,
etc.
We can also fetch the caret location from it somehow.
Should prolly be an overload of drawText
blink taskbar / demand attention cross platform. FlashWindow and demandAttention
WS_EX_NOACTIVATE
WS_CHILD - owner and owned vs parent and child. Does X have something similar?
full screen windows. Can just set the atom on X. Windows will be harder.
moving windows. resizing windows.
hide cursor, capture cursor, change cursor.
REMEMBER: simpledisplay does NOT have to do everything! It just needs to make
sure the pieces are there to do its job easily and make other jobs possible.
*/
/++
simpledisplay.d provides basic cross-platform GUI-related functionality,
including creating windows, drawing on them, working with the clipboard,
timers, OpenGL, and more. However, it does NOT provide high level GUI
widgets. See my minigui.d, an extension to this module, for that
functionality.
simpledisplay provides cross-platform wrapping for Windows and Linux
(and perhaps other OSes that use X11), but also does not prevent you
from using the underlying facilities if you need them. It has a goal
of working efficiently over a remote X link (at least as far as Xlib
reasonably allows.)
simpledisplay depends on [arsd.color|color.d], which should be available from the
same place where you got this file. Other than that, however, it has
very few dependencies and ones that don't come with the OS and/or the
compiler are all opt-in.
simpledisplay.d's home base is on my arsd repo on Github. The file is:
https://github.com/adamdruppe/arsd/blob/master/simpledisplay.d
simpledisplay is basically stable. I plan to refactor the internals,
and may add new features and fix bugs, but It do not expect to
significantly change the API. It has been stable a few years already now.
Installation_instructions:
`simpledisplay.d` does not have any dependencies outside the
operating system and `color.d`, so it should just work most the
time, but there are a few caveats on some systems:
Please note when compiling on Win64, you need to explicitly list
`-Lgdi32.lib -Luser32.lib` on the build command. If you want the Windows
subsystem too, use `-L/subsystem:windows -L/entry:mainCRTStartup`.
On Win32, you can pass `-L/subsystem:windows` if you don't want a
console to be automatically allocated.
On Mac, when compiling with X11, you need XQuartz and -L-L/usr/X11R6/lib passed to dmd. If using the Cocoa implementation on Mac, you need to pass `-L-framework -LCocoa` to dmd.
On Ubuntu, you might need to install X11 development libraries to
successfully link.
$(CONSOLE
$ sudo apt-get install libglc-dev
$ sudo apt-get install libx11-dev
)
Jump_list:
Don't worry, you don't have to read this whole documentation file!
Check out the [#Event-example] and [#Pong-example] to get started quickly.
The main classes you may want to create are [SimpleWindow], [Timer],
[Image], and [Sprite].
The main functions you'll want are [setClipboardText] and [getClipboardText].
There are also platform-specific functions available such as [XDisplayConnection]
and [GetAtom] for X11, among others.
See the examples and topics list below to learn more.
$(H2 About this documentation)
The goal here is to give some complete programs as overview examples first, then a look at each major feature with working examples first, then, finally, the inline class and method list will follow.
Scan for headers for a topic - $(B they will visually stand out) - you're interested in to get started quickly and feel free to copy and paste any example as a starting point for your program. I encourage you to learn the library by experimenting with the examples!
All examples are provided with no copyright restrictions whatsoever. You do not need to credit me or carry any kind of notice with the source if you copy and paste from them.
To get started, download `simpledisplay.d` and `color.d` to a working directory. Copy an example info a file called `example.d` and compile using the command given at the top of each example.
If you need help, email me: destructionator@gmail.com or IRC us, #d on Freenode (I am destructionator or adam_d_ruppe there). If you learn something that isn't documented, I appreciate pull requests on github to this file.
At points, I will talk about implementation details in the documentation. These are sometimes
subject to change, but nevertheless useful to understand what is really going on. You can learn
more about some of the referenced things by searching the web for info about using them from C.
You can always look at the source of simpledisplay.d too for the most authoritative source on
its specific implementation. If you disagree with how I did something, please contact me so we
can discuss it!
Examples:
$(H3 Event-example)
This program creates a window and draws events inside them as they
happen, scrolling the text in the window as needed. Run this program
and experiment to get a feel for where basic input events take place
in the library.
---
// dmd example.d simpledisplay.d color.d
import arsd.simpledisplay;
import std.conv;
void main() {
auto window = new SimpleWindow(Size(500, 500), "Event example - simpledisplay.d");
int y = 0;
void addLine(string text) {
auto painter = window.draw();
if(y + painter.fontHeight >= window.height) {
painter.scrollArea(Point(0, 0), window.width, window.height, 0, painter.fontHeight);
y -= painter.fontHeight;
}
painter.outlineColor = Color.red;
painter.fillColor = Color.black;
painter.drawRectangle(Point(0, y), window.width, painter.fontHeight);
painter.outlineColor = Color.white;
painter.drawText(Point(10, y), text);
y += painter.fontHeight;
}
window.eventLoop(1000,
() {
addLine("Timer went off!");
},
(KeyEvent event) {
addLine(to!string(event));
},
(MouseEvent event) {
addLine(to!string(event));
},
(dchar ch) {
addLine(to!string(ch));
}
);
}
---
If you are interested in more game writing with D, check out my gamehelpers.d which builds upon simpledisplay, and its other stand-alone support modules, simpleaudio.d and joystick.d, too.
This program displays a pie chart. Clicking on a color will increase its share of the pie.
---
---
$(H2 Topics)
$(H3 $(ID topic-windows) Windows)
The [SimpleWindow] class is simpledisplay's flagship feature. It represents a single
window on the user's screen.
You may create multiple windows, if the underlying platform supports it. You may check
`static if(multipleWindowsSupported)` at compile time, or catch exceptions thrown by
SimpleWindow's constructor at runtime to handle those cases.
A single running event loop will handle as many windows as needed.
setEventHandlers function
eventLoop function
draw function
title property
$(H3 $(ID topic-event-loops) Event loops)
The simpledisplay event loop is designed to handle common cases easily while being extensible for more advanced cases, or replaceable by other libraries.
The most common scenario is creating a window, then calling [SimpleWindow.eventLoop|window.eventLoop] when setup is complete. You can pass several handlers to the `eventLoop` method right there:
---
// dmd example.d simpledisplay.d color.d
import arsd.simpledisplay;
void main() {
auto window = new SimpleWindow(200, 200);
window.eventLoop(0,
delegate (dchar) { /* got a character key press */ }
);
}
---
$(TIP If you get a compile error saying "I can't use this event handler", the most common thing in my experience is passing a function instead of a delegate. The simple solution is to use the `delegate` keyword, like I did in the example above.)
On Linux, the event loop is implemented with the `epoll` system call for efficiency an extensibility to other files. On Windows, it runs a traditional `GetMessage` + `DispatchMessage` loop, with a call to `SleepEx` in each iteration to allow the thread to enter an alertable wait state regularly, primarily so Overlapped I/O callbacks will get a chance to run.
On Linux, simpledisplay also supports my [arsd.eventloop] module. Compile your program, including the eventloop.d file, with the `-version=with_eventloop` switch.
It should be possible to integrate simpledisplay with vibe.d as well, though I haven't tried.
$(H3 $(ID topic-notification-areas) Notification area (aka systray) icons)
Notification area icons are currently implemented on X11 and Windows. On X11, it defaults to using `libnotify` to show bubbles, if available, and will do a custom bubble window if not. You can `version=without_libnotify` to avoid this run-time dependency, if you like.
$(H3 $(ID topic-input-handling) Input handling)
There are event handlers for low-level keyboard and mouse events, and higher level handlers for character events.
$(H3 $(ID topic-2d-drawing) 2d Drawing)
To draw on your window, use the [SimpleWindow.draw] method. It returns a [ScreenPainter] structure with drawing methods.
Important: `ScreenPainter` double-buffers and will not actually update the window until its destructor is run. Always ensure the painter instance goes out-of-scope before proceeding. You can do this by calling it inside an event handler, a timer callback, or an small scope inside main. For example:
---
// dmd example.d simpledisplay.d color.d
import arsd.simpledisplay;
void main() {
auto window = new SimpleWindow(200, 200);
{ // introduce sub-scope
auto painter = window.draw(); // begin drawing
/* draw here */
painter.outlineColor = Color.red;
painter.fillColor = Color.black;
painter.drawRectangle(Point(0, 0), 200, 200);
} // end scope, calling `painter`'s destructor, drawing to the screen.
window.eventLoop(0); // handle events
}
---
Painting is done based on two color properties, a pen and a brush.
At this time, the 2d drawing does not support alpha blending. If you need that, use a 2d OpenGL context instead.
FIXME add example of 2d opengl drawing here
$(H3 $(ID topic-3d-drawing) 3d Drawing (or 2d with OpenGL))
simpledisplay can create OpenGL contexts on your window. It works quite differently than 2d drawing.
Note that it is still possible to draw 2d on top of an OpenGL window, using the `draw` method, though I don't recommend it.
To start, you create a [SimpleWindow] with OpenGL enabled by passing the argument [OpenGlOptions.yes] to the constructor.
Next, you set [SimpleWindow.redrawOpenGlScene|window.redrawOpenGlScene] to a delegate which draws your frame.
To force a redraw of the scene, call [SimpleWindow.redrawOpenGlScene|window.redrawOpenGlSceneNow()].
Please note that my experience with OpenGL is very out-of-date, and the bindings in simpledisplay reflect that. If you want to use more modern functions, you may have to define the bindings yourself, or import them from another module. However, the OpenGL context creation done in simpledisplay will work for any version.
This example program will draw a rectangle on your window:
---
// dmd example.d simpledisplay.d color.d
import arsd.simpledisplay;
void main() {
}
---
$(H3 $(ID topic-images) Displaying images)
You can also load PNG images using [arsd.png].
---
// dmd example.d simpledisplay.d color.d png.d
import arsd.simpledisplay;
import arsd.png;
void main() {
auto image = Image.fromMemoryImage(readPng("image.png"));
displayImage(image);
}
---
Compile with `dmd example.d simpledisplay.d png.d`.
If you find an image file which is a valid png that [arsd.png] fails to load, please let me know. In the mean time of fixing the bug, you can probably convert the file into an easier-to-load format. Be sure to turn OFF png interlacing, as that isn't supported. Other things to try would be making the image smaller, or trying 24 bit truecolor mode with an alpha channel.
$(H3 $(ID topic-sprites) Sprites)
The [Sprite] class is used to make images on the display server for fast blitting to screen. This is especially important to use to support fast drawing of repeated images on a remote X11 link.
$(H3 $(ID topic-clipboard) Clipboard)
The free functions [getClipboardText] and [setClipboardText] consist of simpledisplay's cross-platform clipboard support at this time.
It also has helpers for handling X-specific events.
$(H3 $(ID topic-timers) Timers)
There are two timers in simpledisplay: one is the pulse timeout you can set on the call to `window.eventLoop`, and the other is a customizable class, [Timer].
The pulse timeout is used by setting a non-zero interval as the first argument to `eventLoop` function and adding a zero-argument delegate to handle the pulse.
---
import arsd.simpledisplay;
void main() {
auto window = new SimpleWindow(400, 400);
// every 100 ms, it will draw a random line
// on the window.
window.eventLoop(100, {
auto painter = window.draw();
import std.random;
// random color
painter.outlineColor = Color(uniform(0, 256), uniform(0, 256), uniform(0, 256));
// random line
painter.drawLine(
Point(uniform(0, window.width), uniform(0, window.height)),
Point(uniform(0, window.width), uniform(0, window.height)));
});
}
---
The `Timer` class works similarly, but is created separately from the event loop. (It still fires through the event loop, though.) You may make as many instances of `Timer` as you wish.
The pulse timer and instances of the [Timer] class may be combined at will.
---
import arsd.simpledisplay;
void main() {
auto window = new SimpleWindow(400, 400);
auto timer = new Timer(1000, delegate {
auto painter = window.draw();
painter.clear();
});
window.eventLoop(0);
}
---
Timers are currently only implemented on Windows, using `SetTimer` and Linux, using `timerfd_create`. These deliver timeout messages through your application event loop.
$(H3 $(ID topic-os-helpers) OS-specific helpers)
simpledisplay carries a lot of code to help implement itself without extra dependencies, and much of this code is available for you too, so you may extend the functionality yourself.
See also: `xwindows.d` from my github.
$(H3 $(ID topic-os-extension) Extending with OS-specific functionality)
`handleNativeEvent` and `handleNativeGlobalEvent`.
$(H3 $(ID topic-integration) Integration with other libraries)
Integration with a third-party event loop is possible.
On Linux, you might want to support both terminal input and GUI input. You can do this by using simpledisplay together with eventloop.d and terminal.d.
$(H3 $(ID topic-guis) GUI widgets)
simpledisplay does not provide GUI widgets such as text areas, buttons, checkboxes, etc. It only gives basic windows, the ability to draw on it, receive input from it, and access native information for extension. You may write your own gui widgets with these, but you don't have to because I already did for you!
Download `minigui.d` from my github repository and add it to your project. minigui builds these things on top of simpledisplay and offers its own Window class (and subclasses) to use that wrap SimpleWindow, adding a new event and drawing model that is hookable by subwidgets, represented by their own classes.
Migrating to minigui from simpledisplay is often easy though, because they both use the same ScreenPainter API, and the same simpledisplay events are available, if you want them. (Though you may like using the minigui model, especially if you are familiar with writing web apps in the browser with Javascript.)
minigui still needs a lot of work to be finished at this time, but it already offers a number of useful classes.
$(H2 Platform-specific tips and tricks)
Windows_tips:
You can add icons or manifest files to your exe using a resource file.
To create a Windows .ico file, use the gimp or something. I'll write a helper
program later.
Create `yourapp.rc`:
```rc
1 ICON filename.ico
CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST "YourApp.exe.manifest"
```
And `yourapp.exe.manifest`:
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
version="1.0.0.0"
processorArchitecture="*"
name="CompanyName.ProductName.YourApplication"
type="win32"
/>
<description>Your application description here.</description>
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
</assembly>
```
$(H2 $(ID developer-notes) Developer notes)
I don't have a Mac, so that code isn't maintained. I would like to have a Cocoa
implementation though.
The NativeSimpleWindowImplementation and NativeScreenPainterImplementation both
suck. If I was rewriting it, I wouldn't do it that way again.
This file must not have any more required dependencies. If you need bindings, add
them right to this file. Once it gets into druntime and is there for a while, remove
bindings from here to avoid conflicts (or put them in an appropriate version block
so it continues to just work on old dmd), but wait a couple releases before making the
transition so this module remains usable with older versions of dmd.
You may have optional dependencies if needed by putting them in version blocks or
template functions. You may also extend the module with other modules with UFCS without
actually editing this - that is nice to do if you can.
Try to make functions work the same way across operating systems. I typically make
it thinly wrap Windows, then emulate that on Linux.
A goal of this is to keep a gui hello world to less than 250 KB. This means avoiding
Phobos! So try to avoid it.
See more comments throughout the source.
I realize this file is fairly large, but over half that is just bindings at the bottom
or documentation at the top. Some of the classes are a bit big too, but hopefully easy
to understand. I suggest you jump around the source by looking for a particular
declaration you're interested in, like `class SimpleWindow` using your editor's search
function, then look at one piece at a time.
Authors: Adam D. Ruppe with the help of others. If you need help, please email me with
destructionator@gmail.com or find me on IRC. Our channel is #d on Freenode. I go by
Destructionator or adam_d_ruppe, depending on which computer I'm logged into.
I live in the eastern United States, so I will most likely not be around at night in
that US east timezone.
License: Copyright Adam D. Ruppe, 2011-2017. Released under the Boost Software License.
Building documentation: You may wish to use the `arsd.ddoc` file from my github with
building the documentation for simpledisplay yourself. It will give it a bit more style.
Simply download the arsd.ddoc file and add it to your compile command when building docs.
`dmd -c simpledisplay.d color.d -D arsd.ddoc`
+/
module arsd.simpledisplay;
// FIXME: tetris demo
// FIXME: space invaders demo
// FIXME: asteroids demo
/++ $(ID Pong-example)
$(H3 Pong)
This program creates a little Pong-like game. Player one is controlled
with the keyboard. Player two is controlled with the mouse. It demos
the pulse timer, event handling, and some basic drawing.
+/
unittest {
// dmd example.d simpledisplay.d color.d
import arsd.simpledisplay;
enum paddleMovementSpeed = 8;
enum paddleHeight = 48;
void main() {
auto window = new SimpleWindow(600, 400, "Pong game!");
int playerOnePosition, playerTwoPosition;
int playerOneMovement, playerTwoMovement;
int playerOneScore, playerTwoScore;
int ballX, ballY;
int ballDx, ballDy;
void serve() {
import std.random;
ballX = window.width / 2;
ballY = window.height / 2;
ballDx = uniform(-4, 4) * 3;
ballDy = uniform(-4, 4) * 3;
if(ballDx == 0)
ballDx = uniform(0, 2) == 0 ? 3 : -3;
}
serve();
window.eventLoop(50, // set a 50 ms timer pulls
// This runs once per timer pulse
delegate () {
auto painter = window.draw();
painter.clear();
// Update everyone's motion
playerOnePosition += playerOneMovement;
playerTwoPosition += playerTwoMovement;
ballX += ballDx;
ballY += ballDy;
// Bounce off the top and bottom edges of the window
if(ballY + 7 >= window.height)
ballDy = -ballDy;
if(ballY - 8 <= 0)
ballDy = -ballDy;
// Bounce off the paddle, if it is in position
if(ballX - 8 <= 16) {
if(ballY + 7 > playerOnePosition && ballY - 8 < playerOnePosition + paddleHeight) {
ballDx = -ballDx + 1; // add some speed to keep it interesting
ballDy += playerOneMovement; // and y movement based on your controls too
ballX = 24; // move it past the paddle so it doesn't wiggle inside
} else {
// Missed it
playerTwoScore ++;
serve();
}
}
if(ballX + 7 >= window.width - 16) { // do the same thing but for player 1
if(ballY + 7 > playerTwoPosition && ballY - 8 < playerTwoPosition + paddleHeight) {
ballDx = -ballDx - 1;
ballDy += playerTwoMovement;
ballX = window.width - 24;
} else {
// Missed it
playerOneScore ++;
serve();
}
}
// Draw the paddles
painter.outlineColor = Color.black;
painter.drawLine(Point(16, playerOnePosition), Point(16, playerOnePosition + paddleHeight));
painter.drawLine(Point(window.width - 16, playerTwoPosition), Point(window.width - 16, playerTwoPosition + paddleHeight));
// Draw the ball
painter.fillColor = Color.red;
painter.outlineColor = Color.yellow;
painter.drawEllipse(Point(ballX - 8, ballY - 8), Point(ballX + 7, ballY + 7));
// Draw the score
painter.outlineColor = Color.blue;
import std.conv;
painter.drawText(Point(64, 4), to!string(playerOneScore));
painter.drawText(Point(window.width - 64, 4), to!string(playerTwoScore));
},
delegate (KeyEvent event) {
// Player 1's controls are the arrow keys on the keyboard
if(event.key == Key.Down)
playerOneMovement = event.pressed ? paddleMovementSpeed : 0;
if(event.key == Key.Up)
playerOneMovement = event.pressed ? -paddleMovementSpeed : 0;
},
delegate (MouseEvent event) {
// Player 2's controls are mouse movement while the left button is held down
if(event.type == MouseEventType.motion && (event.modifierState & ModifierState.leftButtonDown)) {
if(event.dy > 0)
playerTwoMovement = paddleMovementSpeed;
else if(event.dy < 0)
playerTwoMovement = -paddleMovementSpeed;
} else {
playerTwoMovement = 0;
}
}
);
}
}
/++ $(ID example-minesweeper)
This minesweeper demo shows how we can implement another classic
game with simpledisplay and shows some mouse input and basic output
code.
+/
unittest {
import arsd.simpledisplay;
enum GameSquare {
mine = 0,
clear,
m1, m2, m3, m4, m5, m6, m7, m8
}
enum UserSquare {
unknown,
revealed,
flagged,
questioned
}
enum GameState {
inProgress,
lose,
win
}
GameSquare[] board;
UserSquare[] userState;
GameState gameState;
int boardWidth;
int boardHeight;
bool isMine(int x, int y) {
if(x < 0 || y < 0 || x >= boardWidth || y >= boardHeight)
return false;
return board[y * boardWidth + x] == GameSquare.mine;
}
GameState reveal(int x, int y) {
if(board[y * boardWidth + x] == GameSquare.clear) {
floodFill(userState, boardWidth, boardHeight,
UserSquare.unknown, UserSquare.revealed,
x, y,
(x, y) {
if(board[y * boardWidth + x] == GameSquare.clear)
return true;
else {
userState[y * boardWidth + x] = UserSquare.revealed;
return false;
}
});
} else {
userState[y * boardWidth + x] = UserSquare.revealed;
if(isMine(x, y))
return GameState.lose;
}
foreach(state; userState) {
if(state == UserSquare.unknown || state == UserSquare.questioned)
return GameState.inProgress;
}
return GameState.win;
}
void initializeBoard(int width, int height, int numberOfMines) {
boardWidth = width;
boardHeight = height;
board.length = width * height;
userState.length = width * height;
userState[] = UserSquare.unknown;
import std.algorithm, std.random, std.range;
board[] = GameSquare.clear;
foreach(minePosition; randomSample(iota(0, board.length), numberOfMines))
board[minePosition] = GameSquare.mine;
int x;
int y;
foreach(idx, ref square; board) {
if(square == GameSquare.clear) {
int danger = 0;
danger += isMine(x-1, y-1)?1:0;
danger += isMine(x-1, y)?1:0;
danger += isMine(x-1, y+1)?1:0;
danger += isMine(x, y-1)?1:0;
danger += isMine(x, y+1)?1:0;
danger += isMine(x+1, y-1)?1:0;
danger += isMine(x+1, y)?1:0;
danger += isMine(x+1, y+1)?1:0;
square = cast(GameSquare) (danger + 1);
}
x++;
if(x == width) {
x = 0;
y++;
}
}
}
void redraw(SimpleWindow window) {
import std.conv;
auto painter = window.draw();
painter.clear();
final switch(gameState) with(GameState) {
case inProgress:
break;
case win:
painter.fillColor = Color.green;
painter.drawRectangle(Point(0, 0), window.width, window.height);
return;
case lose:
painter.fillColor = Color.red;
painter.drawRectangle(Point(0, 0), window.width, window.height);
return;
}
int x = 0;
int y = 0;
foreach(idx, square; board) {
auto state = userState[idx];
final switch(state) with(UserSquare) {
case unknown:
painter.outlineColor = Color.black;
painter.fillColor = Color(128,128,128);
painter.drawRectangle(
Point(x * 20, y * 20),
20, 20
);
break;
case revealed:
if(square == GameSquare.clear) {
painter.outlineColor = Color.white;
painter.fillColor = Color.white;
painter.drawRectangle(
Point(x * 20, y * 20),
20, 20
);
} else {
painter.outlineColor = Color.black;
painter.fillColor = Color.white;
painter.drawText(
Point(x * 20, y * 20),
to!string(square)[1..2],
Point(x * 20 + 20, y * 20 + 20),
TextAlignment.Center | TextAlignment.VerticalCenter);
}
break;
case flagged:
painter.outlineColor = Color.black;
painter.fillColor = Color.red;
painter.drawRectangle(
Point(x * 20, y * 20),
20, 20
);
break;
case questioned:
painter.outlineColor = Color.black;
painter.fillColor = Color.yellow;
painter.drawRectangle(
Point(x * 20, y * 20),
20, 20
);
break;
}
x++;
if(x == boardWidth) {
x = 0;
y++;
}
}
}
void main() {
auto window = new SimpleWindow(200, 200);
initializeBoard(10, 10, 10);
redraw(window);
window.eventLoop(0,
delegate (MouseEvent me) {
if(me.type != MouseEventType.buttonPressed)
return;
auto x = me.x / 20;
auto y = me.y / 20;
if(x >= 0 && x < boardWidth && y >= 0 && y < boardHeight) {
if(me.button == MouseButton.left) {
gameState = reveal(x, y);
} else {
userState[y*boardWidth+x] = UserSquare.flagged;
}
redraw(window);
}
}
);
}
}
version(without_opengl) {
enum SdpyIsUsingIVGLBinds = false;
} else /*version(Posix)*/ {
static if (__traits(compiles, (){import iv.glbinds;})) {
enum SdpyIsUsingIVGLBinds = true;
public import iv.glbinds;
//pragma(msg, "SDPY: using iv.glbinds");
} else {
enum SdpyIsUsingIVGLBinds = false;
}
//} else {
// enum SdpyIsUsingIVGLBinds = false;
}
version(Windows) {
//import core.sys.windows.windows;
import core.sys.windows.winnls;
import core.sys.windows.windef;
import core.sys.windows.basetyps;
import core.sys.windows.winbase;
import core.sys.windows.winuser;
import core.sys.windows.shellapi;
import core.sys.windows.wingdi;
static import gdi = core.sys.windows.wingdi; // so i
pragma(lib, "gdi32");
pragma(lib, "user32");
} else version (linux) {
//k8: this is hack for rdmd. sorry.
static import core.sys.linux.epoll;
static import core.sys.linux.timerfd;
}
// FIXME: icons on Windows don't look quite right, I think the transparency mask is off.
// http://wiki.dlang.org/Simpledisplay.d
// FIXME: SIGINT handler is necessary to clean up shared memory handles upon ctrl+c
// see : http://www.sbin.org/doc/Xlib/chapt_09.html section on Keyboard Preferences re: scroll lock led
// Cool stuff: I want right alt and scroll lock to do different stuff for personal use. maybe even right ctrl
// but can i control the scroll lock led
// Note: if you are using Image on X, you might want to do:
/*
static if(UsingSimpledisplayX11) {
if(!Image.impl.xshmAvailable) {
// the images will use the slower XPutImage, you might
// want to consider an alternative method to get better speed
}
}
If the shared memory extension is available though, simpledisplay uses it
for a significant speed boost whenever you draw large Images.
*/
// CHANGE FROM LAST VERSION: the window background is no longer fixed, so you might want to fill the screen with a particular color before drawing.
// WARNING: if you are using with_eventloop, don't forget to call XFlush(XDisplayConnection.get()); before calling loop()!
/*
Biggest FIXME:
make sure the key event numbers match between X and Windows OR provide symbolic constants on each system
clean up opengl contexts when their windows close
fix resizing the bitmaps/pixmaps
*/
// BTW on Windows:
// -L/SUBSYSTEM:WINDOWS:5.0
// to dmd will make a nice windows binary w/o a console if you want that.
/*
Stuff to add:
use multibyte functions everywhere we can
OpenGL windows
more event stuff
extremely basic windows w/ no decoration for tooltips, splash screens, etc.
resizeEvent
and make the windows non-resizable by default,
or perhaps stretched (if I can find something in X like StretchBlt)
take a screenshot function!
Pens and brushes?
Maybe a global event loop?
Mouse deltas
Key items
*/
/*
From MSDN:
You can also use the GET_X_LPARAM or GET_Y_LPARAM macro to extract the x- or y-coordinate.
Important Do not use the LOWORD or HIWORD macros to extract the x- and y- coordinates of the cursor position because these macros return incorrect results on systems with multiple monitors. Systems with multiple monitors can have negative x- and y- coordinates, and LOWORD and HIWORD treat the coordinates as unsigned quantities.
*/
version(linux) {
version = X11;
version(without_libnotify) {
// we cool
}
else
version = libnotify;
}
version(libnotify) {
pragma(lib, "dl");
import core.sys.posix.dlfcn;
void delegate()[int] libnotify_action_delegates;
int libnotify_action_delegates_count;
extern(C) static void libnotify_action_callback_sdpy(void* notification, char* action, void* user_data) {
auto idx = cast(int) user_data;
if(auto dgptr = idx in libnotify_action_delegates) {
(*dgptr)();
libnotify_action_delegates.remove(idx);
}
}
struct C_DynamicLibrary {
void* handle;
this(string name) {
handle = dlopen((name ~ "\0").ptr, RTLD_NOW);
if(handle is null)
throw new Exception("dlopen");
}
void close() {
dlclose(handle);
}
~this() {
// close
}
template call(string func, Ret, Args...) {
extern(C) Ret function(Args) fptr;
typeof(fptr) call() {
fptr = cast(typeof(fptr)) dlsym(handle, func);
return fptr;
}
}
}
C_DynamicLibrary* libnotify;
}
version(OSX) {
version(OSXCocoa) {}
else { version = X11; }
}
//version = OSXCocoa; // this was written by KennyTM
version(FreeBSD)
version = X11;
version(Solaris)
version = X11;
void featureNotImplemented()() {
version(allow_unimplemented_features)
throw new NotYetImplementedException();
else
static assert(0);
}
// these are so the static asserts don't trigger unless you want to
// add support to it for an OS
version(Windows)
version = with_timer;
version(linux)
version = with_timer;
/// If you have to get down and dirty with implementation details, this helps figure out if Windows is available you can `static if(UsingSimpledisplayWindows) ...` more reliably than `version()` because `version` is module-local.
version(Windows)
enum bool UsingSimpledisplayWindows = true;
else
enum bool UsingSimpledisplayWindows = false;
/// If you have to get down and dirty with implementation details, this helps figure out if X is available you can `static if(UsingSimpledisplayX11) ...` more reliably than `version()` because `version` is module-local.
version(X11)
enum bool UsingSimpledisplayX11 = true;
else
enum bool UsingSimpledisplayX11 = false;
/// If you have to get down and dirty with implementation details, this helps figure out if Cocoa is available you can `static if(UsingSimpledisplayCocoa) ...` more reliably than `version()` because `version` is module-local.
version(OSXCocoa)
enum bool UsingSimpledisplayCocoa = true;
else
enum bool UsingSimpledisplayCocoa = false;
/// Does this platform support multiple windows? If not, trying to create another will cause it to throw an exception.
version(Windows)
enum multipleWindowsSupported = true;
else version(X11)
enum multipleWindowsSupported = true;
else version(OSXCocoa)
enum multipleWindowsSupported = true;
else
static assert(0);
version(without_opengl)
enum bool OpenGlEnabled = false;
else
enum bool OpenGlEnabled = true;
/++
After selecting a type from [WindowTypes], you may further customize
its behavior by setting one or more of these flags.
The different window types have different meanings of `normal`. If the
window type already is a good match for what you want to do, you should
just use [WindowFlags.normal], the default, which will do the right thing
for your users.
The window flags will not always be honored by the operating system
and window managers; they are hints, not commands.
+/
enum WindowFlags : int {
normal = 0, ///
skipTaskbar = 1, ///
alwaysOnTop = 2, ///
alwaysOnBottom = 4, ///
cannotBeActivated = 8, ///
alwaysRequestMouseMotionEvents = 16, /// By default, simpledisplay will attempt to optimize mouse motion event reporting when it detects a remote connection, causing them to only be issued if input is grabbed (see: [SimpleWindow.grabInput]). This means doing hover effects and mouse game control on a remote X connection may not work right. Include this flag to override this optimization and always request the motion events. However btw, if you are doing mouse game control, you probably want to grab input anyway, and hover events are usually expendable! So think before you use this flag.
extraComposite = 32, /// On windows this will make this a layered windows (not supported for child windows before windows 8) to support transparency and improve animation performance.
dontAutoShow = 0x1000_0000, /// Don't automatically show window after creation; you will have to call `show()` manually.
}
/++
When creating a window, you can pass a type to SimpleWindow's constructor,
then further customize the window by changing `WindowFlags`.
You should mostly only need [normal], [undecorated], and [eventOnly] for normal
use. The others are there to build a foundation for a higher level GUI toolkit,
but are themselves not as high level as you might think from their names.
This list is based on the EMWH spec for X11.
http://standards.freedesktop.org/wm-spec/1.4/ar01s05.html#idm139704063786896
+/
enum WindowTypes : int {
/// An ordinary application window.
normal,
/// A generic window without a title bar or border. You can draw on the entire area of the screen it takes up and use it as you wish. Remember that users don't really expect these though, so don't use it where a window of any other type is appropriate.
undecorated,
/// A window that doesn't actually display on screen. You can use it for cases where you need a dummy window handle to communicate with or something.
eventOnly,
/// A drop down menu, such as from a menu bar
dropdownMenu,
/// A popup menu, such as from a right click
popupMenu,
/// A popup bubble notification
notification,
/*
menu, /// a tearable menu bar
splashScreen, /// a loading splash screen for your application
tooltip, /// A tiny window showing temporary help text or something.
comboBoxDropdown,
dialog,
toolbar
*/
/// a child nested inside the parent. You must pass a parent window to the ctor
nestedChild,
}
private __gshared ushort sdpyOpenGLContextVersion = 0; // default: use legacy call
private __gshared bool sdpyOpenGLContextCompatible = true; // default: allow "deprecated" features
private __gshared char* sdpyWindowClassStr = null;
private __gshared bool sdpyOpenGLContextAllowFallback = false;
/**
Set OpenGL context version to use. This has no effect on non-OpenGL windows.
You may want to change context version if you want to use advanced shaders or
other modern OpenGL techinques. This setting doesn't affect already created
windows. You may use version 2.1 as your default, which should be supported
by any box since 2006, so seems to be a reasonable choice.
Note that by default version is set to `0`, which forces SimpleDisplay to use
old context creation code without any version specified. This is the safest
way to init OpenGL, but it may not give you access to advanced features.
See available OpenGL versions here: https://en.wikipedia.org/wiki/OpenGL
*/
void setOpenGLContextVersion() (ubyte hi, ubyte lo) { sdpyOpenGLContextVersion = cast(ushort)(hi<<8|lo); }
/**
Set OpenGL context mode. Modern (3.0+) OpenGL versions deprecated old fixed
pipeline functions, and without "compatible" mode you won't be able to use
your old non-shader-based code with such contexts. By default SimpleDisplay
creates compatible context, so you can gradually upgrade your OpenGL code if
you want to (or leave it as is, as it should "just work").
*/
@property void openGLContextCompatible() (bool v) { sdpyOpenGLContextCompatible = v; }
/**
Set to `true` to allow creating OpenGL context with lower version than requested
instead of throwing. If fallback was activated (or legacy OpenGL was requested),
`openGLContextFallbackActivated()` will return `true`.
*/
@property void openGLContextAllowFallback() (bool v) { sdpyOpenGLContextAllowFallback = v; }
/**
After creating OpenGL window, you can check this to see if you got only "legacy" OpenGL context.
*/
@property bool openGLContextFallbackActivated() () { return (sdpyOpenGLContextVersion == 0); }
/**
Set window class name for all following `new SimpleWindow()` calls.
WARNING! For Windows, you should set your class name before creating any
window, and NEVER change it after that!
*/
void sdpyWindowClass (const(char)[] v) {
import core.stdc.stdlib : realloc;
if (v.length == 0) v = "SimpleDisplayWindow";
sdpyWindowClassStr = cast(char*)realloc(sdpyWindowClassStr, v.length+1);
if (sdpyWindowClassStr is null) return; // oops
sdpyWindowClassStr[0..v.length+1] = 0;
sdpyWindowClassStr[0..v.length] = v[];
}
/**
Get current window class name.
*/
string sdpyWindowClass () {
if (sdpyWindowClassStr is null) return null;
foreach (immutable idx; 0..size_t.max-1) {
if (sdpyWindowClassStr[idx] == 0) return sdpyWindowClassStr[0..idx].idup;
}
return null;
}
/++
Returns the DPI of the default monitor. [0] is width, [1] is height (they are usually the same though). You may wish to round the numbers off.
+/
float[2] getDpi() {
float[2] dpi;
version(Windows) {
HDC screen = GetDC(null);
dpi[0] = GetDeviceCaps(screen, LOGPIXELSX);
dpi[1] = GetDeviceCaps(screen, LOGPIXELSY);
} else version(X11) {
auto display = XDisplayConnection.get;
auto screen = DefaultScreen(display);
void fallback() {
// 25.4 millimeters in an inch...
dpi[0] = cast(float) DisplayWidth(display, screen) / DisplayWidthMM(display, screen) * 25.4;
dpi[1] = cast(float) DisplayHeight(display, screen) / DisplayHeightMM(display, screen) * 25.4;
}
char* resourceString = XResourceManagerString(display);
XrmInitialize();
auto db = XrmGetStringDatabase(resourceString);
if (resourceString) {
XrmValue value;
char* type;
if (XrmGetResource(db, "Xft.dpi", "String", &type, &value) == true) {
if (value.addr) {
import core.stdc.stdlib;
dpi[0] = atof(cast(char*) value.addr);
dpi[1] = dpi[0];
} else {
fallback();
}
} else {
fallback();
}
} else {
fallback();
}
}
return dpi;
}
version(X11) {
extern(C) char* XResourceManagerString(Display*);
extern(C) void XrmInitialize();
extern(C) XrmDatabase XrmGetStringDatabase(char* data);
extern(C) bool XrmGetResource(XrmDatabase, const char*, const char*, char**, XrmValue*);
alias XrmDatabase = void*;
struct XrmValue {
uint size;
void* addr;
}
}
TrueColorImage trueColorImageFromNativeHandle(NativeWindowHandle handle, int width, int height) {
throw new Exception("not implemented");
version(none) {
version(X11) {
auto display = XDisplayConnection.get;
auto image = XGetImage(display, handle, 0, 0, width, height, (cast(c_ulong) ~0) /*AllPlanes*/, ZPixmap);
// https://github.com/adamdruppe/arsd/issues/98
// FIXME: copy that shit
XDestroyImage(image);
} else version(Windows) {
// I just need to BitBlt that shit... BUT WAIT IT IS ALREADY IN A DIB!!!!!!!
} else featureNotImplemented();
return null;
}
}
/++
The flagship window class.
SimpleWindow tries to make ordinary windows very easy to create and use without locking you
out of more advanced or complex features of the underlying windowing system.
For many applications, you can simply call `new SimpleWindow(some_width, some_height, "some title")`
and get a suitable window to work with.
From there, you can opt into additional features, like custom resizability and OpenGL support
with the next two constructor arguments. Or, if you need even more, you can set a window type
and customization flags with the final two constructor arguments.
If none of that works for you, you can also create a window using native function calls, then
wrap the window in a SimpleWindow instance by calling `new SimpleWindow(native_handle)`. Remember,
though, if you do this, managing the window is still your own responsibility! Notably, you
will need to destroy it yourself.
+/
class SimpleWindow : CapableOfHandlingNativeEvent, CapableOfBeingDrawnUpon {
/// Be warned: this can be a very slow operation
/// FIXME NOT IMPLEMENTED
TrueColorImage takeScreenshot() {
version(Windows)
return trueColorImageFromNativeHandle(impl.hwnd, width, height);
else version(OSXCocoa)
throw new NotYetImplementedException();
else
return trueColorImageFromNativeHandle(impl.window, width, height);
}
version(X11) {
void recreateAfterDisconnect() {
if(!stateDiscarded) return;
if(_parent !is null && _parent.stateDiscarded)
_parent.recreateAfterDisconnect();
bool wasHidden = hidden;
activeScreenPainter = null; // should already be done but just to confirm
impl.createWindow(_width, _height, _title, openglMode, _parent);
if(recreateAdditionalConnectionState)
recreateAdditionalConnectionState();
hidden = wasHidden;
stateDiscarded = false;
}
bool stateDiscarded;
void discardConnectionState() {
if(XDisplayConnection.display)
impl.dispose(); // if display is already null, it is hopeless to try to destroy stuff on it anyway
if(discardAdditionalConnectionState)
discardAdditionalConnectionState();
stateDiscarded = true;
}
void delegate() discardAdditionalConnectionState;
void delegate() recreateAdditionalConnectionState;
}
SimpleWindow _parent;
bool beingOpenKeepsAppOpen = true;
/++
This creates a window with the given options. The window will be visible and able to receive input as soon as you start your event loop. You may draw on it immediately after creating the window, without needing to wait for the event loop to start if you want.
The constructor tries to have sane default arguments, so for many cases, you only need to provide a few of them.
Params:
width = the width of the window's client area, in pixels
height = the height of the window's client area, in pixels
title = the title of the window (seen in the title bar, taskbar, etc.). You can change it after construction with the [SimpleWindow.title\ property.
opengl = [OpenGlOptions] are yes and no. If yes, it creates an OpenGL context on the window.
resizable = [Resizability] has three options:
$(P `allowResizing`, which allows the window to be resized by the user. The `windowResized` delegate will be called when the size is changed.)
$(P `fixedSize` will not allow the user to resize the window.)
$(P `automaticallyScaleIfPossible` will allow the user to resize, but will still present the original size to the API user. The contents you draw will be scaled to the size the user chose. If this scaling is not efficient, the window will be fixed size. The `windowResized` event handler will never be called. This is the default.)
windowType = The type of window you want to make.
customizationFlags = A way to make a window without a border, always on top, skip taskbar, and more. Do not use this if one of the pre-defined [WindowTypes], given in the `windowType` argument, is a good match for what you need.
parent = the parent window, if applicable
+/
this(int width = 640, int height = 480, string title = null, OpenGlOptions opengl = OpenGlOptions.no, Resizability resizable = Resizability.automaticallyScaleIfPossible, WindowTypes windowType = WindowTypes.normal, int customizationFlags = WindowFlags.normal, SimpleWindow parent = null) {
this._width = width;
this._height = height;
this.openglMode = opengl;
this.resizability = resizable;
this.windowType = windowType;
this.customizationFlags = customizationFlags;
this._title = (title is null ? "D Application" : title);
this._parent = parent;
impl.createWindow(width, height, this._title, opengl, parent);
if(windowType == WindowTypes.dropdownMenu || windowType == WindowTypes.popupMenu || windowType == WindowTypes.nestedChild)
beingOpenKeepsAppOpen = false;
}
/// Same as above, except using the `Size` struct instead of separate width and height.
this(Size size, string title = null, OpenGlOptions opengl = OpenGlOptions.no, Resizability resizable = Resizability.automaticallyScaleIfPossible) {
this(size.width, size.height, title, opengl, resizable);
}
/++
Creates a window based on the given [Image]. It's client area
width and height is equal to the image. (A window's client area
is the drawable space inside; it excludes the title bar, etc.)
Windows based on images will not be resizable and do not use OpenGL.
+/
this(Image image, string title = null) {
this(image.width, image.height, title);
this.image = image;
}
/++
Wraps a native window handle with very little additional processing - notably no destruction
this is incomplete so don't use it for much right now. The purpose of this is to make native
windows created through the low level API (so you can use platform-specific options and
other details SimpleWindow does not expose) available to the event loop wrappers.
+/
this(NativeWindowHandle nativeWindow) {
version(Windows)
impl.hwnd = nativeWindow;
else version(X11) {
impl.window = nativeWindow;
display = XDisplayConnection.get(); // get initial display to not segfault
} else version(OSXCocoa)
throw new NotYetImplementedException();
else featureNotImplemented();
// FIXME: set the size correctly
_width = 1;
_height = 1;
nativeMapping[nativeWindow] = this;
CapableOfHandlingNativeEvent.nativeHandleMapping[nativeWindow] = this;
_suppressDestruction = true; // so it doesn't try to close
}
/// Experimental, do not use yet
/++
Grabs exclusive input from the user until you release it with
[releaseInputGrab].
Note: it is extremely rude to do this without good reason.
Reasons may include doing some kind of mouse drag operation
or popping up a temporary menu that should get events and will
be dismissed at ease by the user clicking away.
Params:
keyboard = do you want to grab keyboard input?
mouse = grab mouse input?
confine = confine the mouse cursor to inside this window?
+/
void grabInput(bool keyboard = true, bool mouse = true, bool confine = false) {
static if(UsingSimpledisplayX11) {
XSync(XDisplayConnection.get, 0);
if(keyboard)
XSetInputFocus(XDisplayConnection.get, this.impl.window, RevertToParent, CurrentTime);
if(mouse) {
if(auto res = XGrabPointer(XDisplayConnection.get, this.impl.window, false /* owner_events */,
EventMask.PointerMotionMask // FIXME: not efficient
| EventMask.ButtonPressMask
| EventMask.ButtonReleaseMask
/* event mask */, GrabMode.GrabModeAsync, GrabMode.GrabModeAsync, confine ? this.impl.window : None, None, CurrentTime)
)
{
XSync(XDisplayConnection.get, 0);
import core.stdc.stdio;
printf("Grab input failed %d\n", res);
//throw new Exception("Grab input failed");
} else {
// cool
}
}
} else version(Windows) {
// FIXME: keyboard?
SetCapture(impl.hwnd);
if(confine) {
RECT rcClip;
//RECT rcOldClip;
//GetClipCursor(&rcOldClip);
GetWindowRect(hwnd, &rcClip);
ClipCursor(&rcClip);
}
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
/++
Releases the grab acquired by [grabInput].
+/
void releaseInputGrab() {
static if(UsingSimpledisplayX11) {
XUngrabPointer(XDisplayConnection.get, CurrentTime);
} else version(Windows) {
ReleaseCapture();
ClipCursor(null);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
/++
Sets the input focus to this window.
You shouldn't call this very often - please let the user control the input focus.
+/
void focus() {
static if(UsingSimpledisplayX11) {
XSetInputFocus(XDisplayConnection.get, this.impl.window, RevertToParent, CurrentTime);
} else version(Windows) {
SetFocus(this.impl.hwnd);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
/++
Requests attention from the user for this window.
The typical result of this function is to change the color
of the taskbar icon, though it may be tweaked on specific
platforms.
It is meant to unobtrusively tell the user that something
relevant to them happened in the background and they should
check the window when they get a chance. Upon receiving the
keyboard focus, the window will automatically return to its
natural state.
If the window already has the keyboard focus, this function
may do nothing, because the user is presumed to already be
giving the window attention.
Implementation_note:
`requestAttention` uses the _NET_WM_STATE_DEMANDS_ATTENTION
atom on X11 and the FlashWindow function on Windows.
+/
void requestAttention() {
if(_focused)
return;
version(Windows) {
FLASHWINFO info;
info.cbSize = info.sizeof;
info.hwnd = impl.hwnd;
info.dwFlags = FLASHW_TRAY;
info.uCount = 1;
FlashWindowEx(&info);
} else version(X11) {
demandingAttention = true;
demandAttention(this, true);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
private bool _focused;
version(X11) private bool demandingAttention;
/// This will be called when WM wants to close your window (i.e. user clicked "close" icon, for example).
/// You'll have to call `close()` manually if you set this delegate.
void delegate () closeQuery;
/// This will be called when window visibility was changed.
void delegate (bool becomesVisible) visibilityChanged;
/// This will be called when window becomes visible for the first time.
/// You can do OpenGL initialization here. Note that in X11 you can't call
/// [setAsCurrentOpenGlContext] right after window creation, or X11 may
/// fail to send reparent and map events (hit that with proprietary NVidia drivers).
private bool _visibleForTheFirstTimeCalled;
void delegate () visibleForTheFirstTime;
/// Returns true if the window has been closed.
final @property bool closed() { return _closed; }
/// Returns true if the window is focused.
final @property bool focused() { return _focused; }
private bool _visible;
/// Returns true if the window is visible (mapped).
final @property bool visible() { return _visible; }
/// Closes the window. If there are no more open windows, the event loop will terminate.
void close() {
if (!_closed) {
if (onClosing !is null) onClosing();
impl.closeWindow();
_closed = true;
}
}
/// Alias for `hidden = false`
void show() {
hidden = false;
}
/// Alias for `hidden = true`
void hide() {
hidden = true;
}
/// Hide cursor when it enters the window.
void hideCursor() {
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.hideCursor();
}
/// Don't hide cursor when it enters the window.
void showCursor() {
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.showCursor();
}
/** "Warp" mouse pointer to coordinates relative to window top-left corner. Return "success" flag.
*
* Currently only supported on X11, so Windows implementation will return `false`.
*
* Note: "warping" pointer will not send any synthesised mouse events, so you probably doesn't want
* to use it to move mouse pointer to some active GUI area, for example, as your window won't
* receive "mouse moved here" event.
*/
bool warpMouse (int x, int y) {
version(X11) {
if (!_closed) { impl.warpMouse(x, y); return true; }
}
return false;
}
/// Send dummy window event to ping event loop. Required to process NotificationIcon on X11, for example.
void sendDummyEvent () {
version(X11) {
if (!_closed) { impl.sendDummyEvent(); }
}
}
/// Set window minimal size.
void setMinSize (int minwidth, int minheight) {
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.setMinSize(minwidth, minheight);
}
/// Set window maximal size.
void setMaxSize (int maxwidth, int maxheight) {
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.setMaxSize(maxwidth, maxheight);
}
/// Set window resize step (window size will be changed with the given granularity on supported platforms).
/// Currently only supported on X11.
void setResizeGranularity (int granx, int grany) {
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.setResizeGranularity(granx, grany);
}
/// Move window.
void move(int x, int y) {
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.move(x, y);
}
/// ditto
void move(Point p) {
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.move(p.x, p.y);
}
/++
Resize window.
Note that the width and height of the window are NOT instantly
updated - it waits for the window manager to approve the resize
request, which means you must return to the event loop before the
width and height are actually changed.
+/
void resize(int w, int h) {
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.resize(w, h);
}
/// Move and resize window (this can be faster and more visually pleasant than doing it separately).
void moveResize (int x, int y, int w, int h) {
version(OSXCocoa) throw new NotYetImplementedException(); else
if (!_closed) impl.moveResize(x, y, w, h);
}
private bool _hidden;
/// Returns true if the window is hidden.
final @property bool hidden() {
return _hidden;
}
/// Shows or hides the window based on the bool argument.
final @property void hidden(bool b) {
_hidden = b;
version(Windows) {
ShowWindow(impl.hwnd, b ? SW_HIDE : SW_SHOW);
} else version(X11) {
if(b)
//XUnmapWindow(impl.display, impl.window);
XWithdrawWindow(impl.display, impl.window, DefaultScreen(impl.display));
else
XMapWindow(impl.display, impl.window);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
/// Sets the window opacity. On X11 this requires a compositor to be running. On windows the WindowFlags.extraComposite must be set at window creation.
void opacity(double opacity) @property
in {
assert(opacity >= 0 && opacity <= 1);
} body {
version (Windows) {
impl.setOpacity(cast(ubyte)(255 * opacity));
} else version (X11) {
impl.setOpacity(cast(uint)(uint.max * opacity));
} else throw new NotYetImplementedException();
}
/++
Sets your event handlers, without entering the event loop. Useful if you
have multiple windows - set the handlers on each window, then only do eventLoop on your main window.
+/
void setEventHandlers(T...)(T eventHandlers) {
// FIXME: add more events
foreach(handler; eventHandlers) {
static if(__traits(compiles, handleKeyEvent = handler)) {
handleKeyEvent = handler;
} else static if(__traits(compiles, handleCharEvent = handler)) {
handleCharEvent = handler;
} else static if(__traits(compiles, handlePulse = handler)) {
handlePulse = handler;
} else static if(__traits(compiles, handleMouseEvent = handler)) {
handleMouseEvent = handler;
} else static assert(0, "I can't use this event handler " ~ typeof(handler).stringof ~ "\nHave you tried using the delegate keyword?");
}
}
/// The event loop automatically returns when the window is closed
/// pulseTimeout is given in milliseconds. If pulseTimeout == 0, no
/// pulse timer is created. The event loop will block until an event
/// arrives or the pulse timer goes off.
final int eventLoop(T...)(
long pulseTimeout, /// set to zero if you don't want a pulse.
T eventHandlers) /// delegate list like std.concurrency.receive
{
setEventHandlers(eventHandlers);
version(with_eventloop) {
// delegates event loop to my other module
version(X11)
XFlush(display);
import arsd.eventloop;
auto handle = setInterval(handlePulse, cast(int) pulseTimeout);
scope(exit) clearInterval(handle);
loop();
return 0;
} else version(OSXCocoa) {
// FIXME
if (handlePulse !is null && pulseTimeout != 0) {
timer = scheduledTimer(pulseTimeout*1e-3,
view, sel_registerName("simpledisplay_pulse"),
null, true);
}
setNeedsDisplay(view, true);
run(NSApp);
return 0;
} else {
EventLoop el = EventLoop(pulseTimeout, handlePulse);
return el.run();
}
}
/++
This lets you draw on the window (or its backing buffer) using basic
2D primitives.
Be sure to call this in a limited scope because your changes will not
actually appear on the window until ScreenPainter's destructor runs.
Returns: an instance of [ScreenPainter], which has the drawing methods
on it to draw on this window.
+/
ScreenPainter draw() {
return impl.getPainter();
}
// This is here to implement the interface we use for various native handlers.
NativeEventHandler getNativeEventHandler() { return handleNativeEvent; }
// maps native window handles to SimpleWindow instances, if there are any
// you shouldn't need this, but it is public in case you do in a native event handler or something
public __gshared SimpleWindow[NativeWindowHandle] nativeMapping;
/// Width of the window's drawable client area, in pixels.
@scriptable
final @property int width() { return _width; }
/// Height of the window's drawable client area, in pixels.
@scriptable
final @property int height() { return _height; }
private int _width;
private int _height;
// HACK: making the best of some copy constructor woes with refcounting
private ScreenPainterImplementation* activeScreenPainter_;
protected ScreenPainterImplementation* activeScreenPainter() { return activeScreenPainter_; }
protected void activeScreenPainter(ScreenPainterImplementation* i) { activeScreenPainter_ = i; }
private OpenGlOptions openglMode;
private Resizability resizability;
private WindowTypes windowType;
private int customizationFlags;
/// `true` if OpenGL was initialized for this window.
@property bool isOpenGL () const pure nothrow @safe @nogc {
version(without_opengl)
return false;
else
return (openglMode == OpenGlOptions.yes);
}
@property Resizability resizingMode () const pure nothrow @safe @nogc { return resizability; } /// Original resizability.
@property WindowTypes type () const pure nothrow @safe @nogc { return windowType; } /// Original window type.
@property int customFlags () const pure nothrow @safe @nogc { return customizationFlags; } /// Original customization flags.
/// "Lock" this window handle, to do multithreaded synchronization. You probably won't need
/// to call this, as it's not recommended to share window between threads.
void mtLock () {
version(X11) {
XLockDisplay(this.display);
}
}
/// "Unlock" this window handle, to do multithreaded synchronization. You probably won't need
/// to call this, as it's not recommended to share window between threads.
void mtUnlock () {
version(X11) {
XUnlockDisplay(this.display);
}
}
/// Emit a beep to get user's attention.
void beep () {
version(X11) {
XBell(this.display, 100);
} else version(Windows) {
MessageBeep(0xFFFFFFFF);
}
}
version(without_opengl) {} else {
/// Put your code in here that you want to be drawn automatically when your window is uncovered. Set a handler here *before* entering your event loop any time you pass `OpenGlOptions.yes` to the constructor. Ideally, you will set this delegate immediately after constructing the `SimpleWindow`.
void delegate() redrawOpenGlScene;
/// This will allow you to change OpenGL vsync state.
final @property void vsync (bool wait) {
if (this._closed) return; // window may be closed, but timer is still firing; avoid GLXBadDrawable error
version(X11) {
setAsCurrentOpenGlContext();
glxSetVSync(display, impl.window, wait);
}
}
/// Set this to `false` if you don't need to do `glFinish()` after `swapOpenGlBuffers()`.
/// Note that at least NVidia proprietary driver may segfault if you will modify texture fast
/// enough without waiting 'em to finish their frame bussiness.
bool useGLFinish = true;
// FIXME: it should schedule it for the end of the current iteration of the event loop...
/// call this to invoke your delegate. It automatically sets up the context and flips the buffer. If you need to redraw the scene in response to an event, call this.
void redrawOpenGlSceneNow() {
version(X11) if (!this._visible) return; // no need to do this if window is invisible
if (this._closed) return; // window may be closed, but timer is still firing; avoid GLXBadDrawable error
if(redrawOpenGlScene is null)
return;
this.mtLock();
scope(exit) this.mtUnlock();
this.setAsCurrentOpenGlContext();
redrawOpenGlScene();
this.swapOpenGlBuffers();
// at least nvidia proprietary crap segfaults on exit if you won't do this and will call glTexSubImage2D() too fast; no, `glFlush()` won't work.
if (useGLFinish) glFinish();
}
/// Makes all gl* functions target this window until changed. This is only valid if you passed `OpenGlOptions.yes` to the constructor.
void setAsCurrentOpenGlContext() {
assert(openglMode == OpenGlOptions.yes);
version(X11) {
if(glXMakeCurrent(display, impl.window, impl.glc) == 0)
throw new Exception("glXMakeCurrent");
} else version(Windows) {
static if (SdpyIsUsingIVGLBinds) import iv.glbinds; // override druntime windows imports
if (!wglMakeCurrent(ghDC, ghRC))
throw new Exception("wglMakeCurrent"); // let windows users suffer too
}
}
/// Makes all gl* functions target this window until changed. This is only valid if you passed `OpenGlOptions.yes` to the constructor.
/// This doesn't throw, returning success flag instead.
bool setAsCurrentOpenGlContextNT() nothrow {
assert(openglMode == OpenGlOptions.yes);
version(X11) {
return (glXMakeCurrent(display, impl.window, impl.glc) != 0);
} else version(Windows) {
static if (SdpyIsUsingIVGLBinds) import iv.glbinds; // override druntime windows imports
return wglMakeCurrent(ghDC, ghRC) ? true : false;
}
}
/// Releases OpenGL context, so it can be reused in, for example, different thread. This is only valid if you passed `OpenGlOptions.yes` to the constructor.
/// This doesn't throw, returning success flag instead.
bool releaseCurrentOpenGlContext() nothrow {
assert(openglMode == OpenGlOptions.yes);
version(X11) {
return (glXMakeCurrent(display, 0, null) != 0);
} else version(Windows) {
static if (SdpyIsUsingIVGLBinds) import iv.glbinds; // override druntime windows imports
return wglMakeCurrent(ghDC, null) ? true : false;
}
}
/++
simpledisplay always uses double buffering, usually automatically. This
manually swaps the OpenGL buffers.
You should not need to call this yourself because simpledisplay will do it
for you after calling your `redrawOpenGlScene`.
Remember that this may throw an exception, which you can catch in a multithreaded
application to keep your thread from dying from an unhandled exception.
+/
void swapOpenGlBuffers() {
assert(openglMode == OpenGlOptions.yes);
version(X11) {
if (!this._visible) return; // no need to do this if window is invisible
if (this._closed) return; // window may be closed, but timer is still firing; avoid GLXBadDrawable error
glXSwapBuffers(display, impl.window);
} else version(Windows) {
SwapBuffers(ghDC);
}
}
}
/++
Set the window title, which is visible on the window manager title bar, operating system taskbar, etc.
---
auto window = new SimpleWindow(100, 100, "First title");
window.title = "A new title";
---
You may call this function at any time.
+/
@property void title(string title) {
_title = title;
version(OSXCocoa) throw new NotYetImplementedException(); else
impl.setTitle(title);
}
private string _title;
/// Gets the title
@property string title() {
if(_title is null)
_title = getRealTitle();
return _title;
}
/++
Get the title as set by the window manager.
May not match what you attempted to set.
+/
string getRealTitle() {
static if(is(typeof(impl.getTitle())))
return impl.getTitle();
else
return null;
}
/// Set the icon that is seen in the title bar or taskbar, etc., for the user.
@property void icon(MemoryImage icon) {
auto tci = icon.getAsTrueColorImage();
version(Windows) {
winIcon = new WindowsIcon(icon);
SendMessageA(impl.hwnd, 0x0080 /*WM_SETICON*/, 0 /*ICON_SMALL*/, cast(LPARAM) winIcon.hIcon); // there is also 1 == ICON_BIG
} else version(X11) {
// FIXME: ensure this is correct
auto display = XDisplayConnection.get;
arch_ulong[] buffer;
buffer ~= icon.width;
buffer ~= icon.height;
foreach(c; tci.imageData.colors) {
arch_ulong b;
b |= c.a << 24;
b |= c.r << 16;
b |= c.g << 8;
b |= c.b;
buffer ~= b;
}
XChangeProperty(
display,
impl.window,
GetAtom!"_NET_WM_ICON"(display),
GetAtom!"CARDINAL"(display),
32 /* bits */,
0 /*PropModeReplace*/,
buffer.ptr,
cast(int) buffer.length);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
version(Windows)
private WindowsIcon winIcon;
bool _suppressDestruction;
~this() {
if(_suppressDestruction)
return;
impl.dispose();
}
private bool _closed;
// the idea here is to draw something temporary on top of the main picture e.g. a blinking cursor
/*
ScreenPainter drawTransiently() {
return impl.getPainter();
}
*/
/// Draws an image on the window. This is meant to provide quick look
/// of a static image generated elsewhere.
@property void image(Image i) {
version(Windows) {
BITMAP bm;
HDC hdc = GetDC(hwnd);
HDC hdcMem = CreateCompatibleDC(hdc);
HBITMAP hbmOld = SelectObject(hdcMem, i.handle);
GetObject(i.handle, bm.sizeof, &bm);
BitBlt(hdc, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem, 0, 0, SRCCOPY);
SelectObject(hdcMem, hbmOld);
DeleteDC(hdcMem);
DeleteDC(hwnd);
/*
RECT r;
r.right = i.width;
r.bottom = i.height;
InvalidateRect(hwnd, &r, false);
*/
} else
version(X11) {
if(!destroyed) {
if(i.usingXshm)
XShmPutImage(display, cast(Drawable) window, gc, i.handle, 0, 0, 0, 0, i.width, i.height, false);
else
XPutImage(display, cast(Drawable) window, gc, i.handle, 0, 0, 0, 0, i.width, i.height);
}
} else
version(OSXCocoa) {
draw().drawImage(Point(0, 0), i);
setNeedsDisplay(view, true);
} else static assert(0);
}
/++
Changes the cursor for the window. If the cursor is hidden via [hideCursor], this has no effect.
---
window.cursor = GenericCursor.Help;
// now the window mouse cursor is set to a generic help
---
+/
@property void cursor(MouseCursor cursor) {
auto ch = cursor.cursorHandle;
if(this.impl.curHidden <= 0) {
static if(UsingSimpledisplayX11) {
XDefineCursor(XDisplayConnection.get(), this.impl.window, ch);
} else version(Windows) {
impl.currentCursor = ch;
SetCursor(ch); // redraw without waiting for mouse movement to update
} else featureNotImplemented();
}
}
/// What follows are the event handlers. These are set automatically
/// by the eventLoop function, but are still public so you can change
/// them later. wasPressed == true means key down. false == key up.
/// Handles a low-level keyboard event. Settable through setEventHandlers.
void delegate(KeyEvent ke) handleKeyEvent;
/// Handles a higher level keyboard event - c is the character just pressed. Settable through setEventHandlers.
void delegate(dchar c) handleCharEvent;
/// Handles a timer pulse. Settable through setEventHandlers.
void delegate() handlePulse;
/// Called when the focus changes, param is if we have it (true) or are losing it (false).
void delegate(bool) onFocusChange;
/** Called inside `close()` method. Our window is still alive, and we can free various resources.
* Sometimes it is easier to setup the delegate instead of subclassing. */
void delegate() onClosing;
/** Called when we received destroy notification. At this stage we cannot do much with our window
* (as it is already dead, and it's native handle cannot be used), but we still can do some
* last minute cleanup. */
void delegate() onDestroyed;
static if (UsingSimpledisplayX11)
/** Called when Expose event comes. See Xlib manual to understand the arguments.
* Return `false` if you want Simpledisplay to copy backbuffer, or `true` if you did it yourself.
* You will probably never need to setup this handler, it is for very low-level stuff.
*
* WARNING! Xlib is multithread-locked when this handles is called! */
bool delegate(int x, int y, int width, int height, int eventsLeft) handleExpose;
//version(Windows)
//bool delegate(WPARAM wParam, LPARAM lParam) handleWM_PAINT;
private {
int lastMouseX = int.min;
int lastMouseY = int.min;
void mdx(ref MouseEvent ev) {
if(lastMouseX == int.min || lastMouseY == int.min) {
ev.dx = 0;
ev.dy = 0;
} else {
ev.dx = ev.x - lastMouseX;
ev.dy = ev.y - lastMouseY;
}
lastMouseX = ev.x;
lastMouseY = ev.y;
}
}
/// Mouse event handler. Settable through setEventHandlers.
void delegate(MouseEvent) handleMouseEvent;
/// use to redraw child widgets if you use system apis to add stuff
void delegate() paintingFinished;
void delegate() paintingFinishedDg() {
return paintingFinished;
}
/// handle a resize, after it happens. You must construct the window with Resizability.allowResizing
/// for this to ever happen.
void delegate(int width, int height) windowResized;
/** Platform specific - handle any native messages this window gets.
*
* Note: this is called *in addition to* other event handlers, unless you return zero indicating that you handled it.
* On Windows, it takes the form of int delegate(HWND,UINT, WPARAM, LPARAM).
* On X11, it takes the form of int delegate(XEvent).
* IMPORTANT: it used to be static in old versions of simpledisplay.d, but I always used
* it as if it wasn't static... so now I just fixed it so it isn't anymore.
**/
NativeEventHandler handleNativeEvent;
/// This is the same as handleNativeEvent, but static so it can hook ALL events in the loop.
/// If you used to use handleNativeEvent depending on it being static, just change it to use
/// this instead and it will work the same way.
__gshared NativeEventHandler handleNativeGlobalEvent;
// private:
/// The native implementation is available, but you shouldn't use it unless you are
/// familiar with the underlying operating system, don't mind depending on it, and
/// know simpledisplay.d's internals too. It is virtually private; you can hopefully
/// do what you need to do with handleNativeEvent instead.
///
/// This is likely to eventually change to be just a struct holding platform-specific
/// handles instead of a template mixin at some point because I'm not happy with the
/// code duplication here (ironically).
mixin NativeSimpleWindowImplementation!() impl;
/**
This is in-process one-way (from anything to window) event sending mechanics.
It is thread-safe, so it can be used in multi-threaded applications to send,
for example, "wake up and repaint" events when thread completed some operation.
This will allow to avoid using timer pulse to check events with synchronization,
'cause event handler will be called in UI thread. You can stop guessing which
pulse frequency will be enough for your app.
Note that events handlers may be called in arbitrary order, i.e. last registered
handler can be called first, and vice versa.
*/
public:
/** Is our custom event queue empty? Can be used in simple cases to prevent
* "spamming" window with events it can't cope with.
* It is safe to call this from non-UI threads.
*/
@property bool eventQueueEmpty() () {
synchronized(this) {
foreach (const ref o; eventQueue[0..eventQueueUsed]) if (!o.doProcess) return false;
}
return true;
}
/** Does our custom event queue contains at least one with the given type?
* Can be used in simple cases to prevent "spamming" window with events
* it can't cope with.
* It is safe to call this from non-UI threads.
*/
@property bool eventQueued(ET:Object) () {
synchronized(this) {
foreach (const ref o; eventQueue[0..eventQueueUsed]) {
if (!o.doProcess) {
if (cast(ET)(o.evt)) return true;
}
}
}
return false;
}
/** Add listener for custom event. Can be used like this:
*
* ---------------------
* auto eid = win.addEventListener((MyStruct evt) { ... });
* ...
* win.removeEventListener(eid);
* ---------------------
*
* Returns: 0 on failure (should never happen, so ignore it)
*
* $(WARNING Don't use this method in object destructors!)
*
* $(WARNING It is better to register all event handlers and don't remove 'em,
* 'cause if event handler id counter will overflow, you won't be able
* to register any more events.)
*/
uint addEventListener(ET:Object) (void delegate (ET) dg) {
if (dg is null) return 0; // ignore empty handlers
synchronized(this) {
//FIXME: abort on overflow?
if (++lastUsedHandlerId == 0) { --lastUsedHandlerId; return 0; } // alas, can't register more events. at all.
EventHandlerEntry e;
e.dg = delegate (Object o) {
if (auto co = cast(ET)o) {
try {
dg(co);
} catch (Exception) {
// sorry!
}
return true;
}
return false;
};
e.id = lastUsedHandlerId;
auto optr = eventHandlers.ptr;
eventHandlers ~= e;
if (eventHandlers.ptr !is optr) {
import core.memory : GC;
if (eventHandlers.ptr is GC.addrOf(eventHandlers.ptr)) GC.setAttr(eventHandlers.ptr, GC.BlkAttr.NO_INTERIOR);
}
return lastUsedHandlerId;
}
}
/// Remove event listener. It is safe to pass invalid event id here.
/// $(WARNING Don't use this method in object destructors!)
void removeEventListener() (uint id) {
if (id == 0 || id > lastUsedHandlerId) return;
synchronized(this) {
foreach (immutable idx; 0..eventHandlers.length) {
if (eventHandlers[idx].id == id) {
foreach (immutable c; idx+1..eventHandlers.length) eventHandlers[c-1] = eventHandlers[c];
eventHandlers[$-1].dg = null;
eventHandlers.length -= 1;
eventHandlers.assumeSafeAppend;
return;
}
}
}
}
/// Post event to queue. It is safe to call this from non-UI threads.
/// If `timeoutmsecs` is greater than zero, the event will be delayed for at least `timeoutmsecs` milliseconds.
/// if `replace` is `true`, replace all existing events typed `ET` with the new one (if `evt` is empty, remove 'em all)
/// Returns `true` if event was queued. Always returns `false` if `evt` is null.
bool postTimeout(ET:Object) (ET evt, uint timeoutmsecs, bool replace=false) {
if (this.closed) return false; // closed windows can't handle events
// remove all events of type `ET`
void removeAllET () {
uint eidx = 0, ec = eventQueueUsed;
auto eptr = eventQueue.ptr;
while (eidx < ec) {
if (eptr.doProcess) { ++eidx; ++eptr; continue; }
if (cast(ET)eptr.evt !is null) {
// i found her!
if (inCustomEventProcessor) {
// if we're in custom event processing loop, processor will clear it for us
eptr.evt = null;
++eidx;
++eptr;
} else {
foreach (immutable c; eidx+1..ec) eventQueue.ptr[c-1] = eventQueue.ptr[c];
ec = --eventQueueUsed;
// clear last event (it is already copied)
eventQueue.ptr[ec].evt = null;
}
} else {
++eidx;
++eptr;
}
}
}
if (evt is null) {
if (replace) { synchronized(this) removeAllET(); }
// ignore empty events, they can't be handled anyway
return false;
}
// add events even if no event FD/event object created yet
synchronized(this) {
if (replace) removeAllET();
if (eventQueueUsed == uint.max) return false; // just in case
if (eventQueueUsed < eventQueue.length) {
eventQueue[eventQueueUsed++] = QueuedEvent(evt, timeoutmsecs);
} else {
if (eventQueue.capacity == eventQueue.length) {
// need to reallocate; do a trick to ensure that old array is cleared
auto oarr = eventQueue;
eventQueue ~= QueuedEvent(evt, timeoutmsecs);
// just in case, do yet another check
if (oarr.length != 0 && oarr.ptr !is eventQueue.ptr) foreach (ref e; oarr[0..eventQueueUsed]) e.evt = null;
import core.memory : GC;
if (eventQueue.ptr is GC.addrOf(eventQueue.ptr)) GC.setAttr(eventQueue.ptr, GC.BlkAttr.NO_INTERIOR);
} else {
auto optr = eventQueue.ptr;
eventQueue ~= QueuedEvent(evt, timeoutmsecs);
assert(eventQueue.ptr is optr);
}
++eventQueueUsed;
assert(eventQueueUsed == eventQueue.length);
}
if (!eventWakeUp()) {
// can't wake up event processor, so there is no reason to keep the event
assert(eventQueueUsed > 0);
eventQueue[--eventQueueUsed].evt = null;
return false;
}
return true;
}
}
/// Post event to queue. It is safe to call this from non-UI threads.
/// if `replace` is `true`, replace all existing events typed `ET` with the new one (if `evt` is empty, remove 'em all)
/// Returns `true` if event was queued. Always returns `false` if `evt` is null.
bool postEvent(ET:Object) (ET evt, bool replace=false) {
return postTimeout!ET(evt, 0, replace);
}
private:
private import core.time : MonoTime;
version(X11) {
__gshared int customEventFD = -1;
} else version(Windows) {
__gshared HANDLE customEventH = null;
}
// wake up event processor
bool eventWakeUp () {
version(X11) {
import core.sys.posix.unistd : write;
ulong n = 1;
if (customEventFD >= 0) write(customEventFD, &n, n.sizeof);
return true;
} else version(Windows) {
if (customEventH !is null) SetEvent(customEventH);
return true;
} else {
// not implemented for other OSes
return false;
}
}
static struct QueuedEvent {
Object evt;
bool timed = false;
MonoTime hittime = MonoTime.zero;
bool doProcess = false; // process event at the current iteration (internal flag)
this (Object aevt, uint toutmsecs) {
evt = aevt;
if (toutmsecs > 0) {
import core.time : msecs;
timed = true;
hittime = MonoTime.currTime+toutmsecs.msecs;
}
}
}
alias CustomEventHandler = bool delegate (Object o) nothrow;
static struct EventHandlerEntry {
CustomEventHandler dg;
uint id;
}
uint lastUsedHandlerId;
EventHandlerEntry[] eventHandlers;
QueuedEvent[] eventQueue = null;
uint eventQueueUsed = 0; // to avoid `.assumeSafeAppend` and length changes
bool inCustomEventProcessor = false; // required to properly remove events
// process queued events and call custom event handlers
// this will not process events posted from called handlers (such events are postponed for the next iteration)
void processCustomEvents () {
bool hasSomethingToDo = false;
uint ecount;
bool ocep;
synchronized(this) {
ocep = inCustomEventProcessor;
inCustomEventProcessor = true;
ecount = eventQueueUsed; // user may want to post new events from an event handler; process 'em on next iteration
auto ctt = MonoTime.currTime;
bool hasEmpty = false;
// mark events to process (this is required for `eventQueued()`)
foreach (ref qe; eventQueue[0..ecount]) {
if (qe.evt is null) { hasEmpty = true; continue; }
if (qe.timed) {
qe.doProcess = (qe.hittime <= ctt);
} else {
qe.doProcess = true;
}
hasSomethingToDo = (hasSomethingToDo || qe.doProcess);
}
if (!hasSomethingToDo) {
// remove empty events
if (hasEmpty) {
uint eidx = 0, ec = eventQueueUsed;
auto eptr = eventQueue.ptr;
while (eidx < ec) {
if (eptr.evt is null) {
foreach (immutable c; eidx+1..ec) eventQueue.ptr[c-1] = eventQueue.ptr[c];
ec = --eventQueueUsed;
eventQueue.ptr[ec].evt = null; // make GC life easier
} else {
++eidx;
++eptr;
}
}
}
inCustomEventProcessor = ocep;
return;
}
}
// process marked events
uint efree = 0; // non-processed events will be put at this index
EventHandlerEntry[] eh;
Object evt;
foreach (immutable eidx; 0..ecount) {
synchronized(this) {
if (!eventQueue[eidx].doProcess) {
// skip this event
assert(efree <= eidx);
if (efree != eidx) {
// copy this event to queue start
eventQueue[efree] = eventQueue[eidx];
eventQueue[eidx].evt = null; // just in case
}
++efree;
continue;
}
evt = eventQueue[eidx].evt;
eventQueue[eidx].evt = null; // in case event handler will hit GC
if (evt is null) continue; // just in case
// try all handlers; this can be slow, but meh...
eh = eventHandlers;
}
foreach (ref evhan; eh) if (evhan.dg !is null) evhan.dg(evt);
evt = null;
eh = null;
}
synchronized(this) {
// move all unprocessed events to queue top; efree holds first "free index"
foreach (immutable eidx; ecount..eventQueueUsed) {
assert(efree <= eidx);
if (efree != eidx) eventQueue[efree] = eventQueue[eidx];
++efree;
}
eventQueueUsed = efree;
// wake up event processor on next event loop iteration if we have more queued events
// also, remove empty events
bool awaken = false;
uint eidx = 0, ec = eventQueueUsed;
auto eptr = eventQueue.ptr;
while (eidx < ec) {
if (eptr.evt is null) {
foreach (immutable c; eidx+1..ec) eventQueue.ptr[c-1] = eventQueue.ptr[c];
ec = --eventQueueUsed;
eventQueue.ptr[ec].evt = null; // make GC life easier
} else {
if (!awaken && !eptr.timed) { eventWakeUp(); awaken = true; }
++eidx;
++eptr;
}
}
inCustomEventProcessor = ocep;
}
}
// for all windows in nativeMapping
static void processAllCustomEvents () {
foreach (SimpleWindow sw; SimpleWindow.nativeMapping.byValue) {
if (sw is null || sw.closed) continue;
sw.processCustomEvents();
}
}
// 0: infinite (i.e. no scheduled events in queue)
uint eventQueueTimeoutMSecs () {
synchronized(this) {
if (eventQueueUsed == 0) return 0;
if (inCustomEventProcessor) assert(0, "WUTAFUUUUUUU..."); // the thing that should not be. ABSOLUTELY! (c)
uint res = int.max;
auto ctt = MonoTime.currTime;
foreach (const ref qe; eventQueue[0..eventQueueUsed]) {
if (qe.evt is null) assert(0, "WUTAFUUUUUUU..."); // the thing that should not be. ABSOLUTELY! (c)
if (qe.doProcess) continue; // just in case
if (!qe.timed) return 1; // minimal
if (qe.hittime <= ctt) return 1; // minimal
auto tms = (qe.hittime-ctt).total!"msecs";
if (tms < 1) tms = 1; // safety net
if (tms >= int.max) tms = int.max-1; // and another safety net
if (res > tms) res = cast(uint)tms;
}
return (res >= int.max ? 0 : res);
}
}
// for all windows in nativeMapping
static uint eventAllQueueTimeoutMSecs () {
uint res = uint.max;
foreach (SimpleWindow sw; SimpleWindow.nativeMapping.byValue) {
if (sw is null || sw.closed) continue;
uint to = sw.eventQueueTimeoutMSecs();
if (to && to < res) {
res = to;
if (to == 1) break; // can't have less than this
}
}
return (res >= int.max ? 0 : res);
}
}
/// Represents a mouse cursor (aka the mouse pointer, the image seen on screen that indicates where the mouse is pointing).
/// See [GenericCursor]
class MouseCursor {
int osId;
bool isStockCursor;
private this(int osId) {
this.osId = osId;
this.isStockCursor = true;
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms648385(v=vs.85).aspx
this(int xHotSpot, int yHotSpot, ubyte[] andMask, ubyte[] xorMask) {}
version(Windows) {
HCURSOR cursor_;
HCURSOR cursorHandle() {
if(cursor_ is null)
cursor_ = LoadCursor(null, MAKEINTRESOURCE(osId));
return cursor_;
}
} else static if(UsingSimpledisplayX11) {
Cursor cursor_ = None;
int xDisplaySequence;
Cursor cursorHandle() {
if(this.osId == None)
return None;
// we need to reload if we on a new X connection
if(cursor_ == None || XDisplayConnection.connectionSequenceNumber != xDisplaySequence) {
cursor_ = XCreateFontCursor(XDisplayConnection.get(), this.osId);
xDisplaySequence = XDisplayConnection.connectionSequenceNumber;
}
return cursor_;
}
}
}
// https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
// https://tronche.com/gui/x/xlib/appendix/b/
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms648391(v=vs.85).aspx
/// Note that there is no exact appearance guaranteed for any of these items; it may change appearance on different operating systems or future simpledisplay versions
enum GenericCursorType {
Default, /// The default arrow pointer.
Wait, /// A cursor indicating something is loading and the user must wait.
Hand, /// A pointing finger, like the one used hovering over hyperlinks in a web browser.
Help, /// A cursor indicating the user can get help about the pointer location.
Cross, /// A crosshair.
Text, /// An i-beam shape, typically used to indicate text selection is possible.
Move, /// Pointer indicating movement is possible. May also be used as SizeAll
UpArrow, /// An arrow pointing straight up.
Progress, /// The hourglass and arrow, indicating the computer is working but the user can still work. Not great results on X11.
NotAllowed, /// Indicates the current operation is not allowed. Not great results on X11.
SizeNesw, /// Arrow pointing northeast and southwest (lower-left corner resize indicator)
SizeNs, /// Arrow pointing north and south (upper/lower edge resize indicator)
SizeNwse, /// Arrow pointing northwest and southeast (upper-left corner resize indicator)
SizeWe, /// Arrow pointing west and east (left/right edge resize indicator)
}
/*
X_plus == css cell == Windows ?
*/
/// You get one by `GenericCursor.SomeTime`. See [GenericCursorType] for a list of types.
static struct GenericCursor {
static:
///
MouseCursor opDispatch(string str)() if(__traits(hasMember, GenericCursorType, str)) {
static MouseCursor mc;
auto type = __traits(getMember, GenericCursorType, str);
if(mc is null) {
version(Windows) {
int osId;
final switch(type) {
case GenericCursorType.Default: osId = IDC_ARROW; break;
case GenericCursorType.Wait: osId = IDC_WAIT; break;
case GenericCursorType.Hand: osId = IDC_HAND; break;
case GenericCursorType.Help: osId = IDC_HELP; break;
case GenericCursorType.Cross: osId = IDC_CROSS; break;
case GenericCursorType.Text: osId = IDC_IBEAM; break;
case GenericCursorType.Move: osId = IDC_SIZEALL; break;
case GenericCursorType.UpArrow: osId = IDC_UPARROW; break;
case GenericCursorType.Progress: osId = IDC_APPSTARTING; break;
case GenericCursorType.NotAllowed: osId = IDC_NO; break;
case GenericCursorType.SizeNesw: osId = IDC_SIZENESW; break;
case GenericCursorType.SizeNs: osId = IDC_SIZENS; break;
case GenericCursorType.SizeNwse: osId = IDC_SIZENWSE; break;
case GenericCursorType.SizeWe: osId = IDC_SIZEWE; break;
}
} else static if(UsingSimpledisplayX11) {
int osId;
final switch(type) {
case GenericCursorType.Default: osId = None; break;
case GenericCursorType.Wait: osId = 150 /* XC_watch */; break;
case GenericCursorType.Hand: osId = 60 /* XC_hand2 */; break;
case GenericCursorType.Help: osId = 92 /* XC_question_arrow */; break;
case GenericCursorType.Cross: osId = 34 /* XC_crosshair */; break;
case GenericCursorType.Text: osId = 152 /* XC_xterm */; break;
case GenericCursorType.Move: osId = 52 /* XC_fleur */; break;
case GenericCursorType.UpArrow: osId = 22 /* XC_center_ptr */; break;
case GenericCursorType.Progress: osId = 150 /* XC_watch, best i can do i think */; break;
case GenericCursorType.NotAllowed: osId = 24 /* XC_circle. not great */; break;
case GenericCursorType.SizeNesw: osId = 12 /* XC_bottom_left_corner */ ; break;
case GenericCursorType.SizeNs: osId = 116 /* XC_sb_v_double_arrow */; break;
case GenericCursorType.SizeNwse: osId = 14 /* XC_bottom_right_corner */; break;
case GenericCursorType.SizeWe: osId = 108 /* XC_sb_h_double_arrow */; break;
}
} else featureNotImplemented();
mc = new MouseCursor(osId);
}
return mc;
}
}
/++
If you want to get more control over the event loop, you can use this.
Typically though, you can just call [SimpleWindow.eventLoop].
+/
struct EventLoop {
@disable this();
static EventLoop get() {
return EventLoop(0, null);
}
this(long pulseTimeout, void delegate() handlePulse) {
if(impl is null)
impl = new EventLoopImpl(pulseTimeout, handlePulse);
else {
if(pulseTimeout) {
impl.pulseTimeout = pulseTimeout;
impl.handlePulse = handlePulse;
}
}
impl.refcount++;
}
~this() {
if(impl is null)
return;
impl.refcount--;
if(impl.refcount == 0)
impl.dispose();
}
this(this) {
if(impl is null)
return;
impl.refcount++;
}
int run(bool delegate() whileCondition = null) {
assert(impl !is null);
impl.notExited = true;
return impl.run(whileCondition);
}
void exit() {
assert(impl !is null);
impl.notExited = false;
}
static EventLoopImpl* impl;
}
version(linux)
void delegate(int, int) globalHupHandler;
version(linux)
void makeNonBlocking(int fd) {
import fcntl = core.sys.posix.fcntl;
auto flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0);
if(flags == -1)
throw new Exception("fcntl get");
flags |= fcntl.O_NONBLOCK;
auto s = fcntl.fcntl(fd, fcntl.F_SETFL, flags);
if(s == -1)
throw new Exception("fcntl set");
}
struct EventLoopImpl {
int refcount;
bool notExited = true;
version(linux) {
static import ep = core.sys.linux.epoll;
static import unix = core.sys.posix.unistd;
static import err = core.stdc.errno;
import core.sys.linux.timerfd;
}
version(X11) {
int pulseFd = -1;
version(linux) ep.epoll_event[16] events = void;
} else version(Windows) {
Timer pulser;
HANDLE[] handles;
}
/// "Lock" this window handle, to do multithreaded synchronization. You probably won't need
/// to call this, as it's not recommended to share window between threads.
void mtLock () {
version(X11) {
XLockDisplay(this.display);
}
}
version(X11)
auto display() { return XDisplayConnection.get; }
/// "Unlock" this window handle, to do multithreaded synchronization. You probably won't need
/// to call this, as it's not recommended to share window between threads.
void mtUnlock () {
version(X11) {
XUnlockDisplay(this.display);
}
}
version(with_eventloop)
void initialize(long pulseTimeout) {}
else
void initialize(long pulseTimeout) {
version(Windows) {
if(pulseTimeout)
pulser = new Timer(cast(int) pulseTimeout, handlePulse);
if (customEventH is null) {
customEventH = CreateEvent(null, FALSE/*autoreset*/, FALSE/*initial state*/, null);
if (customEventH !is null) {
handles ~= customEventH;
} else {
// this is something that should not be; better be safe than sorry
throw new Exception("can't create eventfd for custom event processing");
}
}
SimpleWindow.processAllCustomEvents(); // process events added before event object creation
}
version(linux) {
prepareEventLoop();
{
auto display = XDisplayConnection.get;
// adding Xlib file
ep.epoll_event ev = void;
{ import core.stdc.string : memset; memset(&ev, 0, ev.sizeof); } // this makes valgrind happy
ev.events = ep.EPOLLIN;
ev.data.fd = display.fd;
//import std.conv;
if(ep.epoll_ctl(epollFd, ep.EPOLL_CTL_ADD, display.fd, &ev) == -1)
throw new Exception("add x fd");// ~ to!string(epollFd));
displayFd = display.fd;
}
if(pulseTimeout) {
pulseFd = timerfd_create(CLOCK_MONOTONIC, 0);
if(pulseFd == -1)
throw new Exception("pulse timer create failed");
itimerspec value;
value.it_value.tv_sec = cast(int) (pulseTimeout / 1000);
value.it_value.tv_nsec = (pulseTimeout % 1000) * 1000_000;
value.it_interval.tv_sec = cast(int) (pulseTimeout / 1000);
value.it_interval.tv_nsec = (pulseTimeout % 1000) * 1000_000;
if(timerfd_settime(pulseFd, 0, &value, null) == -1)
throw new Exception("couldn't make pulse timer");
ep.epoll_event ev = void;
{ import core.stdc.string : memset; memset(&ev, 0, ev.sizeof); } // this makes valgrind happy
ev.events = ep.EPOLLIN;
ev.data.fd = pulseFd;
ep.epoll_ctl(epollFd, ep.EPOLL_CTL_ADD, pulseFd, &ev);
}
// eventfd for custom events
if (customEventFD == -1) {
customEventFD = eventfd(0, 0);
if (customEventFD >= 0) {
ep.epoll_event ev = void;
{ import core.stdc.string : memset; memset(&ev, 0, ev.sizeof); } // this makes valgrind happy
ev.events = ep.EPOLLIN;
ev.data.fd = customEventFD;
ep.epoll_ctl(epollFd, ep.EPOLL_CTL_ADD, customEventFD, &ev);
} else {
// this is something that should not be; better be safe than sorry
throw new Exception("can't create eventfd for custom event processing");
}
}
}
SimpleWindow.processAllCustomEvents(); // process events added before event FD creation
version(linux) {
this.mtLock();
scope(exit) this.mtUnlock();
XPending(display); // no, really
}
disposed = false;
}
bool disposed = true;
version(X11)
int displayFd = -1;
version(with_eventloop)
void dispose() {}
else
void dispose() {
disposed = true;
version(X11) {
if(pulseFd != -1) {
import unix = core.sys.posix.unistd;
unix.close(pulseFd);
pulseFd = -1;
}
version(linux)
if(displayFd != -1) {
// clean up xlib fd when we exit, in case we come back later e.g. X disconnect and reconnect with new FD, don't want to still keep the old one around
ep.epoll_event ev = void;
{ import core.stdc.string : memset; memset(&ev, 0, ev.sizeof); } // this makes valgrind happy
ev.events = ep.EPOLLIN;
ev.data.fd = displayFd;
//import std.conv;
ep.epoll_ctl(epollFd, ep.EPOLL_CTL_DEL, displayFd, &ev);
displayFd = -1;
}
} else version(Windows) {
if(pulser !is null) {
pulser.destroy();
pulser = null;
}
if (customEventH !is null) {
CloseHandle(customEventH);
customEventH = null;
}
}
}
this(long pulseTimeout, void delegate() handlePulse) {
this.pulseTimeout = pulseTimeout;
this.handlePulse = handlePulse;
initialize(pulseTimeout);
}
private long pulseTimeout;
void delegate() handlePulse;
~this() {
dispose();
}
version(X11)
ref int customEventFD() { return SimpleWindow.customEventFD; }
version(Windows)
ref auto customEventH() { return SimpleWindow.customEventH; }
version(with_eventloop) {
int loopHelper(bool delegate() whileCondition) {
// FIXME: whileCondition
import arsd.eventloop;
loop();
return 0;
}
} else
int loopHelper(bool delegate() whileCondition) {
version(X11) {
bool done = false;
XFlush(display);
insideXEventLoop = true;
scope(exit) insideXEventLoop = false;
version(linux) {
while(!done && (whileCondition is null || whileCondition() == true) && notExited) {
bool forceXPending = false;
auto wto = SimpleWindow.eventAllQueueTimeoutMSecs();
// eh... some events may be queued for "squashing" (or "late delivery"), so we have to do the following magic
{
this.mtLock();
scope(exit) this.mtUnlock();
if (XEventsQueued(this.display, QueueMode.QueuedAlready)) { forceXPending = true; if (wto > 10 || wto <= 0) wto = 10; } // so libX event loop will be able to do it's work
}
//{ import core.stdc.stdio; printf("*** wto=%d; force=%d\n", wto, (forceXPending ? 1 : 0)); }
auto nfds = ep.epoll_wait(epollFd, events.ptr, events.length, (wto == 0 || wto >= int.max ? -1 : cast(int)wto));
if(nfds == -1) {
if(err.errno == err.EINTR) {
continue; // interrupted by signal, just try again
}
throw new Exception("epoll wait failure");
}
SimpleWindow.processAllCustomEvents(); // anyway
//version(sdddd) { import std.stdio; writeln("nfds=", nfds, "; [0]=", events[0].data.fd); }
foreach(idx; 0 .. nfds) {
if(done) break;
auto fd = events[idx].data.fd;
assert(fd != -1); // should never happen cuz the api doesn't do that but better to assert than assume.
auto flags = events[idx].events;
if(flags & ep.EPOLLIN) {
if(fd == display.fd) {
version(sdddd) { import std.stdio; writeln("X EVENT PENDING!"); }
this.mtLock();
scope(exit) this.mtUnlock();
while(!done && XPending(display)) {
done = doXNextEvent(this.display);
}
forceXPending = false;
} else if(fd == pulseFd) {
long expirationCount;
// if we go over the count, I ignore it because i don't want the pulse to go off more often and eat tons of cpu time...
handlePulse();
// read just to clear the buffer so poll doesn't trigger again
// BTW I read AFTER the pulse because if the pulse handler takes
// a lot of time to execute, we don't want the app to get stuck
// in a loop of timer hits without a chance to do anything else
//
// IOW handlePulse happens at most once per pulse interval.
unix.read(pulseFd, &expirationCount, expirationCount.sizeof);
} else if (fd == customEventFD) {
// we have some custom events; process 'em
import core.sys.posix.unistd : read;
ulong n;
read(customEventFD, &n, n.sizeof); // reset counter value to zero again
//{ import core.stdc.stdio; printf("custom event! count=%u\n", eventQueueUsed); }
//SimpleWindow.processAllCustomEvents();
} else {
// some other timer
version(sdddd) { import std.stdio; writeln("unknown fd: ", fd); }
if(Timer* t = fd in Timer.mapping)
(*t).trigger();
if(PosixFdReader* pfr = fd in PosixFdReader.mapping)
(*pfr).ready(flags);
// or i might add support for other FDs too
// but for now it is just timer
// (if you want other fds, use arsd.eventloop and compile with -version=with_eventloop), it offers a fuller api for arbitrary stuff.
}
}
if(flags & ep.EPOLLHUP) {
if(PosixFdReader* pfr = fd in PosixFdReader.mapping)
(*pfr).hup(flags);
if(globalHupHandler)
globalHupHandler(fd, flags);
}
/+
} else {
// not interested in OUT, we are just reading here.
//
// error or hup might also be reported
// but it shouldn't here since we are only
// using a few types of FD and Xlib will report
// if it dies.
// so instead of thoughtfully handling it, I'll
// just throw. for now at least
throw new Exception("epoll did something else");
}
+/
}
// if we won't call `XPending()` here, libX may delay some internal event delivery.
// i.e. we HAVE to repeatedly call `XPending()` even if libX fd wasn't signalled!
if (!done && forceXPending) {
this.mtLock();
scope(exit) this.mtUnlock();
//{ import core.stdc.stdio; printf("*** queued: %d\n", XEventsQueued(this.display, QueueMode.QueuedAlready)); }
while(!done && XPending(display)) {
done = doXNextEvent(this.display);
}
}
}
} else {
// Generic fallback: yes to simple pulse support,
// but NO timer support!
// FIXME: we could probably support the POSIX timer_create
// signal-based option, but I'm in no rush to write it since
// I prefer the fd-based functions.
while (!done && (whileCondition is null || whileCondition() == true) && notExited) {
while(!done &&
(pulseTimeout == 0 || (XPending(display) > 0)))
{
this.mtLock();
scope(exit) this.mtUnlock();
done = doXNextEvent(this.display);
}
if(!done && pulseTimeout !=0) {
if(handlePulse !is null)
handlePulse();
import core.thread;
Thread.sleep(dur!"msecs"(pulseTimeout));
}
}
}
}
version(Windows) {
int ret = -1;
MSG message;
while(ret != 0 && (whileCondition is null || whileCondition() == true) && notExited) {
auto wto = SimpleWindow.eventAllQueueTimeoutMSecs();
auto waitResult = MsgWaitForMultipleObjectsEx(
cast(int) handles.length, handles.ptr,
(wto == 0 ? INFINITE : wto), /* timeout */
0x04FF, /* QS_ALLINPUT */
0x0002 /* MWMO_ALERTABLE */ | 0x0004 /* MWMO_INPUTAVAILABLE */);
SimpleWindow.processAllCustomEvents(); // anyway
enum WAIT_OBJECT_0 = 0;
if(waitResult >= WAIT_OBJECT_0 && waitResult < handles.length + WAIT_OBJECT_0) {
auto h = handles[waitResult - WAIT_OBJECT_0];
if(auto e = h in WindowsHandleReader.mapping) {
(*e).ready();
}
} else if(waitResult == handles.length + WAIT_OBJECT_0) {
// message ready
while(PeekMessage(&message, null, 0, 0, PM_NOREMOVE)) { // need to peek since sometimes MsgWaitForMultipleObjectsEx returns even though GetMessage can block. tbh i don't fully understand it but the docs say it is foreground activation
ret = GetMessage(&message, null, 0, 0);
if(ret == -1)
throw new Exception("GetMessage failed");
TranslateMessage(&message);
DispatchMessage(&message);
if(ret == 0) // WM_QUIT
break;
}
} else if(waitResult == 0x000000C0L /* WAIT_IO_COMPLETION */) {
SleepEx(0, true); // I call this to give it a chance to do stuff like async io
} else if(waitResult == 258L /* WAIT_TIMEOUT */) {
// timeout, should never happen since we aren't using it
} else if(waitResult == 0xFFFFFFFF) {
// failed
throw new Exception("MsgWaitForMultipleObjectsEx failed");
} else {
// idk....
}
}
// return message.wParam;
return 0;
} else {
return 0;
}
}
int run(bool delegate() whileCondition = null) {
if(disposed)
initialize(this.pulseTimeout);
version(X11) {
try {
return loopHelper(whileCondition);
} catch(XDisconnectException e) {
if(e.userRequested) {
foreach(item; CapableOfHandlingNativeEvent.nativeHandleMapping)
item.discardConnectionState();
XCloseDisplay(XDisplayConnection.display);
}
XDisplayConnection.display = null;
this.dispose();
throw e;
}
} else {
return loopHelper(whileCondition);
}
}
}
/++
Provides an icon on the system notification area (also known as the system tray).
If a notification area is not available with the NotificationIcon object is created,
it will silently succeed and simply attempt to create one when an area becomes available.
NotificationAreaIcon on Windows assumes you are on Windows Vista or later.
If this is wrong, pass -version=WindowsXP to dmd when compiling and it will
use the older version.
+/
version(OSXCocoa) {} else // NotYetImplementedException
class NotificationAreaIcon : CapableOfHandlingNativeEvent {
version(X11) {
void recreateAfterDisconnect() {
stateDiscarded = false;
clippixmap = None;
throw new Exception("NOT IMPLEMENTED");
}
bool stateDiscarded;
void discardConnectionState() {
stateDiscarded = true;
}
}
version(X11) {
Image img;
NativeEventHandler getNativeEventHandler() {
return delegate int(XEvent e) {
switch(e.type) {
case EventType.Expose:
//case EventType.VisibilityNotify:
redraw();
break;
case EventType.ClientMessage:
version(sddddd) {
import std.stdio;
writeln("\t", e.xclient.message_type == GetAtom!("_XEMBED")(XDisplayConnection.get));
writeln("\t", e.xclient.format);
writeln("\t", e.xclient.data.l);
}
break;
case EventType.ButtonPress:
auto event = e.xbutton;
if (onClick !is null || onClickEx !is null) {
MouseButton mb = cast(MouseButton)0;
switch (event.button) {
case 1: mb = MouseButton.left; break; // left
case 2: mb = MouseButton.middle; break; // middle
case 3: mb = MouseButton.right; break; // right
case 4: mb = MouseButton.wheelUp; break; // scroll up
case 5: mb = MouseButton.wheelDown; break; // scroll down
case 6: break; // idk
case 7: break; // idk
case 8: mb = MouseButton.backButton; break;
case 9: mb = MouseButton.forwardButton; break;
default:
}
if (mb) {
try { onClick()(mb); } catch (Exception) {}
if (onClickEx !is null) try { onClickEx(event.x_root, event.y_root, mb, cast(ModifierState)event.state); } catch (Exception) {}
}
}
break;
case EventType.EnterNotify:
if (onEnter !is null) {
onEnter(e.xcrossing.x_root, e.xcrossing.y_root, cast(ModifierState)e.xcrossing.state);
}
break;
case EventType.LeaveNotify:
if (onLeave !is null) try { onLeave(); } catch (Exception) {}
break;
case EventType.DestroyNotify:
active = false;
CapableOfHandlingNativeEvent.nativeHandleMapping.remove(nativeHandle);
break;
case EventType.ConfigureNotify:
auto event = e.xconfigure;
this.width = event.width;
this.height = event.height;
//import std.stdio; writeln(width, " x " , height, " @ ", event.x, " ", event.y);
redraw();
break;
default: return 1;
}
return 1;
};
}
/* private */ void hideBalloon() {
balloon.close();
version(with_timer)
timer.destroy();
balloon = null;
version(with_timer)
timer = null;
}
void redraw() {
if (!active) return;
auto display = XDisplayConnection.get;
auto gc = DefaultGC(display, DefaultScreen(display));
XClearWindow(display, nativeHandle);
XSetClipMask(display, gc, clippixmap);
XSetForeground(display, gc,
cast(uint) 0 << 16 |
cast(uint) 0 << 8 |
cast(uint) 0);
XFillRectangle(display, nativeHandle, gc, 0, 0, width, height);
if (img is null) {
XSetForeground(display, gc,
cast(uint) 0 << 16 |
cast(uint) 127 << 8 |
cast(uint) 0);
XFillArc(display, nativeHandle,
gc, width / 4, height / 4, width * 2 / 4, height * 2 / 4, 0 * 64, 360 * 64);
} else {
int dx = 0;
int dy = 0;
if(width > img.width)
dx = (width - img.width) / 2;
if(height > img.height)
dy = (height - img.height) / 2;
XSetClipOrigin(display, gc, dx, dy);
if (img.usingXshm)
XShmPutImage(display, cast(Drawable)nativeHandle, gc, img.handle, 0, 0, dx, dy, img.width, img.height, false);
else
XPutImage(display, cast(Drawable)nativeHandle, gc, img.handle, 0, 0, dx, dy, img.width, img.height);
}
XSetClipMask(display, gc, None);
flushGui();
}
static Window getTrayOwner() {
auto display = XDisplayConnection.get;
auto i = cast(int) DefaultScreen(display);
if(i < 10 && i >= 0) {
static Atom atom;
if(atom == None)
atom = XInternAtom(display, cast(char*) ("_NET_SYSTEM_TRAY_S"~(cast(char) (i + '0')) ~ '\0').ptr, false);
return XGetSelectionOwner(display, atom);
}
return None;
}
static void sendTrayMessage(arch_long message, arch_long d1, arch_long d2, arch_long d3) {
auto to = getTrayOwner();
auto display = XDisplayConnection.get;
XEvent ev;
ev.xclient.type = EventType.ClientMessage;
ev.xclient.window = to;
ev.xclient.message_type = GetAtom!("_NET_SYSTEM_TRAY_OPCODE", true)(display);
ev.xclient.format = 32;
ev.xclient.data.l[0] = CurrentTime;
ev.xclient.data.l[1] = message;
ev.xclient.data.l[2] = d1;
ev.xclient.data.l[3] = d2;
ev.xclient.data.l[4] = d3;
XSendEvent(XDisplayConnection.get, to, false, EventMask.NoEventMask, &ev);
}
private static NotificationAreaIcon[] activeIcons;
// FIXME: possible leak with this stuff, should be able to clear it and stuff.
private void newManager() {
close();
createXWin();
if(this.clippixmap)
XFreePixmap(XDisplayConnection.get, clippixmap);
if(this.originalMemoryImage)
this.icon = this.originalMemoryImage;
else if(this.img)
this.icon = this.img;
}
private void createXWin () {
// create window
auto display = XDisplayConnection.get;
// to check for MANAGER on root window to catch new/changed tray owners
XDisplayConnection.addRootInput(EventMask.StructureNotifyMask);
// so if a thing does appear, we can handle it
foreach(ai; activeIcons)
if(ai is this)
goto alreadythere;
activeIcons ~= this;
alreadythere:
// and check for an existing tray
auto trayOwner = getTrayOwner();
if(trayOwner == None)
return;
//throw new Exception("No notification area found");
Visual* v = cast(Visual*) CopyFromParent;
/+
auto visualProp = getX11PropertyData(trayOwner, GetAtom!("_NET_SYSTEM_TRAY_VISUAL", true)(display));
if(visualProp !is null) {
c_ulong[] info = cast(c_ulong[]) visualProp;
if(info.length == 1) {
auto vid = info[0];
int returned;
XVisualInfo t;
t.visualid = vid;
auto got = XGetVisualInfo(display, VisualIDMask, &t, &returned);
if(got !is null) {
if(returned == 1) {
v = got.visual;
import std.stdio;
writeln("using special visual ", *got);
}
XFree(got);
}
}
}
+/
auto nativeWindow = XCreateWindow(display, RootWindow(display, DefaultScreen(display)), 0, 0, 16, 16, 0, 24, InputOutput, v, 0, null);
assert(nativeWindow);
XSetWindowBackgroundPixmap(display, nativeWindow, 1 /* ParentRelative */);
nativeHandle = nativeWindow;
///+
arch_ulong[2] info;
info[0] = 0;
info[1] = 1;
string title = this.name is null ? "simpledisplay.d program" : this.name;
auto XA_UTF8 = XInternAtom(display, "UTF8_STRING".ptr, false);
auto XA_NETWM_NAME = XInternAtom(display, "_NET_WM_NAME".ptr, false);
XChangeProperty(display, nativeWindow, XA_NETWM_NAME, XA_UTF8, 8, PropModeReplace, title.ptr, cast(uint)title.length);
XChangeProperty(
display,
nativeWindow,
GetAtom!("_XEMBED_INFO", true)(display),
GetAtom!("_XEMBED_INFO", true)(display),
32 /* bits */,
0 /*PropModeReplace*/,
info.ptr,
2);
import core.sys.posix.unistd;
arch_ulong pid = getpid();
XChangeProperty(
display,
nativeWindow,
GetAtom!("_NET_WM_PID", true)(display),
XA_CARDINAL,
32 /* bits */,
0 /*PropModeReplace*/,
&pid,
1);
updateNetWmIcon();
if (sdpyWindowClassStr !is null && sdpyWindowClassStr[0]) {
//{ import core.stdc.stdio; printf("winclass: [%s]\n", sdpyWindowClassStr); }
XClassHint klass;
XWMHints wh;
XSizeHints size;
klass.res_name = sdpyWindowClassStr;
klass.res_class = sdpyWindowClassStr;
XSetWMProperties(display, nativeWindow, null, null, null, 0, &size, &wh, &klass);
}
// believe it or not, THIS is what xfce needed for the 9999 issue
XSizeHints sh;
c_long spr;
XGetWMNormalHints(display, nativeWindow, &sh, &spr);
sh.flags |= PMaxSize | PMinSize;
// FIXME maybe nicer resizing
sh.min_width = 16;
sh.min_height = 16;
sh.max_width = 16;
sh.max_height = 16;
XSetWMNormalHints(display, nativeWindow, &sh);
//+/
XSelectInput(display, nativeWindow,
EventMask.ButtonPressMask | EventMask.ExposureMask | EventMask.StructureNotifyMask | EventMask.VisibilityChangeMask |
EventMask.EnterWindowMask | EventMask.LeaveWindowMask);
sendTrayMessage(SYSTEM_TRAY_REQUEST_DOCK, nativeWindow, 0, 0);
CapableOfHandlingNativeEvent.nativeHandleMapping[nativeWindow] = this;
active = true;
}
void updateNetWmIcon() {
if(img is null) return;
auto display = XDisplayConnection.get;
// FIXME: ensure this is correct
arch_ulong[] buffer;
auto imgMi = img.toTrueColorImage;
buffer ~= imgMi.width;
buffer ~= imgMi.height;
foreach(c; imgMi.imageData.colors) {
arch_ulong b;
b |= c.a << 24;
b |= c.r << 16;
b |= c.g << 8;
b |= c.b;
buffer ~= b;
}
XChangeProperty(
display,
nativeHandle,
GetAtom!"_NET_WM_ICON"(display),
GetAtom!"CARDINAL"(display),
32 /* bits */,
0 /*PropModeReplace*/,
buffer.ptr,
cast(int) buffer.length);
}
private SimpleWindow balloon;
version(with_timer)
private Timer timer;
private Window nativeHandle;
private Pixmap clippixmap = None;
private int width = 16;
private int height = 16;
private bool active = false;
void delegate (int x, int y, MouseButton button, ModifierState mods) onClickEx; /// x and y are globals (relative to root window). X11 only.
void delegate (int x, int y, ModifierState mods) onEnter; /// x and y are global window coordinates. X11 only.
void delegate () onLeave; /// X11 only.
@property bool closed () const pure nothrow @safe @nogc { return !active; } ///
/// X11 only. Get global window coordinates and size. This can be used to show various notifications.
void getWindowRect (out int x, out int y, out int width, out int height) {
if (!active) { width = 1; height = 1; return; } // 1: just in case
Window dummyw;
auto dpy = XDisplayConnection.get;
//XWindowAttributes xwa;
//XGetWindowAttributes(dpy, nativeHandle, &xwa);
//XTranslateCoordinates(dpy, nativeHandle, RootWindow(dpy, DefaultScreen(dpy)), xwa.x, xwa.y, &x, &y, &dummyw);
XTranslateCoordinates(dpy, nativeHandle, RootWindow(dpy, DefaultScreen(dpy)), x, y, &x, &y, &dummyw);
width = this.width;
height = this.height;
}
}
/+
What I actually want from this:
* set / change: icon, tooltip
* handle: mouse click, right click
* show: notification bubble.
+/
version(Windows) {
WindowsIcon win32Icon;
HWND hwnd;
NOTIFYICONDATAW data;
NativeEventHandler getNativeEventHandler() {
return delegate int(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
if(msg == WM_USER) {
auto event = LOWORD(lParam);
auto iconId = HIWORD(lParam);
//auto x = GET_X_LPARAM(wParam);
//auto y = GET_Y_LPARAM(wParam);
switch(event) {
case WM_LBUTTONDOWN:
onClick()(MouseButton.left);
break;
case WM_RBUTTONDOWN:
onClick()(MouseButton.right);
break;
case WM_MBUTTONDOWN:
onClick()(MouseButton.middle);
break;
case WM_MOUSEMOVE:
// sent, we could use it.
break;
case WM_MOUSEWHEEL:
// NOT SENT
break;
//case NIN_KEYSELECT:
//case NIN_SELECT:
//break;
default: {}
}
}
return 0;
};
}
enum NIF_SHOWTIP = 0x00000080;
private static struct NOTIFYICONDATAW {
DWORD cbSize;
HWND hWnd;
UINT uID;
UINT uFlags;
UINT uCallbackMessage;
HICON hIcon;
WCHAR[128] szTip;
DWORD dwState;
DWORD dwStateMask;
WCHAR[256] szInfo;
union {
UINT uTimeout;
UINT uVersion;
}
WCHAR[64] szInfoTitle;
DWORD dwInfoFlags;
GUID guidItem;
HICON hBalloonIcon;
}
}
/++
Note that on Windows, only left, right, and middle buttons are sent.
Mouse wheel buttons are NOT set, so don't rely on those events if your
program is meant to be used on Windows too.
+/
this(string name, MemoryImage icon, void delegate(MouseButton button) onClick) {
// The canonical constructor for Windows needs the MemoryImage, so it is here,
// but on X, we need an Image, so its canonical ctor is there. They should
// forward to each other though.
version(X11) {
this.name = name;
this.onClick = onClick;
createXWin();
this.icon = icon;
} else version(Windows) {
this.onClick = onClick;
this.win32Icon = new WindowsIcon(icon);
HINSTANCE hInstance = cast(HINSTANCE) GetModuleHandle(null);
static bool registered = false;
if(!registered) {
WNDCLASSEX wc;
wc.cbSize = wc.sizeof;
wc.hInstance = hInstance;
wc.lpfnWndProc = &WndProc;
wc.lpszClassName = "arsd_simpledisplay_notification_icon"w.ptr;
if(!RegisterClassExW(&wc))
throw new WindowsApiException("RegisterClass");
registered = true;
}
this.hwnd = CreateWindowW("arsd_simpledisplay_notification_icon"w.ptr, "test"w.ptr /* name */, 0 /* dwStyle */, 0, 0, 0, 0, HWND_MESSAGE, null, hInstance, null);
if(hwnd is null)
throw new Exception("CreateWindow");
data.cbSize = data.sizeof;
data.hWnd = hwnd;
data.uID = cast(uint) cast(void*) this;
data.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_STATE | NIF_SHOWTIP /* use default tooltip, for now. */;
// NIF_INFO means show balloon
data.uCallbackMessage = WM_USER;
data.hIcon = this.win32Icon.hIcon;
data.szTip = ""; // FIXME
data.dwState = 0; // NIS_HIDDEN; // windows vista
data.dwStateMask = NIS_HIDDEN; // windows vista
data.uVersion = 4; // NOTIFYICON_VERSION_4; // Windows Vista and up
Shell_NotifyIcon(NIM_ADD, cast(NOTIFYICONDATA*) &data);
CapableOfHandlingNativeEvent.nativeHandleMapping[this.hwnd] = this;
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
/// ditto
this(string name, Image icon, void delegate(MouseButton button) onClick) {
version(X11) {
this.onClick = onClick;
this.name = name;
createXWin();
this.icon = icon;
} else version(Windows) {
this(name, icon is null ? null : icon.toTrueColorImage(), onClick);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
version(X11) {
/++
X-specific extension (for now at least)
+/
this(string name, MemoryImage icon, void delegate(int x, int y, MouseButton button, ModifierState mods) onClickEx) {
this.onClickEx = onClickEx;
createXWin();
if (icon !is null) this.icon = icon;
}
/// ditto
this(string name, Image icon, void delegate(int x, int y, MouseButton button, ModifierState mods) onClickEx) {
this.onClickEx = onClickEx;
createXWin();
this.icon = icon;
}
}
private void delegate (MouseButton button) onClick_;
///
@property final void delegate(MouseButton) onClick() {
if(onClick_ is null)
onClick_ = delegate void(MouseButton) {};
return onClick_;
}
/// ditto
@property final void onClick(void delegate(MouseButton) handler) {
// I made this a property setter so we can wrap smaller arg
// delegates and just forward all to onClickEx or something.
onClick_ = handler;
}
string name_;
@property void name(string n) {
name_ = n;
}
@property string name() {
return name_;
}
private MemoryImage originalMemoryImage;
///
@property void icon(MemoryImage i) {
version(X11) {
this.originalMemoryImage = i;
if (!active) return;
if (i !is null) {
this.img = Image.fromMemoryImage(i);
this.clippixmap = transparencyMaskFromMemoryImage(i, nativeHandle);
//import std.stdio; writeln("using pixmap ", clippixmap);
updateNetWmIcon();
redraw();
} else {
if (this.img !is null) {
this.img = null;
redraw();
}
}
} else version(Windows) {
this.win32Icon = new WindowsIcon(i);
data.uFlags = NIF_ICON;
data.hIcon = this.win32Icon.hIcon;
Shell_NotifyIcon(NIM_MODIFY, cast(NOTIFYICONDATA*) &data);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
/// ditto
@property void icon (Image i) {
version(X11) {
if (!active) return;
if (i !is img) {
originalMemoryImage = null;
img = i;
redraw();
}
} else version(Windows) {
this.icon(i is null ? null : i.toTrueColorImage());
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
/++
Shows a balloon notification. You can only show one balloon at a time, if you call
it twice while one is already up, the first balloon will be replaced.
The user is free to block notifications and they will automatically disappear after
a timeout period.
Params:
title = Title of the notification. Must be 40 chars or less or the OS may truncate it.
message = The message to pop up. Must be 220 chars or less or the OS may truncate it.
icon = the icon to display with the notification. If null, it uses your existing icon.
onclick = delegate called if the user clicks the balloon. (not yet implemented)
timeout = your suggested timeout period. The operating system is free to ignore your suggestion.
+/
void showBalloon(string title, string message, MemoryImage icon = null, void delegate() onclick = null, int timeout = 2_500) {
bool useCustom = true;
version(libnotify) {
if(onclick is null) // libnotify impl doesn't support callbacks yet because it doesn't do a dbus message loop
try {
if(!active) return;
if(libnotify is null) {
libnotify = new C_DynamicLibrary("libnotify.so");
libnotify.call!("notify_init", int, const char*)()((ApplicationName ~ "\0").ptr);
}
auto n = libnotify.call!("notify_notification_new", void*, const char*, const char*, const char*)()((title~"\0").ptr, (message~"\0").ptr, null /* icon */);
libnotify.call!("notify_notification_set_timeout", void, void*, int)()(n, timeout);
if(onclick) {
libnotify_action_delegates[libnotify_action_delegates_count] = onclick;
libnotify.call!("notify_notification_add_action", void, void*, const char*, const char*, typeof(&libnotify_action_callback_sdpy), void*, void*)()(n, "DEFAULT".ptr, "Go".ptr, &libnotify_action_callback_sdpy, cast(void*) libnotify_action_delegates_count, null);
libnotify_action_delegates_count++;
}
// FIXME icon
// set hint image-data
// set default action for onclick
void* error;
libnotify.call!("notify_notification_show", bool, void*, void**)()(n, &error);
useCustom = false;
} catch(Exception e) {
}
}
version(X11) {
if(useCustom) {
if(!active) return;
if(balloon) {
hideBalloon();
}
// I know there are two specs for this, but one is never
// implemented by any window manager I have ever seen, and
// the other is a bloated mess and too complicated for simpledisplay...
// so doing my own little window instead.
balloon = new SimpleWindow(380, 120, null, OpenGlOptions.no, Resizability.fixedSize, WindowTypes.notification, WindowFlags.dontAutoShow/*, window*/);
int x, y, width, height;
getWindowRect(x, y, width, height);
int bx = x - balloon.width;
int by = y - balloon.height;
if(bx < 0)
bx = x + width + balloon.width;
if(by < 0)
by = y + height;
// just in case, make sure it is actually on scren
if(bx < 0)
bx = 0;
if(by < 0)
by = 0;
balloon.move(bx, by);
auto painter = balloon.draw();
painter.fillColor = Color(220, 220, 220);
painter.outlineColor = Color.black;
painter.drawRectangle(Point(0, 0), balloon.width, balloon.height);
auto iconWidth = icon is null ? 0 : icon.width;
if(icon)
painter.drawImage(Point(4, 4), Image.fromMemoryImage(icon));
iconWidth += 6; // margin around the icon
// draw a close button
painter.outlineColor = Color(44, 44, 44);
painter.fillColor = Color(255, 255, 255);
painter.drawRectangle(Point(balloon.width - 15, 3), 13, 13);
painter.pen = Pen(Color.black, 3);
painter.drawLine(Point(balloon.width - 14, 4), Point(balloon.width - 4, 14));
painter.drawLine(Point(balloon.width - 4, 4), Point(balloon.width - 14, 13));
painter.pen = Pen(Color.black, 1);
painter.fillColor = Color(220, 220, 220);
// Draw the title and message
painter.drawText(Point(4 + iconWidth, 4), title);
painter.drawLine(
Point(4 + iconWidth, 4 + painter.fontHeight + 1),
Point(balloon.width - 4, 4 + painter.fontHeight + 1),
);
painter.drawText(Point(4 + iconWidth, 4 + painter.fontHeight + 4), message);
balloon.setEventHandlers(
(MouseEvent ev) {
if(ev.type == MouseEventType.buttonPressed) {
if(ev.x > balloon.width - 16 && ev.y < 16)
hideBalloon();
else if(onclick)
onclick();
}
}
);
balloon.show();
version(with_timer)
timer = new Timer(timeout, &hideBalloon);
else {} // FIXME
}
} else version(Windows) {
enum NIF_INFO = 0x00000010;
data.uFlags = NIF_INFO;
// FIXME: go back to the last valid unicode code point
if(title.length > 40)
title = title[0 .. 40];
if(message.length > 220)
message = message[0 .. 220];
enum NIIF_RESPECT_QUIET_TIME = 0x00000080;
enum NIIF_LARGE_ICON = 0x00000020;
enum NIIF_NOSOUND = 0x00000010;
enum NIIF_USER = 0x00000004;
enum NIIF_ERROR = 0x00000003;
enum NIIF_WARNING = 0x00000002;
enum NIIF_INFO = 0x00000001;
enum NIIF_NONE = 0;
WCharzBuffer t = WCharzBuffer(title);
WCharzBuffer m = WCharzBuffer(message);
t.copyInto(data.szInfoTitle);
m.copyInto(data.szInfo);
data.dwInfoFlags = NIIF_RESPECT_QUIET_TIME;
if(icon !is null) {
auto i = new WindowsIcon(icon);
data.hBalloonIcon = i.hIcon;
data.dwInfoFlags |= NIIF_USER;
}
Shell_NotifyIcon(NIM_MODIFY, cast(NOTIFYICONDATA*) &data);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
///
//version(Windows)
void show() {
version(X11) {
if(!hidden)
return;
sendTrayMessage(SYSTEM_TRAY_REQUEST_DOCK, nativeHandle, 0, 0);
hidden = false;
} else version(Windows) {
data.uFlags = NIF_STATE;
data.dwState = 0; // NIS_HIDDEN; // windows vista
data.dwStateMask = NIS_HIDDEN; // windows vista
Shell_NotifyIcon(NIM_MODIFY, cast(NOTIFYICONDATA*) &data);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
version(X11)
bool hidden = false;
///
//version(Windows)
void hide() {
version(X11) {
if(hidden)
return;
hidden = true;
XUnmapWindow(XDisplayConnection.get, nativeHandle);
} else version(Windows) {
data.uFlags = NIF_STATE;
data.dwState = NIS_HIDDEN; // windows vista
data.dwStateMask = NIS_HIDDEN; // windows vista
Shell_NotifyIcon(NIM_MODIFY, cast(NOTIFYICONDATA*) &data);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
///
void close () {
version(X11) {
if (active) {
active = false; // event handler will set this too, but meh
XUnmapWindow(XDisplayConnection.get, nativeHandle); // 'cause why not; let's be polite
XDestroyWindow(XDisplayConnection.get, nativeHandle);
flushGui();
}
} else version(Windows) {
Shell_NotifyIcon(NIM_DELETE, cast(NOTIFYICONDATA*) &data);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
~this() {
version(X11)
if(clippixmap != None)
XFreePixmap(XDisplayConnection.get, clippixmap);
close();
}
}
version(X11)
/// call XFreePixmap on the return value
Pixmap transparencyMaskFromMemoryImage(MemoryImage i, Window window) {
char[] data = new char[](i.width * i.height / 8 + 2);
data[] = 0;
int bitOffset = 0;
foreach(c; i.getAsTrueColorImage().imageData.colors) { // FIXME inefficient unnecessary conversion in palette cases
ubyte v = c.a > 128 ? 1 : 0;
data[bitOffset / 8] |= v << (bitOffset%8);
bitOffset++;
}
auto handle = XCreateBitmapFromData(XDisplayConnection.get, cast(Drawable) window, data.ptr, i.width, i.height);
return handle;
}
// basic functions to make timers
/**
A timer that will trigger your function on a given interval.
You create a timer with an interval and a callback. It will continue
to fire on the interval until it is destroyed.
There are currently no one-off timers (instead, just create one and
destroy it when it is triggered) nor are there pause/resume functions -
the timer must again be destroyed and recreated if you want to pause it.
auto timer = new Timer(50, { it happened!; });
timer.destroy();
Timers can only be expected to fire when the event loop is running.
*/
version(with_timer) {
class Timer {
// FIXME: I might add overloads for ones that take a count of
// how many elapsed since last time (on Windows, it will divide
// the ticks thing given, on Linux it is just available) and
// maybe one that takes an instance of the Timer itself too
/// Create a timer with a callback when it triggers.
this(int intervalInMilliseconds, void delegate() onPulse) {
assert(onPulse !is null);
this.onPulse = onPulse;
version(Windows) {
/*
handle = SetTimer(null, handle, intervalInMilliseconds, &timerCallback);
if(handle == 0)
throw new Exception("SetTimer fail");
*/
// thanks to Archival 998 for the WaitableTimer blocks
handle = CreateWaitableTimer(null, false, null);
long initialTime = 0;
if(handle is null || !SetWaitableTimer(handle, cast(LARGE_INTEGER*)&initialTime, intervalInMilliseconds, &timerCallback, handle, false))
throw new Exception("SetWaitableTimer Failed");
mapping[handle] = this;
} else version(linux) {
static import ep = core.sys.linux.epoll;
import core.sys.linux.timerfd;
fd = timerfd_create(CLOCK_MONOTONIC, 0);
if(fd == -1)
throw new Exception("timer create failed");
mapping[fd] = this;
itimerspec value;
value.it_value.tv_sec = cast(int) (intervalInMilliseconds / 1000);
value.it_value.tv_nsec = (intervalInMilliseconds % 1000) * 1000_000;
value.it_interval.tv_sec = cast(int) (intervalInMilliseconds / 1000);
value.it_interval.tv_nsec = (intervalInMilliseconds % 1000) * 1000_000;
if(timerfd_settime(fd, 0, &value, null) == -1)
throw new Exception("couldn't make pulse timer");
version(with_eventloop) {
import arsd.eventloop;
addFileEventListeners(fd, &trigger, null, null);
} else {
prepareEventLoop();
ep.epoll_event ev = void;
ev.events = ep.EPOLLIN;
ev.data.fd = fd;
ep.epoll_ctl(epollFd, ep.EPOLL_CTL_ADD, fd, &ev);
}
} else featureNotImplemented();
}
/// Stop and destroy the timer object.
void destroy() {
version(Windows) {
if(handle) {
// KillTimer(null, handle);
CancelWaitableTimer(cast(void*)handle);
mapping.remove(handle);
CloseHandle(handle);
handle = null;
}
} else version(linux) {
if(fd != -1) {
import unix = core.sys.posix.unistd;
static import ep = core.sys.linux.epoll;
version(with_eventloop) {
import arsd.eventloop;
removeFileEventListeners(fd);
} else {
ep.epoll_event ev = void;
ev.events = ep.EPOLLIN;
ev.data.fd = fd;
ep.epoll_ctl(epollFd, ep.EPOLL_CTL_DEL, fd, &ev);
}
unix.close(fd);
mapping.remove(fd);
fd = -1;
}
} else featureNotImplemented();
}
~this() {
destroy();
}
void changeTime(int intervalInMilliseconds)
{
version(Windows)
{
if(handle)
{
//handle = SetTimer(null, handle, intervalInMilliseconds, &timerCallback);
long initialTime = 0;
if(handle is null || !SetWaitableTimer(handle, cast(LARGE_INTEGER*)&initialTime, intervalInMilliseconds, &timerCallback, handle, false))
throw new Exception("couldn't change pulse timer");
}
}
}
private:
void delegate() onPulse;
void trigger() {
version(linux) {
import unix = core.sys.posix.unistd;
long val;
unix.read(fd, &val, val.sizeof); // gotta clear the pipe
} else version(Windows) {
} else featureNotImplemented();
onPulse();
}
version(Windows)
extern(Windows)
//static void timerCallback(HWND, UINT, UINT_PTR timer, DWORD dwTime) nothrow {
static void timerCallback(HANDLE timer, DWORD lowTime, DWORD hiTime) nothrow {
if(Timer* t = timer in mapping) {
try
(*t).trigger();
catch(Exception e) { throw new Error(e.msg, e.file, e.line); }
}
}
version(Windows) {
//UINT_PTR handle;
//static Timer[UINT_PTR] mapping;
HANDLE handle;
__gshared Timer[HANDLE] mapping;
} else version(linux) {
int fd = -1;
__gshared Timer[int] mapping;
} else static assert(0, "timer not supported");
}
}
version(Windows)
/// Lets you add HANDLEs to the event loop. Not meant to be used for async I/O per se, but for other handles (it can only handle a few handles at a time.)
class WindowsHandleReader {
///
this(void delegate() onReady, HANDLE handle) {
this.onReady = onReady;
this.handle = handle;
mapping[handle] = this;
enable();
}
///
void enable() {
auto el = EventLoop.get().impl;
el.handles ~= handle;
}
///
void disable() {
auto el = EventLoop.get().impl;
for(int i = 0; i < el.handles.length; i++) {
if(el.handles[i] is handle) {
el.handles[i] = el.handles[$-1];
el.handles = el.handles[0 .. $-1];
return;
}
}
}
void dispose() {
disable();
mapping.remove(handle);
handle = null;
}
void ready() {
if(onReady)
onReady();
}
HANDLE handle;
void delegate() onReady;
__gshared WindowsHandleReader[HANDLE] mapping;
}
version(linux)
/// Lets you add files to the event loop for reading. Use at your own risk.
class PosixFdReader {
///
this(void delegate() onReady, int fd, bool captureReads = true, bool captureWrites = false) {
this((int, bool, bool) { onReady(); }, fd, captureReads, captureWrites);
}
///
this(void delegate(int) onReady, int fd, bool captureReads = true, bool captureWrites = false) {
this((int fd, bool, bool) { onReady(fd); }, fd, captureReads, captureWrites);
}
///
this(void delegate(int fd, bool read, bool write) onReady, int fd, bool captureReads = true, bool captureWrites = false) {
this.onReady = onReady;
this.fd = fd;
this.captureWrites = captureWrites;
this.captureReads = captureReads;
mapping[fd] = this;
version(with_eventloop) {
import arsd.eventloop;
addFileEventListeners(fd, &readyel);
} else {
enable();
}
}
bool captureReads;
bool captureWrites;
version(with_eventloop) {} else
///
void enable() {
prepareEventLoop();
static import ep = core.sys.linux.epoll;
ep.epoll_event ev = void;
ev.events = (captureReads ? ep.EPOLLIN : 0) | (captureWrites ? ep.EPOLLOUT : 0);
//import std.stdio; writeln("enable ", fd, " ", captureReads, " ", captureWrites);
ev.data.fd = fd;
ep.epoll_ctl(epollFd, ep.EPOLL_CTL_ADD, fd, &ev);
}
version(with_eventloop) {} else
///
void disable() {
prepareEventLoop();
static import ep = core.sys.linux.epoll;
ep.epoll_event ev = void;
ev.events = (captureReads ? ep.EPOLLIN : 0) | (captureWrites ? ep.EPOLLOUT : 0);
//import std.stdio; writeln("disable ", fd, " ", captureReads, " ", captureWrites);
ev.data.fd = fd;
ep.epoll_ctl(epollFd, ep.EPOLL_CTL_DEL, fd, &ev);
}
version(with_eventloop) {} else
///
void dispose() {
disable();
mapping.remove(fd);
fd = -1;
}
void delegate(int, bool, bool) onReady;
version(with_eventloop)
void readyel() {
onReady(fd, true, true);
}
void ready(uint flags) {
static import ep = core.sys.linux.epoll;
onReady(fd, (flags & ep.EPOLLIN) ? true : false, (flags & ep.EPOLLOUT) ? true : false);
}
void hup(uint flags) {
if(onHup)
onHup();
}
void delegate() onHup;
int fd = -1;
__gshared PosixFdReader[int] mapping;
}
// basic functions to access the clipboard
/+
http://msdn.microsoft.com/en-us/library/windows/desktop/ff729168%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms649039%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms649035%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms649051%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms649037%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms649035%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms649016%28v=vs.85%29.aspx
+/
/++
this does a delegate because it is actually an async call on X...
the receiver may never be called if the clipboard is empty or unavailable
gets plain text from the clipboard
+/
void getClipboardText(SimpleWindow clipboardOwner, void delegate(in char[]) receiver) {
version(Windows) {
HWND hwndOwner = clipboardOwner ? clipboardOwner.impl.hwnd : null;
if(OpenClipboard(hwndOwner) == 0)
throw new Exception("OpenClipboard");
scope(exit)
CloseClipboard();
if(auto dataHandle = GetClipboardData(CF_UNICODETEXT)) {
if(auto data = cast(wchar*) GlobalLock(dataHandle)) {
scope(exit)
GlobalUnlock(dataHandle);
// FIXME: CR/LF conversions
// FIXME: I might not have to copy it now that the receiver is in char[] instead of string
int len = 0;
auto d = data;
while(*d) {
d++;
len++;
}
string s;
s.reserve(len);
foreach(dchar ch; data[0 .. len]) {
s ~= ch;
}
receiver(s);
}
}
} else version(X11) {
getX11Selection!"CLIPBOARD"(clipboardOwner, receiver);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
version(Windows)
struct WCharzBuffer {
wchar[256] staticBuffer;
wchar[] buffer;
size_t length() {
return buffer.length;
}
wchar* ptr() {
return buffer.ptr;
}
wchar[] slice() {
return buffer;
}
void copyInto(R)(ref R r) {
static if(is(R == wchar[N], size_t N)) {
r[0 .. this.length] = slice[];
r[this.length] = 0;
} else static assert(0, "can only copy into wchar[n], not " ~ R.stringof);
}
/++
conversionFlags = [WindowsStringConversionFlags]
+/
this(in char[] data, int conversionFlags = 0) {
conversionFlags |= WindowsStringConversionFlags.zeroTerminate; // this ALWAYS zero terminates cuz of its name
auto sz = sizeOfConvertedWstring(data, conversionFlags);
if(sz > staticBuffer.length)
buffer = new wchar[](sz);
else
buffer = staticBuffer[];
buffer = makeWindowsString(data, buffer, conversionFlags);
}
}
version(Windows)
int sizeOfConvertedWstring(in char[] s, int conversionFlags) {
int size = 0;
if(conversionFlags & WindowsStringConversionFlags.convertNewLines) {
// need to convert line endings, which means the length will get bigger.
// BTW I betcha this could be faster with some simd stuff.
char last;
foreach(char ch; s) {
if(ch == 10 && last != 13)
size++; // will add a 13 before it...
size++;
last = ch;
}
} else {
// no conversion necessary, just estimate based on length
/*
I don't think there's any string with a longer length
in code units when encoded in UTF-16 than it has in UTF-8.
This will probably over allocate, but that's OK.
*/
size = cast(int) s.length;
}
if(conversionFlags & WindowsStringConversionFlags.zeroTerminate)
size++;
return size;
}
version(Windows)
enum WindowsStringConversionFlags : int {
zeroTerminate = 1,
convertNewLines = 2,
}
version(Windows)
class WindowsApiException : Exception {
char[256] buffer;
this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null) {
assert(msg.length < 100);
auto error = GetLastError();
buffer[0 .. msg.length] = msg;
buffer[msg.length] = ' ';
int pos = cast(int) msg.length + 1;
if(error == 0)
buffer[pos++] = '0';
else {
auto init = pos;
while(error) {
buffer[pos++] = (error % 10) + '0';
error /= 10;
}
for(int i = 0; i < (pos - init) / 2; i++) {
char c = buffer[i + init];
buffer[i + init] = buffer[pos - (i + init) - 1];
buffer[pos - (i + init) - 1] = c;
}
}
super(cast(string) buffer[0 .. pos], file, line, next);
}
}
class ErrnoApiException : Exception {
char[256] buffer;
this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null) {
assert(msg.length < 100);
import core.stdc.errno;
auto error = errno;
buffer[0 .. msg.length] = msg;
buffer[msg.length] = ' ';
int pos = cast(int) msg.length + 1;
if(error == 0)
buffer[pos++] = '0';
else {
auto init = pos;
while(error) {
buffer[pos++] = (error % 10) + '0';
error /= 10;
}
for(int i = 0; i < (pos - init) / 2; i++) {
char c = buffer[i + init];
buffer[i + init] = buffer[pos - (i + init) - 1];
buffer[pos - (i + init) - 1] = c;
}
}
super(cast(string) buffer[0 .. pos], file, line, next);
}
}
version(Windows)
wchar[] makeWindowsString(in char[] str, wchar[] buffer, int conversionFlags = WindowsStringConversionFlags.zeroTerminate) {
if(str.length == 0)
return null;
int pos = 0;
dchar last;
foreach(dchar c; str) {
if(c <= 0xFFFF) {
if((conversionFlags & WindowsStringConversionFlags.convertNewLines) && c == 10 && last != 13)
buffer[pos++] = 13;
buffer[pos++] = cast(wchar) c;
} else if(c <= 0x10FFFF) {
buffer[pos++] = cast(wchar)((((c - 0x10000) >> 10) & 0x3FF) + 0xD800);
buffer[pos++] = cast(wchar)(((c - 0x10000) & 0x3FF) + 0xDC00);
}
last = c;
}
if(conversionFlags & WindowsStringConversionFlags.zeroTerminate) {
buffer[pos] = 0;
}
return buffer[0 .. pos];
}
version(Windows)
char[] makeUtf8StringFromWindowsString(in wchar[] str, char[] buffer) {
if(str.length == 0)
return null;
auto got = WideCharToMultiByte(CP_UTF8, 0, str.ptr, cast(int) str.length, buffer.ptr, cast(int) buffer.length, null, null);
if(got == 0) {
if(GetLastError() == ERROR_INSUFFICIENT_BUFFER)
throw new Exception("not enough buffer");
else
throw new Exception("conversion"); // FIXME: GetLastError
}
return buffer[0 .. got];
}
version(Windows)
string makeUtf8StringFromWindowsString(in wchar[] str) {
char[] buffer;
auto got = WideCharToMultiByte(CP_UTF8, 0, str.ptr, cast(int) str.length, null, 0, null, null);
buffer.length = got;
// it is unique because we just allocated it above!
return cast(string) makeUtf8StringFromWindowsString(str, buffer);
}
version(Windows)
string makeUtf8StringFromWindowsString(wchar* str) {
char[] buffer;
auto got = WideCharToMultiByte(CP_UTF8, 0, str, -1, null, 0, null, null);
buffer.length = got;
got = WideCharToMultiByte(CP_UTF8, 0, str, -1, buffer.ptr, cast(int) buffer.length, null, null);
if(got == 0) {
if(GetLastError() == ERROR_INSUFFICIENT_BUFFER)
throw new Exception("not enough buffer");
else
throw new Exception("conversion"); // FIXME: GetLastError
}
return cast(string) buffer[0 .. got];
}
int findIndexOfZero(in wchar[] str) {
foreach(idx, wchar ch; str)
if(ch == 0)
return cast(int) idx;
return cast(int) str.length;
}
int findIndexOfZero(in char[] str) {
foreach(idx, char ch; str)
if(ch == 0)
return cast(int) idx;
return cast(int) str.length;
}
/// copies some text to the clipboard
void setClipboardText(SimpleWindow clipboardOwner, string text) {
assert(clipboardOwner !is null);
version(Windows) {
if(OpenClipboard(clipboardOwner.impl.hwnd) == 0)
throw new Exception("OpenClipboard");
scope(exit)
CloseClipboard();
EmptyClipboard();
auto sz = sizeOfConvertedWstring(text, WindowsStringConversionFlags.convertNewLines | WindowsStringConversionFlags.zeroTerminate);
auto handle = GlobalAlloc(GMEM_MOVEABLE, sz * 2); // zero terminated wchars
if(handle is null) throw new Exception("GlobalAlloc");
if(auto data = cast(wchar*) GlobalLock(handle)) {
auto slice = data[0 .. sz];
scope(failure)
GlobalUnlock(handle);
auto str = makeWindowsString(text, slice, WindowsStringConversionFlags.convertNewLines | WindowsStringConversionFlags.zeroTerminate);
GlobalUnlock(handle);
SetClipboardData(CF_UNICODETEXT, handle);
}
} else version(X11) {
setX11Selection!"CLIPBOARD"(clipboardOwner, text);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
// FIXME: functions for doing images would be nice too - CF_DIB and whatever it is on X would be ok if we took the MemoryImage from color.d, or an Image from here. hell it might even be a variadic template that sets all the formats in one call. that might be cool.
version(X11) {
// and the PRIMARY on X, be sure to put these in static if(UsingSimpledisplayX11)
private Atom*[] interredAtoms; // for discardAndRecreate
/// Platform specific for X11
@property Atom GetAtom(string name, bool create = false)(Display* display) {
static Atom a;
if(!a) {
a = XInternAtom(display, name, !create);
interredAtoms ~= &a;
}
if(a == None)
throw new Exception("XInternAtom " ~ name ~ " " ~ (create ? "true":"false"));
return a;
}
/// Platform specific for X11 - gets atom names as a string
string getAtomName(Atom atom, Display* display) {
auto got = XGetAtomName(display, atom);
scope(exit) XFree(got);
import core.stdc.string;
string s = got[0 .. strlen(got)].idup;
return s;
}
/// Asserts ownership of PRIMARY and copies the text into a buffer that clients can request later
void setPrimarySelection(SimpleWindow window, string text) {
setX11Selection!"PRIMARY"(window, text);
}
/// Asserts ownership of SECONDARY and copies the text into a buffer that clients can request later
void setSecondarySelection(SimpleWindow window, string text) {
setX11Selection!"SECONDARY"(window, text);
}
///
void setX11Selection(string atomName)(SimpleWindow window, string text) {
assert(window !is null);
auto display = XDisplayConnection.get();
static if (atomName == "PRIMARY") Atom a = XA_PRIMARY;
else static if (atomName == "SECONDARY") Atom a = XA_SECONDARY;
else Atom a = GetAtom!atomName(display);
XSetSelectionOwner(display, a, window.impl.window, 0 /* CurrentTime */);
window.impl.setSelectionHandler = (XEvent ev) {
XSelectionRequestEvent* event = &ev.xselectionrequest;
XSelectionEvent selectionEvent;
selectionEvent.type = EventType.SelectionNotify;
selectionEvent.display = event.display;
selectionEvent.requestor = event.requestor;
selectionEvent.selection = event.selection;
selectionEvent.time = event.time;
selectionEvent.target = event.target;
if(event.property == None)
selectionEvent.property = event.target;
if(event.target == GetAtom!"TARGETS"(display)) {
/* respond with the supported types */
Atom[3] tlist;// = [XA_UTF8, XA_STRING, XA_TARGETS];
tlist[0] = GetAtom!"UTF8_STRING"(display);
tlist[1] = XA_STRING;
tlist[2] = GetAtom!"TARGETS"(display);
XChangeProperty(display, event.requestor, event.property, XA_ATOM, 32, PropModeReplace, cast(void*)tlist.ptr, 3);
selectionEvent.property = event.property;
} else if(event.target == XA_STRING) {
selectionEvent.property = event.property;
XChangeProperty (display,
selectionEvent.requestor,
selectionEvent.property,
event.target,
8 /* bits */, 0 /* PropModeReplace */,
text.ptr, cast(int) text.length);
} else if(event.target == GetAtom!"UTF8_STRING"(display)) {
selectionEvent.property = event.property;
XChangeProperty (display,
selectionEvent.requestor,
selectionEvent.property,
event.target,
8 /* bits */, 0 /* PropModeReplace */,
text.ptr, cast(int) text.length);
} else {
selectionEvent.property = None; // I don't know how to handle this type...
}
XSendEvent(display, selectionEvent.requestor, false, 0, cast(XEvent*) &selectionEvent);
};
}
///
void getPrimarySelection(SimpleWindow window, void delegate(in char[]) handler) {
getX11Selection!"PRIMARY"(window, handler);
}
///
void getX11Selection(string atomName)(SimpleWindow window, void delegate(in char[]) handler) {
assert(window !is null);
auto display = XDisplayConnection.get();
auto atom = GetAtom!atomName(display);
window.impl.getSelectionHandler = handler;
auto target = GetAtom!"TARGETS"(display);
// SDD_DATA is "simpledisplay.d data"
XConvertSelection(display, atom, target, GetAtom!("SDD_DATA", true)(display), window.impl.window, 0 /*CurrentTime*/);
}
///
void[] getX11PropertyData(Window window, Atom property, Atom type = AnyPropertyType) {
Atom actualType;
int actualFormat;
arch_ulong actualItems;
arch_ulong bytesRemaining;
void* data;
auto display = XDisplayConnection.get();
if(XGetWindowProperty(display, window, property, 0, 0x7fffffff, false, type, &actualType, &actualFormat, &actualItems, &bytesRemaining, &data) == Success) {
if(actualFormat == 0)
return null;
else {
int byteLength;
if(actualFormat == 32) {
// 32 means it is a C long... which is variable length
actualFormat = cast(int) arch_long.sizeof * 8;
}
// then it is just a bit count
byteLength = cast(int) (actualItems * actualFormat / 8);
auto d = new ubyte[](byteLength);
d[] = cast(ubyte[]) data[0 .. byteLength];
XFree(data);
return d;
}
}
return null;
}
/* defined in the systray spec */
enum SYSTEM_TRAY_REQUEST_DOCK = 0;
enum SYSTEM_TRAY_BEGIN_MESSAGE = 1;
enum SYSTEM_TRAY_CANCEL_MESSAGE = 2;
/** Global hotkey handler. Simpledisplay will usually create one for you, but if you want to use subclassing
* instead of delegates, you can subclass this, and override `doHandle()` method. */
public class GlobalHotkey {
KeyEvent key;
void delegate () handler;
void doHandle () { if (handler !is null) handler(); } /// this will be called by hotkey manager
/// Create from initialzed KeyEvent object
this (KeyEvent akey, void delegate () ahandler=null) {
if (akey.key == 0 || !GlobalHotkeyManager.isGoodModifierMask(akey.modifierState)) throw new Exception("invalid global hotkey");
key = akey;
handler = ahandler;
}
/// Create from emacs-like key name ("C-M-Y", etc.)
this (const(char)[] akey, void delegate () ahandler=null) {
key = KeyEvent.parse(akey);
if (key.key == 0 || !GlobalHotkeyManager.isGoodModifierMask(key.modifierState)) throw new Exception("invalid global hotkey");
handler = ahandler;
}
}
private extern(C) int XGrabErrorHandler (Display* dpy, XErrorEvent* evt) nothrow @nogc {
//conwriteln("failed to grab key");
GlobalHotkeyManager.ghfailed = true;
return 0;
}
private extern(C) int adrlogger (Display* dpy, XErrorEvent* evt) nothrow @nogc {
import core.stdc.stdio;
char[265] buffer;
XGetErrorText(dpy, evt.error_code, buffer.ptr, cast(int) buffer.length);
printf("ERROR: %s\n", buffer.ptr);
return 0;
}
/++
Global hotkey manager. It contains static methods to manage global hotkeys.
---
try {
GlobalHotkeyManager.register("M-H-A", delegate () { hideShowWindows(); });
} catch (Exception e) {
conwriteln("ERROR registering hotkey!");
}
---
The key strings are based on Emacs. In practical terms,
`M` means `alt` and `H` means the Windows logo key. `C`
is `ctrl`.
$(WARNING
This is X-specific right now. If you are on
Windows, try [registerHotKey] instead.
We will probably merge these into a single
interface later.
)
+/
public class GlobalHotkeyManager : CapableOfHandlingNativeEvent {
version(X11) {
void recreateAfterDisconnect() {
throw new Exception("NOT IMPLEMENTED");
}
void discardConnectionState() {
throw new Exception("NOT IMPLEMENTED");
}
}
private static immutable uint[8] masklist = [ 0,
KeyOrButtonMask.LockMask,
KeyOrButtonMask.Mod2Mask,
KeyOrButtonMask.Mod3Mask,
KeyOrButtonMask.LockMask|KeyOrButtonMask.Mod2Mask,
KeyOrButtonMask.LockMask|KeyOrButtonMask.Mod3Mask,
KeyOrButtonMask.LockMask|KeyOrButtonMask.Mod2Mask|KeyOrButtonMask.Mod3Mask,
KeyOrButtonMask.Mod2Mask|KeyOrButtonMask.Mod3Mask,
];
private __gshared GlobalHotkeyManager ghmanager;
private __gshared bool ghfailed = false;
private static bool isGoodModifierMask (uint modmask) pure nothrow @safe @nogc {
if (modmask == 0) return false;
if (modmask&(KeyOrButtonMask.LockMask|KeyOrButtonMask.Mod2Mask|KeyOrButtonMask.Mod3Mask)) return false;
if (modmask&~(KeyOrButtonMask.Mod5Mask-1)) return false;
return true;
}
private static uint cleanupModifiers (uint modmask) pure nothrow @safe @nogc {
modmask &= ~(KeyOrButtonMask.LockMask|KeyOrButtonMask.Mod2Mask|KeyOrButtonMask.Mod3Mask); // remove caps, num, scroll
modmask &= (KeyOrButtonMask.Mod5Mask-1); // and other modifiers
return modmask;
}
private static uint keyEvent2KeyCode() (in auto ref KeyEvent ke) {
uint keycode = cast(uint)ke.key;
auto dpy = XDisplayConnection.get;
return XKeysymToKeycode(dpy, keycode);
}
private static ulong keyCode2Hash() (uint keycode, uint modstate) pure nothrow @safe @nogc { return ((cast(ulong)modstate)<<32)|keycode; }
private __gshared GlobalHotkey[ulong] globalHotkeyList;
NativeEventHandler getNativeEventHandler () {
return delegate int (XEvent e) {
if (e.type != EventType.KeyPress) return 1;
auto kev = cast(const(XKeyEvent)*)&e;
auto hash = keyCode2Hash(e.xkey.keycode, cleanupModifiers(e.xkey.state));
if (auto ghkp = hash in globalHotkeyList) {
try {
ghkp.doHandle();
} catch (Exception e) {
import core.stdc.stdio : stderr, fprintf;
stderr.fprintf("HOTKEY HANDLER EXCEPTION: %.*s", cast(uint)e.msg.length, e.msg.ptr);
}
}
return 1;
};
}
private this () {
auto dpy = XDisplayConnection.get;
auto root = RootWindow(dpy, DefaultScreen(dpy));
CapableOfHandlingNativeEvent.nativeHandleMapping[root] = this;
XDisplayConnection.addRootInput(EventMask.KeyPressMask);
}
/// Register new global hotkey with initialized `GlobalHotkey` object.
/// This function will throw if it failed to register hotkey (i.e. hotkey is invalid or already taken).
static void register (GlobalHotkey gh) {
if (gh is null) return;
if (gh.key.key == 0 || !isGoodModifierMask(gh.key.modifierState)) throw new Exception("invalid global hotkey");
auto dpy = XDisplayConnection.get;
immutable keycode = keyEvent2KeyCode(gh.key);
auto hash = keyCode2Hash(keycode, gh.key.modifierState);
if (hash in globalHotkeyList) throw new Exception("duplicate global hotkey");
if (ghmanager is null) ghmanager = new GlobalHotkeyManager();
XSync(dpy, 0/*False*/);
Window root = RootWindow(dpy, DefaultScreen(dpy));
XErrorHandler savedErrorHandler = XSetErrorHandler(&XGrabErrorHandler);
ghfailed = false;
foreach (immutable uint ormask; masklist[]) {
XGrabKey(dpy, keycode, gh.key.modifierState|ormask, /*grab_window*/root, /*owner_events*/0/*False*/, GrabMode.GrabModeAsync, GrabMode.GrabModeAsync);
}
XSync(dpy, 0/*False*/);
XSetErrorHandler(savedErrorHandler);
if (ghfailed) {
savedErrorHandler = XSetErrorHandler(&XGrabErrorHandler);
foreach (immutable uint ormask; masklist[]) XUngrabKey(dpy, keycode, gh.key.modifierState|ormask, /*grab_window*/root);
XSync(dpy, 0/*False*/);
XSetErrorHandler(savedErrorHandler);
throw new Exception("cannot register global hotkey");
}
globalHotkeyList[hash] = gh;
}
/// Ditto
static void register (const(char)[] akey, void delegate () ahandler) {
register(new GlobalHotkey(akey, ahandler));
}
private static void removeByHash (ulong hash) {
if (auto ghp = hash in globalHotkeyList) {
auto dpy = XDisplayConnection.get;
immutable keycode = keyEvent2KeyCode(ghp.key);
Window root = RootWindow(dpy, DefaultScreen(dpy));
XSync(dpy, 0/*False*/);
XErrorHandler savedErrorHandler = XSetErrorHandler(&XGrabErrorHandler);
foreach (immutable uint ormask; masklist[]) XUngrabKey(dpy, keycode, ghp.key.modifierState|ormask, /*grab_window*/root);
XSync(dpy, 0/*False*/);
XSetErrorHandler(savedErrorHandler);
globalHotkeyList.remove(hash);
}
}
/// Register new global hotkey with previously used `GlobalHotkey` object.
/// It is safe to unregister unknown or invalid hotkey.
static void unregister (GlobalHotkey gh) {
//TODO: add second AA for faster search? prolly doesn't worth it.
if (gh is null) return;
foreach (const ref kv; globalHotkeyList.byKeyValue) {
if (kv.value is gh) {
removeByHash(kv.key);
return;
}
}
}
/// Ditto.
static void unregister (const(char)[] key) {
auto kev = KeyEvent.parse(key);
immutable keycode = keyEvent2KeyCode(kev);
removeByHash(keyCode2Hash(keycode, kev.modifierState));
}
}
}
version(Windows) {
/// Platform-specific for Windows. Sends a string as key press and release events to the actively focused window (not necessarily your application)
void sendSyntheticInput(wstring s) {
INPUT[] inputs;
inputs.reserve(s.length * 2);
foreach(wchar c; s) {
INPUT input;
input.type = INPUT_KEYBOARD;
input.ki.wScan = c;
input.ki.dwFlags = KEYEVENTF_UNICODE;
inputs ~= input;
input.ki.dwFlags |= KEYEVENTF_KEYUP;
inputs ~= input;
}
if(SendInput(cast(int) inputs.length, inputs.ptr, INPUT.sizeof) != inputs.length) {
throw new Exception("SendInput failed");
}
}
// global hotkey helper function
/// Platform-specific for Windows. Registers a global hotkey. Returns a registration ID.
int registerHotKey(SimpleWindow window, UINT modifiers, UINT vk, void delegate() handler) {
__gshared int hotkeyId = 0;
int id = ++hotkeyId;
if(!RegisterHotKey(window.impl.hwnd, id, modifiers, vk))
throw new Exception("RegisterHotKey failed");
__gshared void delegate()[WPARAM][HWND] handlers;
handlers[window.impl.hwnd][id] = handler;
int delegate(HWND, UINT, WPARAM, LPARAM) oldHandler;
auto nativeEventHandler = delegate int(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch(msg) {
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms646279%28v=vs.85%29.aspx
case WM_HOTKEY:
if(auto list = hwnd in handlers) {
if(auto h = wParam in *list) {
(*h)();
return 0;
}
}
goto default;
default:
}
if(oldHandler)
return oldHandler(hwnd, msg, wParam, lParam);
return 1; // pass it on
};
if(window.handleNativeEvent.funcptr !is nativeEventHandler.funcptr) {
oldHandler = window.handleNativeEvent;
window.handleNativeEvent = nativeEventHandler;
}
return id;
}
/// Platform-specific for Windows. Unregisters a key. The id is the value returned by registerHotKey.
void unregisterHotKey(SimpleWindow window, int id) {
if(!UnregisterHotKey(window.impl.hwnd, id))
throw new Exception("UnregisterHotKey");
}
}
/++
[ScreenPainter] operations can use different operations to combine the color with the color on screen.
See_Also:
$(LIST
*[ScreenPainter]
*[ScreenPainter.rasterOp]
)
+/
enum RasterOp {
normal, /// Replaces the pixel.
xor, /// Uses bitwise xor to draw.
}
// being phobos-free keeps the size WAY down
private const(char)* toStringz(string s) { return (s ~ '\0').ptr; }
package(arsd) const(wchar)* toWStringz(wstring s) { return (s ~ '\0').ptr; }
package(arsd) const(wchar)* toWStringz(string s) {
wstring r;
foreach(dchar c; s)
r ~= c;
r ~= '\0';
return r.ptr;
}
private string[] split(in void[] a, char c) {
string[] ret;
size_t previous = 0;
foreach(i, char ch; cast(ubyte[]) a) {
if(ch == c) {
ret ~= cast(string) a[previous .. i];
previous = i + 1;
}
}
if(previous != a.length)
ret ~= cast(string) a[previous .. $];
return ret;
}
version(without_opengl) {
enum OpenGlOptions {
no,
}
} else {
/++
Determines if you want an OpenGL context created on the new window.
See more: [#topics-3d|in the 3d topic].
---
import arsd.simpledisplay;
void main() {
auto window = new SimpleWindow(500, 500, "OpenGL Test", OpenGlOptions.yes);
// Set up the matrix
window.setAsCurrentOpenGlContext(); // make this window active
// This is called on each frame, we will draw our scene
window.redrawOpenGlScene = delegate() {
};
window.eventLoop(0);
}
---
+/
enum OpenGlOptions {
no, /// No OpenGL context is created
yes, /// Yes, create an OpenGL context
}
version(X11) {
static if (!SdpyIsUsingIVGLBinds) {
pragma(lib, "GL");
pragma(lib, "GLU");
}
} else version(Windows) {
static if (!SdpyIsUsingIVGLBinds) {
pragma(lib, "opengl32");
pragma(lib, "glu32");
}
} else
static assert(0, "OpenGL not supported on your system yet. Try -version=X11 if you have X Windows available, or -version=without_opengl to go without.");
}
deprecated("Sorry, I misspelled it in the first version! Use `Resizability` instead.")
alias Resizablity = Resizability;
/// When you create a SimpleWindow, you can see its resizability to be one of these via the constructor...
enum Resizability {
fixedSize, /// the window cannot be resized
allowResizing, /// the window can be resized. The buffer (if there is one) will automatically adjust size, but not stretch the contents. the windowResized delegate will be called so you can respond to the new size yourself.
automaticallyScaleIfPossible, /// if possible, your drawing buffer will remain the same size and simply be automatically scaled to the new window size. If this is impossible, it will not allow the user to resize the window at all. Note: window.width and window.height WILL be adjusted, which might throw you off if you draw based on them, so keep track of your expected width and height separately. That way, when it is scaled, things won't be thrown off.
// FIXME: automaticallyScaleIfPossible should adjust the OpenGL viewport on resize events
}
/++
Alignment for $(ScreenPainter.drawText). Left, Center, or Right may be combined with VerticalTop, VerticalCenter, or VerticalBottom via bitwise or.
+/
enum TextAlignment : uint {
Left = 0, ///
Center = 1, ///
Right = 2, ///
VerticalTop = 0, ///
VerticalCenter = 4, ///
VerticalBottom = 8, ///
}
public import arsd.color; // no longer stand alone... :-( but i need a common type for this to work with images easily.
alias Rectangle = arsd.color.Rectangle;
/++
Keyboard press and release events
+/
struct KeyEvent {
/// see table below. Always use the symbolic names, even for ASCII characters, since the actual numbers vary across platforms. See [Key]
Key key;
ubyte hardwareCode; /// A platform and hardware specific code for the key
bool pressed; /// true if the key was just pressed, false if it was just released. note: released events aren't always sent...
dchar character; ///
uint modifierState; /// see enum [ModifierState]. They are bitwise combined together.
SimpleWindow window; /// associated Window
// convert key event to simplified string representation a-la emacs
const(char)[] toStrBuf(bool growdest=false) (char[] dest) const nothrow @trusted {
uint dpos = 0;
void put (const(char)[] s...) nothrow @trusted {
static if (growdest) {
foreach (char ch; s) if (dpos < dest.length) dest.ptr[dpos++] = ch; else { dest ~= ch; ++dpos; }
} else {
foreach (char ch; s) if (dpos < dest.length) dest.ptr[dpos++] = ch;
}
}
void putMod (ModifierState mod, Key key, string text) nothrow @trusted {
if ((this.modifierState&mod) != 0 && (this.pressed || this.key != key)) put(text);
}
if (!this.key && !(this.modifierState&(ModifierState.ctrl|ModifierState.alt|ModifierState.shift|ModifierState.windows))) return null;
// put modifiers
// releasing modifier keys can produce bizarre things like "Ctrl+Ctrl", so hack around it
putMod(ModifierState.ctrl, Key.Ctrl, "Ctrl+");
putMod(ModifierState.alt, Key.Alt, "Alt+");
putMod(ModifierState.windows, Key.Shift, "Windows+");
putMod(ModifierState.shift, Key.Shift, "Shift+");
if (this.key) {
foreach (string kn; __traits(allMembers, Key)) {
if (this.key == __traits(getMember, Key, kn)) {
// HACK!
static if (kn == "N0") put("0");
else static if (kn == "N1") put("1");
else static if (kn == "N2") put("2");
else static if (kn == "N3") put("3");
else static if (kn == "N4") put("4");
else static if (kn == "N5") put("5");
else static if (kn == "N6") put("6");
else static if (kn == "N7") put("7");
else static if (kn == "N8") put("8");
else static if (kn == "N9") put("9");
else put(kn);
return dest[0..dpos];
}
}
put("Unknown");
} else {
if (dpos && dest[dpos-1] == '+') --dpos;
}
return dest[0..dpos];
}
string toStr() () { return cast(string)toStrBuf!true(null); } // it is safe to cast here
/** Parse string into key name with modifiers. It accepts things like:
*
* C-H-1 -- emacs style (ctrl, and windows, and 1)
*
* Ctrl+Win+1 -- windows style
*
* Ctrl-Win-1 -- '-' is a valid delimiter too
*
* Ctrl Win 1 -- and space
*
* and even "Win + 1 + Ctrl".
*/
static KeyEvent parse (const(char)[] name, bool* ignoreModsOut=null, int* updown=null) nothrow @trusted @nogc {
auto nanchor = name; // keep it anchored, 'cause `name` may have NO_INTERIOR set
// remove trailing spaces
while (name.length && name[$-1] <= ' ') name = name[0..$-1];
// tokens delimited by blank, '+', or '-'
// null on eol
const(char)[] getToken () nothrow @trusted @nogc {
// remove leading spaces and delimiters
while (name.length && (name[0] <= ' ' || name[0] == '+' || name[0] == '-')) name = name[1..$];
if (name.length == 0) return null; // oops, no more tokens
// get token
size_t epos = 0;
while (epos < name.length && name[epos] > ' ' && name[epos] != '+' && name[epos] != '-') ++epos;
assert(epos > 0 && epos <= name.length);
auto res = name[0..epos];
name = name[epos..$];
return res;
}
static bool strEquCI (const(char)[] s0, const(char)[] s1) pure nothrow @trusted @nogc {
if (s0.length != s1.length) return false;
foreach (immutable ci, char c0; s0) {
if (c0 >= 'A' && c0 <= 'Z') c0 += 32; // poor man's tolower
char c1 = s1[ci];
if (c1 >= 'A' && c1 <= 'Z') c1 += 32; // poor man's tolower
if (c0 != c1) return false;
}
return true;
}
if (ignoreModsOut !is null) *ignoreModsOut = false;
if (updown !is null) *updown = -1;
KeyEvent res;
res.key = cast(Key)0; // just in case
const(char)[] tk, tkn; // last token
bool allowEmascStyle = true;
bool ignoreModifiers = false;
tokenloop: for (;;) {
tk = tkn;
tkn = getToken();
//k8: yay, i took "Bloody Mess" trait from Fallout!
if (tkn.length != 0 && tk.length == 0) { tk = tkn; continue tokenloop; }
if (tkn.length == 0 && tk.length == 0) break; // no more tokens
if (allowEmascStyle && tkn.length != 0) {
if (tk.length == 1) {
char mdc = tk[0];
if (mdc >= 'a' && mdc <= 'z') mdc -= 32; // poor man's toupper()
if (mdc == 'C' && (res.modifierState&ModifierState.ctrl) == 0) {res.modifierState |= ModifierState.ctrl; continue tokenloop; }
if (mdc == 'M' && (res.modifierState&ModifierState.alt) == 0) { res.modifierState |= ModifierState.alt; continue tokenloop; }
if (mdc == 'H' && (res.modifierState&ModifierState.windows) == 0) { res.modifierState |= ModifierState.windows; continue tokenloop; }
if (mdc == 'S' && (res.modifierState&ModifierState.shift) == 0) { res.modifierState |= ModifierState.shift; continue tokenloop; }
if (mdc == '*') { ignoreModifiers = true; continue tokenloop; }
if (mdc == 'U' || mdc == 'R') { if (updown !is null) *updown = 0; continue tokenloop; }
if (mdc == 'D' || mdc == 'P') { if (updown !is null) *updown = 1; continue tokenloop; }
}
}
allowEmascStyle = false;
if (strEquCI(tk, "Ctrl")) { res.modifierState |= ModifierState.ctrl; continue tokenloop; }
if (strEquCI(tk, "Alt")) { res.modifierState |= ModifierState.alt; continue tokenloop; }
if (strEquCI(tk, "Win") || strEquCI(tk, "Windows")) { res.modifierState |= ModifierState.windows; continue tokenloop; }
if (strEquCI(tk, "Shift")) { res.modifierState |= ModifierState.shift; continue tokenloop; }
if (strEquCI(tk, "Release")) { if (updown !is null) *updown = 0; continue tokenloop; }
if (strEquCI(tk, "Press")) { if (updown !is null) *updown = 1; continue tokenloop; }
if (tk == "*") { ignoreModifiers = true; continue tokenloop; }
if (tk.length == 0) continue;
// try key name
if (res.key == 0) {
// little hack
if (tk.length == 1 && tk[0] >= '0' && tk[0] <= '9') {
final switch (tk[0]) {
case '0': tk = "N0"; break;
case '1': tk = "N1"; break;
case '2': tk = "N2"; break;
case '3': tk = "N3"; break;
case '4': tk = "N4"; break;
case '5': tk = "N5"; break;
case '6': tk = "N6"; break;
case '7': tk = "N7"; break;
case '8': tk = "N8"; break;
case '9': tk = "N9"; break;
}
}
foreach (string kn; __traits(allMembers, Key)) {
if (strEquCI(tk, kn)) { res.key = __traits(getMember, Key, kn); continue tokenloop; }
}
}
// unknown or duplicate key name, get out of here
break;
}
if (ignoreModsOut !is null) *ignoreModsOut = ignoreModifiers;
return res; // something
}
bool opEquals() (const(char)[] name) const nothrow @trusted @nogc {
enum modmask = (ModifierState.ctrl|ModifierState.alt|ModifierState.shift|ModifierState.windows);
void doModKey (ref uint mask, ref Key kk, Key k, ModifierState mst) {
if (kk == k) { mask |= mst; kk = cast(Key)0; }
}
bool ignoreMods;
int updown;
auto ke = KeyEvent.parse(name, &ignoreMods, &updown);
if ((updown == 0 && this.pressed) || (updown == 1 && !this.pressed)) return false;
if (this.key != ke.key) {
// things like "ctrl+alt" are complicated
uint tkm = this.modifierState&modmask;
uint kkm = ke.modifierState&modmask;
Key tk = this.key;
// ke
doModKey(kkm, ke.key, Key.Ctrl, ModifierState.ctrl);
doModKey(kkm, ke.key, Key.Alt, ModifierState.alt);
doModKey(kkm, ke.key, Key.Windows, ModifierState.windows);
doModKey(kkm, ke.key, Key.Shift, ModifierState.shift);
// this
doModKey(tkm, tk, Key.Ctrl, ModifierState.ctrl);
doModKey(tkm, tk, Key.Alt, ModifierState.alt);
doModKey(tkm, tk, Key.Windows, ModifierState.windows);
doModKey(tkm, tk, Key.Shift, ModifierState.shift);
return (tk == ke.key && tkm == kkm);
}
return (ignoreMods || ((this.modifierState&modmask) == (ke.modifierState&modmask)));
}
}
/// sets the application name.
@property string ApplicationName(string name) {
return _applicationName = name;
}
string _applicationName;
/// ditto
@property string ApplicationName() {
if(_applicationName is null) {
import core.runtime;
return Runtime.args[0];
}
return _applicationName;
}
/// Type of a [MouseEvent]
enum MouseEventType : int {
motion = 0, /// The mouse moved inside the window
buttonPressed = 1, /// A mouse button was pressed or the wheel was spun
buttonReleased = 2, /// A mouse button was released
}
// FIXME: mouse move should be distinct from presses+releases, so we can avoid subscribing to those events in X unnecessarily
/++
Listen for this on your event listeners if you are interested in mouse action.
Note that [button] is used on mouse press and release events. If you are curious about which button is being held in during motion, use [modifierState] and check the bitmask for [ModifierState.leftButtonDown], etc.
Examples:
This will draw boxes on the window with the mouse as you hold the left button.
---
import arsd.simpledisplay;
void main() {
auto window = new SimpleWindow();
window.eventLoop(0,
(MouseEvent ev) {
if(ev.modifierState & ModifierState.leftButtonDown) {
auto painter = window.draw();
painter.fillColor = Color.red;
painter.outlineColor = Color.black;
painter.drawRectangle(Point(ev.x / 16 * 16, ev.y / 16 * 16), 16, 16);
}
}
);
}
---
+/
struct MouseEvent {
MouseEventType type; /// movement, press, release, double click. See [MouseEventType]
int x; /// Current X position of the cursor when the event fired, relative to the upper-left corner of the window, reported in pixels. (0, 0) is the upper left, (window.width - 1, window.height - 1) is the lower right corner of the window.
int y; /// Current Y position of the cursor when the event fired.
int dx; /// Change in X position since last report
int dy; /// Change in Y position since last report
MouseButton button; /// See [MouseButton]
int modifierState; /// See [ModifierState]
/// Returns a linear representation of mouse button,
/// for use with static arrays. Guaranteed to be >= 0 && <= 15
///
/// Its implementation is based on range-limiting `core.bitop.bsf(button) + 1`.
@property ubyte buttonLinear() const {
import core.bitop;
if(button == 0)
return 0;
return (bsf(button) + 1) & 0b1111;
}
bool doubleClick; /// was it a double click? Only set on type == [MouseEventType.buttonPressed]
SimpleWindow window; /// The window in which the event happened.
Point globalCoordinates() {
Point p;
if(window is null)
throw new Exception("wtf");
static if(UsingSimpledisplayX11) {
Window child;
XTranslateCoordinates(
XDisplayConnection.get,
window.impl.window,
RootWindow(XDisplayConnection.get, DefaultScreen(XDisplayConnection.get)),
x, y, &p.x, &p.y, &child);
return p;
} else version(Windows) {
POINT[1] points;
points[0].x = x;
points[0].y = y;
MapWindowPoints(
window.impl.hwnd,
null,
points.ptr,
points.length
);
p.x = points[0].x;
p.y = points[0].y;
return p;
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
bool opEquals() (const(char)[] str) pure nothrow @trusted @nogc { return equStr(this, str); }
/**
can contain emacs-like modifier prefix
case-insensitive names:
lmbX/leftX
rmbX/rightX
mmbX/middleX
wheelX
motion (no prefix allowed)
'X' is either "up" or "down" (or "-up"/"-down"); if omited, means "down"
*/
static bool equStr() (in auto ref MouseEvent event, const(char)[] str) pure nothrow @trusted @nogc {
if (str.length == 0) return false; // just in case
debug(arsd_mevent_strcmp) { import iv.cmdcon; conwriteln("str=<", str, ">"); }
enum Flag : uint { Up = 0x8000_0000U, Down = 0x4000_0000U, Any = 0x1000_0000U }
auto anchor = str;
uint mods = 0; // uint.max == any
// interesting bits in kmod
uint kmodmask =
ModifierState.shift|
ModifierState.ctrl|
ModifierState.alt|
ModifierState.windows|
ModifierState.leftButtonDown|
ModifierState.middleButtonDown|
ModifierState.rightButtonDown|
0;
uint lastButt = uint.max; // otherwise, bit 31 means "down"
bool wasButtons = false;
while (str.length) {
if (str.ptr[0] <= ' ') {
while (str.length && str.ptr[0] <= ' ') str = str[1..$];
continue;
}
// one-letter modifier?
if (str.length >= 2 && str.ptr[1] == '-') {
switch (str.ptr[0]) {
case '*': // "any" modifier (cannot be undone)
mods = mods.max;
break;
case 'C': case 'c': // emacs "ctrl"
if (mods != mods.max) mods |= ModifierState.ctrl;
break;
case 'M': case 'm': // emacs "meta"
if (mods != mods.max) mods |= ModifierState.alt;
break;
case 'S': case 's': // emacs "shift"
if (mods != mods.max) mods |= ModifierState.shift;
break;
case 'H': case 'h': // emacs "hyper" (aka winkey)
if (mods != mods.max) mods |= ModifierState.windows;
break;
default:
return false; // unknown modifier
}
str = str[2..$];
continue;
}
// word
char[16] buf = void; // locased
auto wep = 0;
while (str.length) {
immutable char ch = str.ptr[0];
if (ch <= ' ' || ch == '-') break;
str = str[1..$];
if (wep > buf.length) return false; // too long
if (ch >= 'A' && ch <= 'Z') buf.ptr[wep++] = cast(char)(ch+32); // poor man tolower
else if (ch >= 'a' && ch <= 'z') buf.ptr[wep++] = ch;
else return false; // invalid char
}
if (wep == 0) return false; // just in case
uint bnum;
enum UpDown { None = -1, Up, Down, Any }
auto updown = UpDown.None; // 0: up; 1: down
switch (buf[0..wep]) {
// left button
case "lmbup": case "leftup": updown = UpDown.Up; goto case "lmb";
case "lmbdown": case "leftdown": updown = UpDown.Down; goto case "lmb";
case "lmbany": case "leftany": updown = UpDown.Any; goto case "lmb";
case "lmb": case "left": bnum = 0; break;
// middle button
case "mmbup": case "middleup": updown = UpDown.Up; goto case "mmb";
case "mmbdown": case "middledown": updown = UpDown.Down; goto case "mmb";
case "mmbany": case "middleany": updown = UpDown.Any; goto case "mmb";
case "mmb": case "middle": bnum = 1; break;
// right button
case "rmbup": case "rightup": updown = UpDown.Up; goto case "rmb";
case "rmbdown": case "rightdown": updown = UpDown.Down; goto case "rmb";
case "rmbany": case "rightany": updown = UpDown.Any; goto case "rmb";
case "rmb": case "right": bnum = 2; break;
// wheel
case "wheelup": updown = UpDown.Up; goto case "wheel";
case "wheeldown": updown = UpDown.Down; goto case "wheel";
case "wheelany": updown = UpDown.Any; goto case "wheel";
case "wheel": bnum = 3; break;
// motion
case "motion": bnum = 7; break;
// unknown
default: return false;
}
debug(arsd_mevent_strcmp) { import iv.cmdcon; conprintfln(" 0: mods=0x%08x; bnum=%u; updown=%s [%s]", mods, bnum, updown, str); }
// parse possible "-up" or "-down"
if (updown == UpDown.None && bnum < 7 && str.length > 0 && str.ptr[0] == '-') {
wep = 0;
foreach (immutable idx, immutable char ch; str[1..$]) {
if (ch <= ' ' || ch == '-') break;
assert(idx == wep); // for now; trick
if (wep > buf.length) { wep = 0; break; } // too long
if (ch >= 'A' && ch <= 'Z') buf.ptr[wep++] = cast(char)(ch+32); // poor man tolower
else if (ch >= 'a' && ch <= 'z') buf.ptr[wep++] = ch;
else { wep = 0; break; } // invalid char
}
if (wep == 2 && buf[0..wep] == "up") updown = UpDown.Up;
else if (wep == 4 && buf[0..wep] == "down") updown = UpDown.Down;
else if (wep == 3 && buf[0..wep] == "any") updown = UpDown.Any;
// remove parsed part
if (updown != UpDown.None) str = str[wep+1..$];
}
if (updown == UpDown.None) {
updown = UpDown.Down;
}
wasButtons = wasButtons || (bnum <= 2);
//assert(updown != UpDown.None);
debug(arsd_mevent_strcmp) { import iv.cmdcon; conprintfln(" 1: mods=0x%08x; bnum=%u; updown=%s [%s]", mods, bnum, updown, str); }
// if we have a previous button, it goes to modifiers (unless it is a wheel or motion)
if (lastButt != lastButt.max) {
if ((lastButt&0xff) >= 3) return false; // wheel or motion
if (mods != mods.max) {
uint butbit = 0;
final switch (lastButt&0x03) {
case 0: butbit = ModifierState.leftButtonDown; break;
case 1: butbit = ModifierState.middleButtonDown; break;
case 2: butbit = ModifierState.rightButtonDown; break;
}
if (lastButt&Flag.Down) mods |= butbit;
else if (lastButt&Flag.Up) mods &= ~butbit;
else if (lastButt&Flag.Any) kmodmask &= ~butbit;
}
}
// remember last button
lastButt = bnum|(updown == UpDown.Up ? Flag.Up : updown == UpDown.Any ? Flag.Any : Flag.Down);
}
// no button -- nothing to do
if (lastButt == lastButt.max) return false;
// done parsing, check if something's left
foreach (immutable char ch; str) if (ch > ' ') return false; // oops
// remove action button from mask
if ((lastButt&0xff) < 3) {
final switch (lastButt&0x03) {
case 0: kmodmask &= ~cast(uint)ModifierState.leftButtonDown; break;
case 1: kmodmask &= ~cast(uint)ModifierState.middleButtonDown; break;
case 2: kmodmask &= ~cast(uint)ModifierState.rightButtonDown; break;
}
}
// special case: "Motion" means "ignore buttons"
if ((lastButt&0xff) == 7 && !wasButtons) {
debug(arsd_mevent_strcmp) { import iv.cmdcon; conwriteln(" *: special motion"); }
kmodmask &= ~cast(uint)(ModifierState.leftButtonDown|ModifierState.middleButtonDown|ModifierState.rightButtonDown);
}
uint kmod = event.modifierState&kmodmask;
debug(arsd_mevent_strcmp) { import iv.cmdcon; conprintfln(" *: mods=0x%08x; lastButt=0x%08x; kmod=0x%08x; type=%s", mods, lastButt, kmod, event.type); }
// check modifier state
if (mods != mods.max) {
if (kmod != mods) return false;
}
// now check type
if ((lastButt&0xff) == 7) {
// motion
if (event.type != MouseEventType.motion) return false;
} else if ((lastButt&0xff) == 3) {
// wheel
if (lastButt&Flag.Up) return (event.type == MouseEventType.buttonPressed && event.button == MouseButton.wheelUp);
if (lastButt&Flag.Down) return (event.type == MouseEventType.buttonPressed && event.button == MouseButton.wheelDown);
if (lastButt&Flag.Any) return (event.type == MouseEventType.buttonPressed && (event.button == MouseButton.wheelUp || event.button == MouseButton.wheelUp));
return false;
} else {
// buttons
if (((lastButt&Flag.Down) != 0 && event.type != MouseEventType.buttonPressed) ||
((lastButt&Flag.Up) != 0 && event.type != MouseEventType.buttonReleased))
{
return false;
}
// button number
switch (lastButt&0x03) {
case 0: if (event.button != MouseButton.left) return false; break;
case 1: if (event.button != MouseButton.middle) return false; break;
case 2: if (event.button != MouseButton.right) return false; break;
default: return false;
}
}
return true;
}
}
version(arsd_mevent_strcmp_test) unittest {
MouseEvent event;
event.type = MouseEventType.buttonPressed;
event.button = MouseButton.left;
event.modifierState = ModifierState.ctrl;
assert(event == "C-LMB");
assert(event != "C-LMBUP");
assert(event != "C-LMB-UP");
assert(event != "C-S-LMB");
assert(event == "*-LMB");
assert(event != "*-LMB-UP");
event.type = MouseEventType.buttonReleased;
assert(event != "C-LMB");
assert(event == "C-LMBUP");
assert(event == "C-LMB-UP");
assert(event != "C-S-LMB");
assert(event != "*-LMB");
assert(event == "*-LMB-UP");
event.button = MouseButton.right;
event.modifierState |= ModifierState.shift;
event.type = MouseEventType.buttonPressed;
assert(event != "C-LMB");
assert(event != "C-LMBUP");
assert(event != "C-LMB-UP");
assert(event != "C-S-LMB");
assert(event != "*-LMB");
assert(event != "*-LMB-UP");
assert(event != "C-RMB");
assert(event != "C-RMBUP");
assert(event != "C-RMB-UP");
assert(event == "C-S-RMB");
assert(event == "*-RMB");
assert(event != "*-RMB-UP");
}
/// This gives a few more options to drawing lines and such
struct Pen {
Color color; /// the foreground color
int width = 1; /// width of the line
Style style; /// See [Style]
/+
// From X.h
#define LineSolid 0
#define LineOnOffDash 1
#define LineDoubleDash 2
LineDou- The full path of the line is drawn, but the
bleDash even dashes are filled differently from the
odd dashes (see fill-style) with CapButt
style used where even and odd dashes meet.
/* capStyle */
#define CapNotLast 0
#define CapButt 1
#define CapRound 2
#define CapProjecting 3
/* joinStyle */
#define JoinMiter 0
#define JoinRound 1
#define JoinBevel 2
/* fillStyle */
#define FillSolid 0
#define FillTiled 1
#define FillStippled 2
#define FillOpaqueStippled 3
+/
/// Style of lines drawn
enum Style {
Solid, /// a solid line
Dashed, /// a dashed line
Dotted, /// a dotted line
}
}
/++
Represents an in-memory image in the format that the GUI expects, but with its raw data available to your program.
On Windows, this means a device-independent bitmap. On X11, it is an XImage.
$(NOTE If you are writing platform-aware code and need to know low-level details, uou may check `if(Image.impl.xshmAvailable)` to see if MIT-SHM is used on X11 targets to draw `Image`s and `Sprite`s. Use `static if(UsingSimpledisplayX11)` to determine if you are compiling for an X11 target.)
Drawing an image to screen is not necessarily fast, but applying algorithms to draw to the image itself should be fast. An `Image` is also the first step in loading and displaying images loaded from files.
If you intend to draw an image to screen several times, you will want to convert it into a [Sprite].
$(IMPORTANT `Image` may represent a scarce, shared resource that persists across process termination, and should be disposed of properly. On X11, it uses the MIT-SHM extension, if available, which uses shared memory handles with the X server, which is a long-lived process that holds onto them after your program terminates if you don't free it.
It is possible for your user's system to run out of these handles over time, forcing them to clean it up with extraordinary measures - their GUI is liable to stop working!
Be sure these are cleaned up properly. simpledisplay will do its best to do the right thing, including cleaning them up in garbage collection sweeps (one of which is run at most normal program terminations) and catching some deadly signals. It will almost always do the right thing. But, this is no substitute for you managing the resource properly yourself. (And try not to segfault, as recovery from them is alway dicey!)
Please call `destroy(image);` when you are done with it. The easiest way to do this is with scope:
---
auto image = new Image(256, 256);
scope(exit) destroy(image);
---
As long as you don't hold on to it outside the scope.
I might change it to be an owned pointer at some point in the future.
)
Drawing pixels on the image may be simple, using the `opIndexAssign` function, but
you can also often get a fair amount of speedup by getting the raw data format and
writing some custom code.
FIXME INSERT EXAMPLES HERE
+/
final class Image {
///
this(int width, int height, bool forcexshm=false) {
this.width = width;
this.height = height;
impl.createImage(width, height, forcexshm);
}
///
this(Size size, bool forcexshm=false) {
this(size.width, size.height, forcexshm);
}
~this() {
impl.dispose();
}
// these numbers are used for working with rawData itself, skipping putPixel and getPixel
/// if you do the math yourself you might be able to optimize it. Call these functions only once and cache the value.
pure const @system nothrow {
/*
To use these to draw a blue rectangle with size WxH at position X,Y...
// make certain that it will fit before we proceed
enforce(X + W <= img.width && Y + H <= img.height); // you could also adjust the size to clip it, but be sure not to run off since this here will do raw pointers with no bounds checks!
// gather all the values you'll need up front. These can be kept until the image changes size if you want
// (though calculating them isn't really that expensive).
auto nextLineAdjustment = img.adjustmentForNextLine();
auto offR = img.redByteOffset();
auto offB = img.blueByteOffset();
auto offG = img.greenByteOffset();
auto bpp = img.bytesPerPixel();
auto data = img.getDataPointer();
// figure out the starting byte offset
auto offset = img.offsetForTopLeftPixel() + nextLineAdjustment*Y + bpp * X;
auto startOfLine = data + offset; // get our pointer lined up on the first pixel
// and now our drawing loop for the rectangle
foreach(y; 0 .. H) {
auto data = startOfLine; // we keep the start of line separately so moving to the next line is simple and portable
foreach(x; 0 .. W) {
// write our color
data[offR] = 0;
data[offG] = 0;
data[offB] = 255;
data += bpp; // moving to the next pixel is just an addition...
}
startOfLine += nextLineAdjustment;
}
As you can see, the loop itself was very simple thanks to the calculations being moved outside.
FIXME: I wonder if I can make the pixel formats consistently 32 bit across platforms, so the color offsets
can be made into a bitmask or something so we can write them as *uint...
*/
///
int offsetForTopLeftPixel() {
version(X11) {
return 0;
} else version(Windows) {
return (((cast(int) width * 3 + 3) / 4) * 4) * (height - 1);
} else version(OSXCocoa) {
return 0 ; //throw new NotYetImplementedException();
} else static assert(0, "fill in this info for other OSes");
}
///
int offsetForPixel(int x, int y) {
version(X11) {
auto offset = (y * width + x) * 4;
return offset;
} else version(Windows) {
auto itemsPerLine = ((cast(int) width * 3 + 3) / 4) * 4;
// remember, bmps are upside down
auto offset = itemsPerLine * (height - y - 1) + x * 3;
return offset;
} else version(OSXCocoa) {
return 0 ; //throw new NotYetImplementedException();
} else static assert(0, "fill in this info for other OSes");
}
///
int adjustmentForNextLine() {
version(X11) {
return width * 4;
} else version(Windows) {
// windows bmps are upside down, so the adjustment is actually negative
return -((cast(int) width * 3 + 3) / 4) * 4;
} else version(OSXCocoa) {
return 0 ; //throw new NotYetImplementedException();
} else static assert(0, "fill in this info for other OSes");
}
/// once you have the position of a pixel, use these to get to the proper color
int redByteOffset() {
version(X11) {
return 2;
} else version(Windows) {
return 2;
} else version(OSXCocoa) {
return 0 ; //throw new NotYetImplementedException();
} else static assert(0, "fill in this info for other OSes");
}
///
int greenByteOffset() {
version(X11) {
return 1;
} else version(Windows) {
return 1;
} else version(OSXCocoa) {
return 0 ; //throw new NotYetImplementedException();
} else static assert(0, "fill in this info for other OSes");
}
///
int blueByteOffset() {
version(X11) {
return 0;
} else version(Windows) {
return 0;
} else version(OSXCocoa) {
return 0 ; //throw new NotYetImplementedException();
} else static assert(0, "fill in this info for other OSes");
}
}
///
final void putPixel(int x, int y, Color c) {
if(x < 0 || x >= width)
return;
if(y < 0 || y >= height)
return;
impl.setPixel(x, y, c);
}
///
final Color getPixel(int x, int y) {
if(x < 0 || x >= width)
return Color.transparent;
if(y < 0 || y >= height)
return Color.transparent;
version(OSXCocoa) throw new NotYetImplementedException(); else
return impl.getPixel(x, y);
}
///
final void opIndexAssign(Color c, int x, int y) {
putPixel(x, y, c);
}
///
TrueColorImage toTrueColorImage() {
auto tci = new TrueColorImage(width, height);
convertToRgbaBytes(tci.imageData.bytes);
return tci;
}
///
static Image fromMemoryImage(MemoryImage i) {
auto tci = i.getAsTrueColorImage();
auto img = new Image(tci.width, tci.height);
img.setRgbaBytes(tci.imageData.bytes);
return img;
}
/// this is here for interop with arsd.image. where can be a TrueColorImage's data member
/// if you pass in a buffer, it will put it right there. length must be width*height*4 already
/// if you pass null, it will allocate a new one.
ubyte[] getRgbaBytes(ubyte[] where = null) {
if(where is null)
where = new ubyte[this.width*this.height*4];
convertToRgbaBytes(where);
return where;
}
/// this is here for interop with arsd.image. from can be a TrueColorImage's data member
void setRgbaBytes(in ubyte[] from ) {
assert(from.length == this.width * this.height * 4);
setFromRgbaBytes(from);
}
// FIXME: make properly cross platform by getting rgba right
/// warning: this is not portable across platforms because the data format can change
ubyte* getDataPointer() {
return impl.rawData;
}
/// for use with getDataPointer
final int bytesPerLine() const pure @safe nothrow {
version(Windows)
return ((cast(int) width * 3 + 3) / 4) * 4;
else version(X11)
return 4 * width;
else version(OSXCocoa)
return 4 * width;
else static assert(0);
}
/// for use with getDataPointer
final int bytesPerPixel() const pure @safe nothrow {
version(Windows)
return 3;
else version(X11)
return 4;
else version(OSXCocoa)
return 4;
else static assert(0);
}
///
immutable int width;
///
immutable int height;
//private:
mixin NativeImageImplementation!() impl;
}
/// A convenience function to pop up a window displaying the image.
/// If you pass a win, it will draw the image in it. Otherwise, it will
/// create a window with the size of the image and run its event loop, closing
/// when a key is pressed.
void displayImage(Image image, SimpleWindow win = null) {
if(win is null) {
win = new SimpleWindow(image);
{
auto p = win.draw;
p.drawImage(Point(0, 0), image);
}
win.eventLoop(0,
(KeyEvent ev) {
if (ev.pressed) win.close();
} );
} else {
win.image = image;
}
}
enum FontWeight : int {
dontcare = 0,
thin = 100,
extralight = 200,
light = 300,
regular = 400,
medium = 500,
semibold = 600,
bold = 700,
extrabold = 800,
heavy = 900
}
/++
Represents a font loaded off the operating system or the X server.
While the api here is unified cross platform, the fonts are not necessarily
available, even across machines of the same platform, so be sure to always check
for null (using [isNull]) and have a fallback plan.
When you have a font you like, use [ScreenPainter.setFont] to load it for drawing.
Worst case, a null font will automatically fall back to the default font loaded
for your system.
+/
class OperatingSystemFont {
version(X11) {
XFontStruct* font;
XFontSet fontset;
} else version(Windows) {
HFONT font;
} else version(OSXCocoa) {
// FIXME
} else static assert(0);
///
this(string name, int size = 0, FontWeight weight = FontWeight.dontcare, bool italic = false) {
load(name, size, weight, italic);
}
///
bool load(string name, int size = 0, FontWeight weight = FontWeight.dontcare, bool italic = false) {
unload();
version(X11) {
string weightstr;
with(FontWeight)
final switch(weight) {
case dontcare: weightstr = "*"; break;
case thin: weightstr = "extralight"; break;
case extralight: weightstr = "extralight"; break;
case light: weightstr = "light"; break;
case regular: weightstr = "regular"; break;
case medium: weightstr = "medium"; break;
case semibold: weightstr = "demibold"; break;
case bold: weightstr = "bold"; break;
case extrabold: weightstr = "demibold"; break;
case heavy: weightstr = "black"; break;
}
string sizestr;
if(size == 0)
sizestr = "*";
else if(size < 10)
sizestr = "" ~ cast(char)(size % 10 + '0');
else
sizestr = "" ~ cast(char)(size / 10 + '0') ~ cast(char)(size % 10 + '0');
auto xfontstr = "-*-"~name~"-"~weightstr~"-"~(italic ? "i" : "r")~"-*-*-"~sizestr~"-*-*-*-*-*-*-*\0";
//import std.stdio; writeln(xfontstr);
auto display = XDisplayConnection.get;
font = XLoadQueryFont(display, xfontstr.ptr);
if(font is null)
return false;
char** lol;
int lol2;
char* lol3;
fontset = XCreateFontSet(display, xfontstr.ptr, &lol, &lol2, &lol3);
} else version(Windows) {
WCharzBuffer buffer = WCharzBuffer(name);
font = CreateFont(size, 0, 0, 0, cast(int) weight, italic, 0, 0, 0, 0, 0, 0, 0, buffer.ptr);
} else version(OSXCocoa) {
// FIXME
} else static assert(0);
return !isNull();
}
///
void unload() {
if(isNull())
return;
version(X11) {
auto display = XDisplayConnection.display;
if(display is null)
return;
if(font)
XFreeFont(display, font);
if(fontset)
XFreeFontSet(display, fontset);
font = null;
fontset = null;
} else version(Windows) {
DeleteObject(font);
font = null;
} else version(OSXCocoa) {
// FIXME
} else static assert(0);
}
/// FIXME not implemented
void loadDefault() {
}
///
bool isNull() {
version(OSXCocoa) throw new NotYetImplementedException(); else
return font is null;
}
/* Metrics */
/+
GetFontMetrics
GetABCWidth
GetKerningPairs
XLoadQueryFont
if I do it right, I can size it all here, and match
what happens when I draw the full string with the OS functions.
subclasses might do the same thing while getting the glyphs on images
+/
struct GlyphInfo {
int glyph;
size_t stringIdxStart;
size_t stringIdxEnd;
Rectangle boundingBox;
}
GlyphInfo[] getCharBoxes() {
return null;
}
~this() {
unload();
}
}
/**
The 2D drawing proxy. You acquire one of these with [SimpleWindow.draw] rather
than constructing it directly. Then, it is reference counted so you can pass it
at around and when the last ref goes out of scope, the buffered drawing activities
are all carried out.
Most functions use the outlineColor instead of taking a color themselves.
ScreenPainter is reference counted and draws its buffer to the screen when its
final reference goes out of scope.
*/
struct ScreenPainter {
CapableOfBeingDrawnUpon window;
this(CapableOfBeingDrawnUpon window, NativeWindowHandle handle) {
this.window = window;
if(window.closed)
return; // null painter is now allowed so no need to throw anymore, this likely happens at the end of a program anyway
currentClipRectangle = arsd.color.Rectangle(0, 0, window.width, window.height);
if(window.activeScreenPainter !is null) {
impl = window.activeScreenPainter;
impl.referenceCount++;
// writeln("refcount ++ ", impl.referenceCount);
} else {
impl = new ScreenPainterImplementation;
impl.window = window;
impl.create(handle);
impl.referenceCount = 1;
window.activeScreenPainter = impl;
// writeln("constructed");
}
copyActiveOriginals();
}
private Pen originalPen;
private Color originalFillColor;
private arsd.color.Rectangle originalClipRectangle;
void copyActiveOriginals() {
if(impl is null) return;
originalPen = impl._activePen;
originalFillColor = impl._fillColor;
originalClipRectangle = impl._clipRectangle;
}
~this() {
if(impl is null) return;
impl.referenceCount--;
//writeln("refcount -- ", impl.referenceCount);
if(impl.referenceCount == 0) {
//writeln("destructed");
impl.dispose();
window.activeScreenPainter = null;
//import std.stdio; writeln("paint finished");
} else {
// there is still an active reference, reset stuff so the
// next user doesn't get weirdness via the reference
this.rasterOp = RasterOp.normal;
pen = originalPen;
fillColor = originalFillColor;
impl.setClipRectangle(originalClipRectangle.left, originalClipRectangle.top, originalClipRectangle.width, originalClipRectangle.height);
}
}
this(this) {
if(impl is null) return;
impl.referenceCount++;
//writeln("refcount ++ ", impl.referenceCount);
copyActiveOriginals();
}
private int _originX;
private int _originY;
@property int originX() { return _originX; }
@property int originY() { return _originY; }
@property int originX(int a) {
//currentClipRectangle.left += a - _originX;
//currentClipRectangle.right += a - _originX;
_originX = a;
return _originX;
}
@property int originY(int a) {
//currentClipRectangle.top += a - _originY;
//currentClipRectangle.bottom += a - _originY;
_originY = a;
return _originY;
}
arsd.color.Rectangle currentClipRectangle; // set BEFORE doing any transformations
private void transform(ref Point p) {
if(impl is null) return;
p.x += _originX;
p.y += _originY;
}
// this needs to be checked BEFORE the originX/Y transformation
private bool isClipped(Point p) {
return !currentClipRectangle.contains(p);
}
private bool isClipped(Point p, int width, int height) {
return !currentClipRectangle.overlaps(arsd.color.Rectangle(p, Size(width + 1, height + 1)));
}
private bool isClipped(Point p, Size s) {
return !currentClipRectangle.overlaps(arsd.color.Rectangle(p, Size(s.width + 1, s.height + 1)));
}
private bool isClipped(Point p, Point p2) {
// need to ensure the end points are actually included inside, so the +1 does that
return !currentClipRectangle.overlaps(arsd.color.Rectangle(p, p2 + Point(1, 1)));
}
/// Sets the clipping region for drawing. If width == 0 && height == 0, disabled clipping.
void setClipRectangle(Point pt, int width, int height) {
if(impl is null) return;
if(pt == currentClipRectangle.upperLeft && width == currentClipRectangle.width && height == currentClipRectangle.height)
return; // no need to do anything
currentClipRectangle = arsd.color.Rectangle(pt, Size(width, height));
transform(pt);
impl.setClipRectangle(pt.x, pt.y, width, height);
}
/// ditto
void setClipRectangle(arsd.color.Rectangle rect) {
if(impl is null) return;
setClipRectangle(rect.upperLeft, rect.width, rect.height);
}
///
void setFont(OperatingSystemFont font) {
if(impl is null) return;
impl.setFont(font);
}
///
int fontHeight() {
if(impl is null) return 0;
return impl.fontHeight();
}
private Pen activePen;
///
@property void pen(Pen p) {
if(impl is null) return;
activePen = p;
impl.pen(p);
}
///
@property void outlineColor(Color c) {
if(impl is null) return;
if(activePen.color == c)
return;
activePen.color = c;
impl.pen(activePen);
}
///
@property void fillColor(Color c) {
if(impl is null) return;
impl.fillColor(c);
}
///
@property void rasterOp(RasterOp op) {
if(impl is null) return;
impl.rasterOp(op);
}
void updateDisplay() {
// FIXME this should do what the dtor does
}
/// Scrolls the contents in the bounding rectangle by dx, dy. Positive dx means scroll left (make space available at the right), positive dy means scroll up (make space available at the bottom)
void scrollArea(Point upperLeft, int width, int height, int dx, int dy) {
if(impl is null) return;
if(isClipped(upperLeft, width, height)) return;
transform(upperLeft);
version(Windows) {
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb787589%28v=vs.85%29.aspx
RECT scroll = RECT(upperLeft.x, upperLeft.y, upperLeft.x + width, upperLeft.y + height);
RECT clip = scroll;
RECT uncovered;
HRGN hrgn;
if(!ScrollDC(impl.hdc, -dx, -dy, &scroll, &clip, hrgn, &uncovered))
throw new Exception("ScrollDC");
} else version(X11) {
// FIXME: clip stuff outside this rectangle
XCopyArea(impl.display, impl.d, impl.d, impl.gc, upperLeft.x, upperLeft.y, width, height, upperLeft.x - dx, upperLeft.y - dy);
} else version(OSXCocoa) {
throw new NotYetImplementedException();
} else static assert(0);
}
///
void clear() {
if(impl is null) return;
fillColor = Color(255, 255, 255);
outlineColor = Color(255, 255, 255);
drawRectangle(Point(0, 0), window.width, window.height);
}
///
version(OSXCocoa) {} else // NotYetImplementedException
void drawPixmap(Sprite s, Point upperLeft) {
if(impl is null) return;
if(isClipped(upperLeft, s.width, s.height)) return;
transform(upperLeft);
impl.drawPixmap(s, upperLeft.x, upperLeft.y);
}
///
void drawImage(Point upperLeft, Image i, Point upperLeftOfImage = Point(0, 0), int w = 0, int h = 0) {
if(impl is null) return;
//if(isClipped(upperLeft, w, h)) return; // FIXME
transform(upperLeft);
if(w == 0 || w > i.width)
w = i.width;
if(h == 0 || h > i.height)
h = i.height;
if(upperLeftOfImage.x < 0)
upperLeftOfImage.x = 0;
if(upperLeftOfImage.y < 0)
upperLeftOfImage.y = 0;
impl.drawImage(upperLeft.x, upperLeft.y, i, upperLeftOfImage.x, upperLeftOfImage.y, w, h);
}
///
Size textSize(in char[] text) {
if(impl is null) return Size(0, 0);
return impl.textSize(text);
}
///
void drawText(Point upperLeft, in char[] text, Point lowerRight = Point(0, 0), uint alignment = 0) {
if(impl is null) return;
if(lowerRight.x != 0 || lowerRight.y != 0) {
if(isClipped(upperLeft, lowerRight)) return;
transform(lowerRight);
} else {
if(isClipped(upperLeft, textSize(text))) return;
}
transform(upperLeft);
impl.drawText(upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y, text, alignment);
}
/++
Draws text using a custom font.
This is still MAJOR work in progress.
Creating a [DrawableFont] can be tricky and require additional dependencies.
+/
void drawText(DrawableFont font, Point upperLeft, in char[] text) {
if(impl is null) return;
if(isClipped(upperLeft, Point(int.max, int.max))) return;
transform(upperLeft);
font.drawString(this, upperLeft, text);
}
static struct TextDrawingContext {
Point boundingBoxUpperLeft;
Point boundingBoxLowerRight;
Point currentLocation;
Point lastDrewUpperLeft;
Point lastDrewLowerRight;
// how do i do right aligned rich text?
// i kinda want to do a pre-made drawing then right align
// draw the whole block.
//
// That's exactly the diff: inline vs block stuff.
// I need to get coordinates of an inline section out too,
// not just a bounding box, but a series of bounding boxes
// should be ok. Consider what's needed to detect a click
// on a link in the middle of a paragraph breaking a line.
//
// Generally, we should be able to get the rectangles of
// any portion we draw.
//
// It also needs to tell what text is left if it overflows
// out of the box, so we can do stuff like float images around
// it. It should not attempt to draw a letter that would be
// clipped.
//
// I might also turn off word wrap stuff.
}
void drawText(TextDrawingContext context, in char[] text, uint alignment = 0) {
if(impl is null) return;
// FIXME
}
/// Drawing an individual pixel is slow. Avoid it if possible.
void drawPixel(Point where) {
if(impl is null) return;
if(isClipped(where)) return;
transform(where);
impl.drawPixel(where.x, where.y);
}
/// Draws a pen using the current pen / outlineColor
void drawLine(Point starting, Point ending) {
if(impl is null) return;
if(isClipped(starting, ending)) return;
transform(starting);
transform(ending);
impl.drawLine(starting.x, starting.y, ending.x, ending.y);
}
/// Draws a rectangle using the current pen/outline color for the border and brush/fill color for the insides
/// The outer lines, inclusive of x = 0, y = 0, x = width - 1, and y = height - 1 are drawn with the outlineColor
/// The rest of the pixels are drawn with the fillColor. If fillColor is transparent, those pixels are not drawn.
void drawRectangle(Point upperLeft, int width, int height) {
if(impl is null) return;
if(isClipped(upperLeft, width, height)) return;
transform(upperLeft);
impl.drawRectangle(upperLeft.x, upperLeft.y, width, height);
}
/// ditto
void drawRectangle(Point upperLeft, Size size) {
if(impl is null) return;
if(isClipped(upperLeft, size.width, size.height)) return;
transform(upperLeft);
impl.drawRectangle(upperLeft.x, upperLeft.y, size.width, size.height);
}
/// ditto
void drawRectangle(Point upperLeft, Point lowerRightInclusive) {
if(impl is null) return;
if(isClipped(upperLeft, lowerRightInclusive + Point(1, 1))) return;
transform(upperLeft);
transform(lowerRightInclusive);
impl.drawRectangle(upperLeft.x, upperLeft.y,
lowerRightInclusive.x - upperLeft.x + 1, lowerRightInclusive.y - upperLeft.y + 1);
}
/// Arguments are the points of the bounding rectangle
void drawEllipse(Point upperLeft, Point lowerRight) {
if(impl is null) return;
if(isClipped(upperLeft, lowerRight)) return;
transform(upperLeft);
transform(lowerRight);
impl.drawEllipse(upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y);
}
/++
start and finish are units of degrees * 64
+/
void drawArc(Point upperLeft, int width, int height, int start, int finish) {
if(impl is null) return;
// FIXME: not actually implemented
if(isClipped(upperLeft, width, height)) return;
transform(upperLeft);
impl.drawArc(upperLeft.x, upperLeft.y, width, height, start, finish);
}
/// .
void drawPolygon(Point[] vertexes) {
if(impl is null) return;
assert(vertexes.length);
int minX = int.max, minY = int.max, maxX = int.min, maxY = int.min;
foreach(ref vertex; vertexes) {
if(vertex.x < minX)
minX = vertex.x;
if(vertex.y < minY)
minY = vertex.y;
if(vertex.x > maxX)
maxX = vertex.x;
if(vertex.y > maxY)
maxY = vertex.y;
transform(vertex);
}
if(isClipped(Point(minX, maxY), Point(maxX + 1, maxY + 1))) return;
impl.drawPolygon(vertexes);
}
/// ditto
void drawPolygon(Point[] vertexes...) {
if(impl is null) return;
drawPolygon(vertexes);
}
// and do a draw/fill in a single call maybe. Windows can do it... but X can't, though it could do two calls.
//mixin NativeScreenPainterImplementation!() impl;
// HACK: if I mixin the impl directly, it won't let me override the copy
// constructor! The linker complains about there being multiple definitions.
// I'll make the best of it and reference count it though.
ScreenPainterImplementation* impl;
}
// HACK: I need a pointer to the implementation so it's separate
struct ScreenPainterImplementation {
CapableOfBeingDrawnUpon window;
int referenceCount;
mixin NativeScreenPainterImplementation!();
}
// FIXME: i haven't actually tested the sprite class on MS Windows
/**
Sprites are optimized for fast drawing on the screen, but slow for direct pixel
access. They are best for drawing a relatively unchanging image repeatedly on the screen.
On X11, this corresponds to an `XPixmap`. On Windows, it still uses a bitmap,
though I'm not sure that's ideal and the implementation might change.
You create one by giving a window and an image. It optimizes for that window,
and copies the image into it to use as the initial picture. Creating a sprite
can be quite slow (especially over a network connection) so you should do it
as little as possible and just hold on to your sprite handles after making them.
simpledisplay does try to do its best though, using the XSHM extension if available,
but you should still write your code as if it will always be slow.
Then you can use `sprite.drawAt(painter, point);` to draw it, which should be
a fast operation - much faster than drawing the Image itself every time.
`Sprite` represents a scarce resource which should be freed when you
are done with it. Use the `dispose` method to do this. Do not use a `Sprite`
after it has been disposed. If you are unsure about this, don't take chances,
just let the garbage collector do it for you. But ideally, you can manage its
lifetime more efficiently.
$(NOTE `Sprite`, like the rest of simpledisplay's `ScreenPainter`, does not
support alpha blending in its drawing at this time. That might change in the
future, but if you need alpha blending right now, use OpenGL instead. See
`gamehelpers.d` for a similar class to `Sprite` that uses OpenGL: `OpenGlTexture`.)
FIXME: you are supposed to be able to draw on these similarly to on windows.
ScreenPainter needs to be refactored to allow that though. So until that is
done, consider a `Sprite` to have const contents.
*/
version(OSXCocoa) {} else // NotYetImplementedException
class Sprite : CapableOfBeingDrawnUpon {
///
ScreenPainter draw() {
return ScreenPainter(this, handle);
}
/// Be warned: this can be a very slow operation
/// FIXME NOT IMPLEMENTED
TrueColorImage takeScreenshot() {
return trueColorImageFromNativeHandle(handle, width, height);
}
void delegate() paintingFinishedDg() { return null; }
bool closed() { return false; }
ScreenPainterImplementation* activeScreenPainter_;
protected ScreenPainterImplementation* activeScreenPainter() { return activeScreenPainter_; }
protected void activeScreenPainter(ScreenPainterImplementation* i) { activeScreenPainter_ = i; }
version(Windows)
private ubyte* rawData;
// FIXME: sprites are lost when disconnecting from X! We need some way to invalidate them...
this(SimpleWindow win, int width, int height) {
this._width = width;
this._height = height;
version(X11) {
auto display = XDisplayConnection.get();
handle = XCreatePixmap(display, cast(Drawable) win.window, width, height, DefaultDepthOfDisplay(display));
} else version(Windows) {
BITMAPINFO infoheader;
infoheader.bmiHeader.biSize = infoheader.bmiHeader.sizeof;
infoheader.bmiHeader.biWidth = width;
infoheader.bmiHeader.biHeight = height;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biBitCount = 24;
infoheader.bmiHeader.biCompression = BI_RGB;
// FIXME: this should prolly be a device dependent bitmap...
handle = CreateDIBSection(
null,
&infoheader,
DIB_RGB_COLORS,
cast(void**) &rawData,
null,
0);
if(handle is null)
throw new Exception("couldn't create pixmap");
}
}
/// Makes a sprite based on the image with the initial contents from the Image
this(SimpleWindow win, Image i) {
this(win, i.width, i.height);
version(X11) {
auto display = XDisplayConnection.get();
if(i.usingXshm)
XShmPutImage(display, cast(Drawable) handle, DefaultGC(display, DefaultScreen(display)), i.handle, 0, 0, 0, 0, i.width, i.height, false);
else
XPutImage(display, cast(Drawable) handle, DefaultGC(display, DefaultScreen(display)), i.handle, 0, 0, 0, 0, i.width, i.height);
} else version(Windows) {
auto itemsPerLine = ((cast(int) width * 3 + 3) / 4) * 4;
auto arrLength = itemsPerLine * height;
rawData[0..arrLength] = i.rawData[0..arrLength];
} else version(OSXCocoa) {
// FIXME: I have no idea if this is even any good
ubyte* rawData;
auto colorSpace = CGColorSpaceCreateDeviceRGB();
context = CGBitmapContextCreate(null, width, height, 8, 4*width,
colorSpace,
kCGImageAlphaPremultipliedLast
|kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
rawData = CGBitmapContextGetData(context);
auto rdl = (width * height * 4);
rawData[0 .. rdl] = i.rawData[0 .. rdl];
} else static assert(0);
}
/++
Draws the image on the specified painter at the specified point. The point is the upper-left point where the image will be drawn.
+/
void drawAt(ScreenPainter painter, Point where) {
painter.drawPixmap(this, where);
}
/// Call this when you're ready to get rid of it
void dispose() {
version(X11) {
if(handle)
XFreePixmap(XDisplayConnection.get(), handle);
handle = None;
} else version(Windows) {
if(handle)
DeleteObject(handle);
handle = null;
} else version(OSXCocoa) {
if(context)
CGContextRelease(context);
context = null;
} else static assert(0);
}
~this() {
dispose();
}
///
final @property int width() { return _width; }
///
final @property int height() { return _height; }
private:
int _width;
int _height;
version(X11)
Pixmap handle;
else version(Windows)
HBITMAP handle;
else version(OSXCocoa)
CGContextRef context;
else static assert(0);
}
///
interface CapableOfBeingDrawnUpon {
///
ScreenPainter draw();
///
int width();
///
int height();
protected ScreenPainterImplementation* activeScreenPainter();
protected void activeScreenPainter(ScreenPainterImplementation*);
bool closed();
void delegate() paintingFinishedDg();
/// Be warned: this can be a very slow operation
TrueColorImage takeScreenshot();
}
/// Flushes any pending gui buffers. Necessary if you are using with_eventloop with X - flush after you create your windows but before you call loop()
void flushGui() {
version(X11) {
auto dpy = XDisplayConnection.get();
XLockDisplay(dpy);
scope(exit) XUnlockDisplay(dpy);
XFlush(dpy);
}
}
/// Used internal to dispatch events to various classes.
interface CapableOfHandlingNativeEvent {
NativeEventHandler getNativeEventHandler();
/*private*//*protected*/ __gshared CapableOfHandlingNativeEvent[NativeWindowHandle] nativeHandleMapping;
version(X11) {
// if this is impossible, you are allowed to just throw from it
// Note: if you call it from another object, set a flag cuz the manger will call you again
void recreateAfterDisconnect();
// discard any *connection specific* state, but keep enough that you
// can be recreated if possible. discardConnectionState() is always called immediately
// before recreateAfterDisconnect(), so you can set a flag there to decide if
// you need initialization order
void discardConnectionState();
}
}
version(X11)
/++
State of keys on mouse events, especially motion.
Do not trust the actual integer values in this, they are platform-specific. Always use the names.
+/
enum ModifierState : uint {
shift = 1, ///
capsLock = 2, ///
ctrl = 4, ///
alt = 8, /// Not always available on Windows
windows = 64, /// ditto
numLock = 16, ///
leftButtonDown = 256, /// these aren't available on Windows for key events, so don't use them for that unless your app is X only.
middleButtonDown = 512, /// ditto
rightButtonDown = 1024, /// ditto
}
else version(Windows)
/// ditto
enum ModifierState : uint {
shift = 4, ///
ctrl = 8, ///
// i'm not sure if the next two are available
alt = 256, /// not always available on Windows
windows = 512, /// ditto
capsLock = 1024, ///
numLock = 2048, ///
leftButtonDown = 1, /// not available on key events
middleButtonDown = 16, /// ditto
rightButtonDown = 2, /// ditto
backButtonDown = 0x20, /// not available on X
forwardButtonDown = 0x40, /// ditto
}
else version(OSXCocoa)
// FIXME FIXME NotYetImplementedException
enum ModifierState : uint {
shift = 1, ///
capsLock = 2, ///
ctrl = 4, ///
alt = 8, /// Not always available on Windows
windows = 64, /// ditto
numLock = 16, ///
leftButtonDown = 256, /// these aren't available on Windows for key events, so don't use them for that unless your app is X only.
middleButtonDown = 512, /// ditto
rightButtonDown = 1024, /// ditto
}
/// The names assume a right-handed mouse. These are bitwise combined on the events that use them
enum MouseButton : int {
none = 0,
left = 1, ///
right = 2, ///
middle = 4, ///
wheelUp = 8, ///
wheelDown = 16, ///
backButton = 32, /// often found on the thumb and used for back in browsers
forwardButton = 64, /// often found on the thumb and used for forward in browsers
}
version(X11) {
// FIXME: match ASCII whenever we can. Most of it is already there,
// but there's a few exceptions and mismatches with Windows
/// Do not trust the numeric values as they are platform-specific. Always use the symbolic name.
enum Key {
Escape = 0xff1b, ///
F1 = 0xffbe, ///
F2 = 0xffbf, ///
F3 = 0xffc0, ///
F4 = 0xffc1, ///
F5 = 0xffc2, ///
F6 = 0xffc3, ///
F7 = 0xffc4, ///
F8 = 0xffc5, ///
F9 = 0xffc6, ///
F10 = 0xffc7, ///
F11 = 0xffc8, ///
F12 = 0xffc9, ///
PrintScreen = 0xff61, ///
ScrollLock = 0xff14, ///
Pause = 0xff13, ///
Grave = 0x60, /// The $(BACKTICK) ~ key
// number keys across the top of the keyboard
N1 = 0x31, /// Number key atop the keyboard
N2 = 0x32, ///
N3 = 0x33, ///
N4 = 0x34, ///
N5 = 0x35, ///
N6 = 0x36, ///
N7 = 0x37, ///
N8 = 0x38, ///
N9 = 0x39, ///
N0 = 0x30, ///
Dash = 0x2d, ///
Equals = 0x3d, ///
Backslash = 0x5c, /// The \ | key
Backspace = 0xff08, ///
Insert = 0xff63, ///
Home = 0xff50, ///
PageUp = 0xff55, ///
Delete = 0xffff, ///
End = 0xff57, ///
PageDown = 0xff56, ///
Up = 0xff52, ///
Down = 0xff54, ///
Left = 0xff51, ///
Right = 0xff53, ///
Tab = 0xff09, ///
Q = 0x71, ///
W = 0x77, ///
E = 0x65, ///
R = 0x72, ///
T = 0x74, ///
Y = 0x79, ///
U = 0x75, ///
I = 0x69, ///
O = 0x6f, ///
P = 0x70, ///
LeftBracket = 0x5b, /// the [ { key
RightBracket = 0x5d, /// the ] } key
CapsLock = 0xffe5, ///
A = 0x61, ///
S = 0x73, ///
D = 0x64, ///
F = 0x66, ///
G = 0x67, ///
H = 0x68, ///
J = 0x6a, ///
K = 0x6b, ///
L = 0x6c, ///
Semicolon = 0x3b, ///
Apostrophe = 0x27, ///
Enter = 0xff0d, ///
Shift = 0xffe1, ///
Z = 0x7a, ///
X = 0x78, ///
C = 0x63, ///
V = 0x76, ///
B = 0x62, ///
N = 0x6e, ///
M = 0x6d, ///
Comma = 0x2c, ///
Period = 0x2e, ///
Slash = 0x2f, /// the / ? key
Shift_r = 0xffe2, /// Note: this isn't sent on all computers, sometimes it just sends Shift, so don't rely on it. If it is supported though, it is the right Shift key, as opposed to the left Shift key
Ctrl = 0xffe3, ///
Windows = 0xffeb, ///
Alt = 0xffe9, ///
Space = 0x20, ///
Alt_r = 0xffea, /// ditto of shift_r
Windows_r = 0xffec, ///
Menu = 0xff67, ///
Ctrl_r = 0xffe4, ///
NumLock = 0xff7f, ///
Divide = 0xffaf, /// The / key on the number pad
Multiply = 0xffaa, /// The * key on the number pad
Minus = 0xffad, /// The - key on the number pad
Plus = 0xffab, /// The + key on the number pad
PadEnter = 0xff8d, /// Numberpad enter key
Pad1 = 0xff9c, /// Numberpad keys
Pad2 = 0xff99, ///
Pad3 = 0xff9b, ///
Pad4 = 0xff96, ///
Pad5 = 0xff9d, ///
Pad6 = 0xff98, ///
Pad7 = 0xff95, ///
Pad8 = 0xff97, ///
Pad9 = 0xff9a, ///
Pad0 = 0xff9e, ///
PadDot = 0xff9f, ///
}
} else version(Windows) {
// the character here is for en-us layouts and for illustration only
// if you actually want to get characters, wait for character events
// (the argument to your event handler is simply a dchar)
// those will be converted by the OS for the right locale.
enum Key {
Escape = 0x1b,
F1 = 0x70,
F2 = 0x71,
F3 = 0x72,
F4 = 0x73,
F5 = 0x74,
F6 = 0x75,
F7 = 0x76,
F8 = 0x77,
F9 = 0x78,
F10 = 0x79,
F11 = 0x7a,
F12 = 0x7b,
PrintScreen = 0x2c,
ScrollLock = 0x91,
Pause = 0x13,
Grave = 0xc0,
// number keys across the top of the keyboard
N1 = 0x31,
N2 = 0x32,
N3 = 0x33,
N4 = 0x34,
N5 = 0x35,
N6 = 0x36,
N7 = 0x37,
N8 = 0x38,
N9 = 0x39,
N0 = 0x30,
Dash = 0xbd,
Equals = 0xbb,
Backslash = 0xdc,
Backspace = 0x08,
Insert = 0x2d,
Home = 0x24,
PageUp = 0x21,
Delete = 0x2e,
End = 0x23,
PageDown = 0x22,
Up = 0x26,
Down = 0x28,
Left = 0x25,
Right = 0x27,
Tab = 0x09,
Q = 0x51,
W = 0x57,
E = 0x45,
R = 0x52,
T = 0x54,
Y = 0x59,
U = 0x55,
I = 0x49,
O = 0x4f,
P = 0x50,
LeftBracket = 0xdb,
RightBracket = 0xdd,
CapsLock = 0x14,
A = 0x41,
S = 0x53,
D = 0x44,
F = 0x46,
G = 0x47,
H = 0x48,
J = 0x4a,
K = 0x4b,
L = 0x4c,
Semicolon = 0xba,
Apostrophe = 0xde,
Enter = 0x0d,
Shift = 0x10,
Z = 0x5a,
X = 0x58,
C = 0x43,
V = 0x56,
B = 0x42,
N = 0x4e,
M = 0x4d,
Comma = 0xbc,
Period = 0xbe,
Slash = 0xbf,
Shift_r = 0xa1, // FIXME Note: this isn't sent on all computers, sometimes it just sends Shift, so don't rely on it
Ctrl = 0x11,
Windows = 0x5b,
Alt = -5, // FIXME
Space = 0x20,
Alt_r = 0xffea, // ditto of shift_r
Windows_r = 0x5c, // ditto of shift_r
Menu = 0x5d,
Ctrl_r = 0xa3, // ditto of shift_r
NumLock = 0x90,
Divide = 0x6f,
Multiply = 0x6a,
Minus = 0x6d,
Plus = 0x6b,
PadEnter = -8, // FIXME
Pad1 = 0x61,
Pad2 = 0x62,
Pad3 = 0x63,
Pad4 = 0x64,
Pad5 = 0x65,
Pad6 = 0x66,
Pad7 = 0x67,
Pad8 = 0x68,
Pad9 = 0x69,
Pad0 = 0x60,
PadDot = 0x6e,
}
// I'm keeping this around for reference purposes
// ideally all these buttons will be listed for all platforms,
// but now now I'm just focusing on my US keyboard
version(none)
enum Key {
LBUTTON = 0x01,
RBUTTON = 0x02,
CANCEL = 0x03,
MBUTTON = 0x04,
//static if (_WIN32_WINNT > = 0x500) {
XBUTTON1 = 0x05,
XBUTTON2 = 0x06,
//}
BACK = 0x08,
TAB = 0x09,
CLEAR = 0x0C,
RETURN = 0x0D,
SHIFT = 0x10,
CONTROL = 0x11,
MENU = 0x12,
PAUSE = 0x13,
CAPITAL = 0x14,
KANA = 0x15,
HANGEUL = 0x15,
HANGUL = 0x15,
JUNJA = 0x17,
FINAL = 0x18,
HANJA = 0x19,
KANJI = 0x19,
ESCAPE = 0x1B,
CONVERT = 0x1C,
NONCONVERT = 0x1D,
ACCEPT = 0x1E,
MODECHANGE = 0x1F,
SPACE = 0x20,
PRIOR = 0x21,
NEXT = 0x22,
END = 0x23,
HOME = 0x24,
LEFT = 0x25,
UP = 0x26,
RIGHT = 0x27,
DOWN = 0x28,
SELECT = 0x29,
PRINT = 0x2A,
EXECUTE = 0x2B,
SNAPSHOT = 0x2C,
INSERT = 0x2D,
DELETE = 0x2E,
HELP = 0x2F,
LWIN = 0x5B,
RWIN = 0x5C,
APPS = 0x5D,
SLEEP = 0x5F,
NUMPAD0 = 0x60,
NUMPAD1 = 0x61,
NUMPAD2 = 0x62,
NUMPAD3 = 0x63,
NUMPAD4 = 0x64,
NUMPAD5 = 0x65,
NUMPAD6 = 0x66,
NUMPAD7 = 0x67,
NUMPAD8 = 0x68,
NUMPAD9 = 0x69,
MULTIPLY = 0x6A,
ADD = 0x6B,
SEPARATOR = 0x6C,
SUBTRACT = 0x6D,
DECIMAL = 0x6E,
DIVIDE = 0x6F,
F1 = 0x70,
F2 = 0x71,
F3 = 0x72,
F4 = 0x73,
F5 = 0x74,
F6 = 0x75,
F7 = 0x76,
F8 = 0x77,
F9 = 0x78,
F10 = 0x79,
F11 = 0x7A,
F12 = 0x7B,
F13 = 0x7C,
F14 = 0x7D,
F15 = 0x7E,
F16 = 0x7F,
F17 = 0x80,
F18 = 0x81,
F19 = 0x82,
F20 = 0x83,
F21 = 0x84,
F22 = 0x85,
F23 = 0x86,
F24 = 0x87,
NUMLOCK = 0x90,
SCROLL = 0x91,
LSHIFT = 0xA0,
RSHIFT = 0xA1,
LCONTROL = 0xA2,
RCONTROL = 0xA3,
LMENU = 0xA4,
RMENU = 0xA5,
//static if (_WIN32_WINNT > = 0x500) {
BROWSER_BACK = 0xA6,
BROWSER_FORWARD = 0xA7,
BROWSER_REFRESH = 0xA8,
BROWSER_STOP = 0xA9,
BROWSER_SEARCH = 0xAA,
BROWSER_FAVORITES = 0xAB,
BROWSER_HOME = 0xAC,
VOLUME_MUTE = 0xAD,
VOLUME_DOWN = 0xAE,
VOLUME_UP = 0xAF,
MEDIA_NEXT_TRACK = 0xB0,
MEDIA_PREV_TRACK = 0xB1,
MEDIA_STOP = 0xB2,
MEDIA_PLAY_PAUSE = 0xB3,
LAUNCH_MAIL = 0xB4,
LAUNCH_MEDIA_SELECT = 0xB5,
LAUNCH_APP1 = 0xB6,
LAUNCH_APP2 = 0xB7,
//}
OEM_1 = 0xBA,
//static if (_WIN32_WINNT > = 0x500) {
OEM_PLUS = 0xBB,
OEM_COMMA = 0xBC,
OEM_MINUS = 0xBD,
OEM_PERIOD = 0xBE,
//}
OEM_2 = 0xBF,
OEM_3 = 0xC0,
OEM_4 = 0xDB,
OEM_5 = 0xDC,
OEM_6 = 0xDD,
OEM_7 = 0xDE,
OEM_8 = 0xDF,
//static if (_WIN32_WINNT > = 0x500) {
OEM_102 = 0xE2,
//}
PROCESSKEY = 0xE5,
//static if (_WIN32_WINNT > = 0x500) {
PACKET = 0xE7,
//}
ATTN = 0xF6,
CRSEL = 0xF7,
EXSEL = 0xF8,
EREOF = 0xF9,
PLAY = 0xFA,
ZOOM = 0xFB,
NONAME = 0xFC,
PA1 = 0xFD,
OEM_CLEAR = 0xFE,
}
} else version(OSXCocoa) {
// FIXME
enum Key {
Escape = 0x1b,
F1 = 0x70,
F2 = 0x71,
F3 = 0x72,
F4 = 0x73,
F5 = 0x74,
F6 = 0x75,
F7 = 0x76,
F8 = 0x77,
F9 = 0x78,
F10 = 0x79,
F11 = 0x7a,
F12 = 0x7b,
PrintScreen = 0x2c,
ScrollLock = -2, // FIXME
Pause = -3, // FIXME
Grave = 0xc0,
// number keys across the top of the keyboard
N1 = 0x31,
N2 = 0x32,
N3 = 0x33,
N4 = 0x34,
N5 = 0x35,
N6 = 0x36,
N7 = 0x37,
N8 = 0x38,
N9 = 0x39,
N0 = 0x30,
Dash = 0xbd,
Equals = 0xbb,
Backslash = 0xdc,
Backspace = 0x08,
Insert = 0x2d,
Home = 0x24,
PageUp = 0x21,
Delete = 0x2e,
End = 0x23,
PageDown = 0x22,
Up = 0x26,
Down = 0x28,
Left = 0x25,
Right = 0x27,
Tab = 0x09,
Q = 0x51,
W = 0x57,
E = 0x45,
R = 0x52,
T = 0x54,
Y = 0x59,
U = 0x55,
I = 0x49,
O = 0x4f,
P = 0x50,
LeftBracket = 0xdb,
RightBracket = 0xdd,
CapsLock = 0x14,
A = 0x41,
S = 0x53,
D = 0x44,
F = 0x46,
G = 0x47,
H = 0x48,
J = 0x4a,
K = 0x4b,
L = 0x4c,
Semicolon = 0xba,
Apostrophe = 0xde,
Enter = 0x0d,
Shift = 0x10,
Z = 0x5a,
X = 0x58,
C = 0x43,
V = 0x56,
B = 0x42,
N = 0x4e,
M = 0x4d,
Comma = 0xbc,
Period = 0xbe,
Slash = 0xbf,
Shift_r = -4, // FIXME Note: this isn't sent on all computers, sometimes it just sends Shift, so don't rely on it
Ctrl = 0x11,
Windows = 0x5b,
Alt = -5, // FIXME
Space = 0x20,
Alt_r = 0xffea, // ditto of shift_r
Windows_r = -6, // FIXME
Menu = 0x5d,
Ctrl_r = -7, // FIXME
NumLock = 0x90,
Divide = 0x6f,
Multiply = 0x6a,
Minus = 0x6d,
Plus = 0x6b,
PadEnter = -8, // FIXME
// FIXME for the rest of these:
Pad1 = 0xff9c,
Pad2 = 0xff99,
Pad3 = 0xff9b,
Pad4 = 0xff96,
Pad5 = 0xff9d,
Pad6 = 0xff98,
Pad7 = 0xff95,
Pad8 = 0xff97,
Pad9 = 0xff9a,
Pad0 = 0xff9e,
PadDot = 0xff9f,
}
}
/* Additional utilities */
Color fromHsl(real h, real s, real l) {
return arsd.color.fromHsl([h,s,l]);
}
/* ********** What follows is the system-specific implementations *********/
version(Windows) {
// helpers for making HICONs from MemoryImages
class WindowsIcon {
struct Win32Icon(int colorCount) {
align(1):
uint biSize;
int biWidth;
int biHeight;
ushort biPlanes;
ushort biBitCount;
uint biCompression;
uint biSizeImage;
int biXPelsPerMeter;
int biYPelsPerMeter;
uint biClrUsed;
uint biClrImportant;
RGBQUAD[colorCount] biColors;
/* Pixels:
Uint8 pixels[]
*/
/* Mask:
Uint8 mask[]
*/
ubyte[4096] data;
void fromMemoryImage(MemoryImage mi, out int icon_len, out int width, out int height) {
width = mi.width;
height = mi.height;
auto indexedImage = cast(IndexedImage) mi;
if(indexedImage is null)
indexedImage = quantize(mi.getAsTrueColorImage());
assert(width %8 == 0); // i don't want padding nor do i want the and mask to get fancy
assert(height %4 == 0);
int icon_plen = height*((width+3)&~3);
int icon_mlen = height*((((width+7)/8)+3)&~3);
icon_len = 40+icon_plen+icon_mlen + cast(int) RGBQUAD.sizeof * colorCount;
biSize = 40;
biWidth = width;
biHeight = height*2;
biPlanes = 1;
biBitCount = 8;
biSizeImage = icon_plen+icon_mlen;
int offset = 0;
int andOff = icon_plen * 8; // the and offset is in bits
for(int y = height - 1; y >= 0; y--) {
int off2 = y * width;
foreach(x; 0 .. width) {
const b = indexedImage.data[off2 + x];
data[offset] = b;
offset++;
const andBit = andOff % 8;
const andIdx = andOff / 8;
assert(b < indexedImage.palette.length);
// this is anded to the destination, since and 0 means erase,
// we want that to be opaque, and 1 for transparent
auto transparent = (indexedImage.palette[b].a <= 127);
data[andIdx] |= (transparent ? (1 << (7-andBit)) : 0);
andOff++;
}
andOff += andOff % 32;
}
foreach(idx, entry; indexedImage.palette) {
if(entry.a > 127) {
biColors[idx].rgbBlue = entry.b;
biColors[idx].rgbGreen = entry.g;
biColors[idx].rgbRed = entry.r;
} else {
biColors[idx].rgbBlue = 255;
biColors[idx].rgbGreen = 255;
biColors[idx].rgbRed = 255;
}
}
/*
data[0..icon_plen] = getFlippedUnfilteredDatastream(png);
data[icon_plen..icon_plen+icon_mlen] = getANDMask(png);
//icon_win32.biColors[1] = Win32Icon.RGBQUAD(0,255,0,0);
auto pngMap = fetchPaletteWin32(png);
biColors[0..pngMap.length] = pngMap[];
*/
}
}
Win32Icon!(256) icon_win32;
this(MemoryImage mi) {
int icon_len, width, height;
icon_win32.fromMemoryImage(mi, icon_len, width, height);
/*
PNG* png = readPnpngData);
PNGHeader pngh = getHeader(png);
void* icon_win32;
if(pngh.depth == 4) {
auto i = new Win32Icon!(16);
i.fromPNG(png, pngh, icon_len, width, height);
icon_win32 = i;
}
else if(pngh.depth == 8) {
auto i = new Win32Icon!(256);
i.fromPNG(png, pngh, icon_len, width, height);
icon_win32 = i;
} else assert(0);
*/
hIcon = CreateIconFromResourceEx(cast(ubyte*) &icon_win32, icon_len, true, 0x00030000, width, height, 0);
if(hIcon is null) throw new Exception("CreateIconFromResourceEx");
}
~this() {
DestroyIcon(hIcon);
}
HICON hIcon;
}
alias int delegate(HWND, UINT, WPARAM, LPARAM) NativeEventHandler;
alias HWND NativeWindowHandle;
extern(Windows)
LRESULT WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam) nothrow {
try {
if(SimpleWindow.handleNativeGlobalEvent !is null) {
// it returns zero if the message is handled, so we won't do anything more there
// do I like that though?
auto ret = SimpleWindow.handleNativeGlobalEvent(hWnd, iMessage, wParam, lParam);
if(ret == 0)
return ret;
}
if(auto window = hWnd in CapableOfHandlingNativeEvent.nativeHandleMapping) {
if(window.getNativeEventHandler !is null) {
auto ret = window.getNativeEventHandler()(hWnd, iMessage, wParam, lParam);
if(ret == 0)
return ret;
}
if(auto w = cast(SimpleWindow) (*window))
return w.windowProcedure(hWnd, iMessage, wParam, lParam);
else
return DefWindowProc(hWnd, iMessage, wParam, lParam);
} else {
return DefWindowProc(hWnd, iMessage, wParam, lParam);
}
} catch (Exception e) {
assert(false, "Exception caught in WndProc " ~ e.toString());
}
}
mixin template NativeScreenPainterImplementation() {
HDC hdc;
HWND hwnd;
//HDC windowHdc;
HBITMAP oldBmp;
void create(NativeWindowHandle window) {
hwnd = window;
if(auto sw = cast(SimpleWindow) this.window) {
// drawing on a window, double buffer
auto windowHdc = GetDC(hwnd);
auto buffer = sw.impl.buffer;
hdc = CreateCompatibleDC(windowHdc);
ReleaseDC(hwnd, windowHdc);
oldBmp = SelectObject(hdc, buffer);
} else {
// drawing on something else, draw directly
hdc = CreateCompatibleDC(null);
SelectObject(hdc, window);
}
// X doesn't draw a text background, so neither should we
SetBkMode(hdc, TRANSPARENT);
static bool triedDefaultGuiFont = false;
if(!triedDefaultGuiFont) {
NONCLIENTMETRICS params;
params.cbSize = params.sizeof;
if(SystemParametersInfo(SPI_GETNONCLIENTMETRICS, params.sizeof, ¶ms, 0)) {
defaultGuiFont = CreateFontIndirect(¶ms.lfMessageFont);
}
triedDefaultGuiFont = true;
}
if(defaultGuiFont) {
SelectObject(hdc, defaultGuiFont);
// DeleteObject(defaultGuiFont);
}
}
static HFONT defaultGuiFont;
void setFont(OperatingSystemFont font) {
if(font && font.font)
SelectObject(hdc, font.font);
else if(defaultGuiFont)
SelectObject(hdc, defaultGuiFont);
}
arsd.color.Rectangle _clipRectangle;
void setClipRectangle(int x, int y, int width, int height) {
_clipRectangle = arsd.color.Rectangle(Point(x, y), Size(width, height));
if(width == 0 || height == 0) {
SelectClipRgn(hdc, null);
} else {
auto region = CreateRectRgn(x, y, x + width, y + height);
SelectClipRgn(hdc, region);
DeleteObject(region);
}
}
// just because we can on Windows...
//void create(Image image);
void dispose() {
// FIXME: this.window.width/height is probably wrong
// BitBlt(windowHdc, 0, 0, this.window.width, this.window.height, hdc, 0, 0, SRCCOPY);
// ReleaseDC(hwnd, windowHdc);
// FIXME: it shouldn't invalidate the whole thing in all cases... it would be ideal to do this right
if(cast(SimpleWindow) this.window)
InvalidateRect(hwnd, cast(RECT*)null, false); // no need to erase bg as the whole thing gets bitblt'd ove
if(originalPen !is null)
SelectObject(hdc, originalPen);
if(currentPen !is null)
DeleteObject(currentPen);
if(originalBrush !is null)
SelectObject(hdc, originalBrush);
if(currentBrush !is null)
DeleteObject(currentBrush);
SelectObject(hdc, oldBmp);
DeleteDC(hdc);
if(window.paintingFinishedDg !is null)
window.paintingFinishedDg();
}
HPEN originalPen;
HPEN currentPen;
Pen _activePen;
@property void pen(Pen p) {
_activePen = p;
HPEN pen;
if(p.color.a == 0) {
pen = GetStockObject(NULL_PEN);
} else {
int style = PS_SOLID;
final switch(p.style) {
case Pen.Style.Solid:
style = PS_SOLID;
break;
case Pen.Style.Dashed:
style = PS_DASH;
break;
case Pen.Style.Dotted:
style = PS_DOT;
break;
}
pen = CreatePen(style, p.width, RGB(p.color.r, p.color.g, p.color.b));
}
auto orig = SelectObject(hdc, pen);
if(originalPen is null)
originalPen = orig;
if(currentPen !is null)
DeleteObject(currentPen);
currentPen = pen;
// the outline is like a foreground since it's done that way on X
SetTextColor(hdc, RGB(p.color.r, p.color.g, p.color.b));
}
@property void rasterOp(RasterOp op) {
int mode;
final switch(op) {
case RasterOp.normal:
mode = R2_COPYPEN;
break;
case RasterOp.xor:
mode = R2_XORPEN;
break;
}
SetROP2(hdc, mode);
}
HBRUSH originalBrush;
HBRUSH currentBrush;
Color _fillColor = Color(1, 1, 1, 1); // what are the odds that they'd set this??
@property void fillColor(Color c) {
if(c == _fillColor)
return;
_fillColor = c;
HBRUSH brush;
if(c.a == 0) {
brush = GetStockObject(HOLLOW_BRUSH);
} else {
brush = CreateSolidBrush(RGB(c.r, c.g, c.b));
}
auto orig = SelectObject(hdc, brush);
if(originalBrush is null)
originalBrush = orig;
if(currentBrush !is null)
DeleteObject(currentBrush);
currentBrush = brush;
// background color is NOT set because X doesn't draw text backgrounds
// SetBkColor(hdc, RGB(255, 255, 255));
}
void drawImage(int x, int y, Image i, int ix, int iy, int w, int h) {
BITMAP bm;
HDC hdcMem = CreateCompatibleDC(hdc);
HBITMAP hbmOld = SelectObject(hdcMem, i.handle);
GetObject(i.handle, bm.sizeof, &bm);
BitBlt(hdc, x, y, w /* bm.bmWidth */, /*bm.bmHeight*/ h, hdcMem, ix, iy, SRCCOPY);
SelectObject(hdcMem, hbmOld);
DeleteDC(hdcMem);
}
void drawPixmap(Sprite s, int x, int y) {
BITMAP bm;
HDC hdcMem = CreateCompatibleDC(hdc);
HBITMAP hbmOld = SelectObject(hdcMem, s.handle);
GetObject(s.handle, bm.sizeof, &bm);
BitBlt(hdc, x, y, bm.bmWidth, bm.bmHeight, hdcMem, 0, 0, SRCCOPY);
SelectObject(hdcMem, hbmOld);
DeleteDC(hdcMem);
}
Size textSize(scope const(char)[] text) {
bool dummyX;
if(text.length == 0) {
text = " ";
dummyX = true;
}
RECT rect;
WCharzBuffer buffer = WCharzBuffer(text);
DrawTextW(hdc, buffer.ptr, cast(int) buffer.length, &rect, DT_CALCRECT);
return Size(dummyX ? 0 : rect.right, rect.bottom);
}
void drawText(int x, int y, int x2, int y2, scope const(char)[] text, uint alignment) {
if(text.length && text[$-1] == '\n')
text = text[0 .. $-1]; // tailing newlines are weird on windows...
WCharzBuffer buffer = WCharzBuffer(text);
if(x2 == 0 && y2 == 0)
TextOutW(hdc, x, y, buffer.ptr, cast(int) buffer.length);
else {
RECT rect;
rect.left = x;
rect.top = y;
rect.right = x2;
rect.bottom = y2;
uint mode = DT_LEFT;
if(alignment & TextAlignment.Right)
mode = DT_RIGHT;
else if(alignment & TextAlignment.Center)
mode = DT_CENTER;
// FIXME: vcenter on windows only works with single line, but I want it to work in all cases
if(alignment & TextAlignment.VerticalCenter)
mode |= DT_VCENTER | DT_SINGLELINE;
DrawTextW(hdc, buffer.ptr, cast(int) buffer.length, &rect, mode);
}
/*
uint mode;
if(alignment & TextAlignment.Center)
mode = TA_CENTER;
SetTextAlign(hdc, mode);
*/
}
int fontHeight() {
TEXTMETRIC metric;
if(GetTextMetricsW(hdc, &metric)) {
return metric.tmHeight;
}
return 16; // idk just guessing here, maybe we should throw
}
void drawPixel(int x, int y) {
SetPixel(hdc, x, y, RGB(_activePen.color.r, _activePen.color.g, _activePen.color.b));
}
// The basic shapes, outlined
void drawLine(int x1, int y1, int x2, int y2) {
MoveToEx(hdc, x1, y1, null);
LineTo(hdc, x2, y2);
}
void drawRectangle(int x, int y, int width, int height) {
gdi.Rectangle(hdc, x, y, x + width, y + height);
}
/// Arguments are the points of the bounding rectangle
void drawEllipse(int x1, int y1, int x2, int y2) {
Ellipse(hdc, x1, y1, x2, y2);
}
void drawArc(int x1, int y1, int width, int height, int start, int finish) {
if((start % (360*64)) == (finish % (360*64)))
drawEllipse(x1, y1, x1 + width, y1 + height);
else {
import core.stdc.math;
float startAngle = start * 64 * 180 / 3.14159265;
float endAngle = finish * 64 * 180 / 3.14159265;
Arc(hdc, x1, y1, x1 + width, y1 + height,
cast(int)(cos(startAngle) * width / 2 + x1),
cast(int)(sin(startAngle) * height / 2 + y1),
cast(int)(cos(endAngle) * width / 2 + x1),
cast(int)(sin(endAngle) * height / 2 + y1),
);
}
}
void drawPolygon(Point[] vertexes) {
POINT[] points;
points.length = vertexes.length;
foreach(i, p; vertexes) {
points[i].x = p.x;
points[i].y = p.y;
}
Polygon(hdc, points.ptr, cast(int) points.length);
}
}
// Mix this into the SimpleWindow class
mixin template NativeSimpleWindowImplementation() {
int curHidden = 0; // counter
__gshared static bool[string] knownWinClasses;
static bool altPressed = false;
HANDLE oldCursor;
void hideCursor () {
if(curHidden == 0)
oldCursor = SetCursor(null);
++curHidden;
}
void showCursor () {
--curHidden;
if(curHidden == 0) {
SetCursor(currentCursor is null ? oldCursor : currentCursor); // show it immediately without waiting for mouse movement
}
}
int minWidth = 0, minHeight = 0, maxWidth = int.max, maxHeight = int.max;
void setMinSize (int minwidth, int minheight) {
minWidth = minwidth;
minHeight = minheight;
}
void setMaxSize (int maxwidth, int maxheight) {
maxWidth = maxwidth;
maxHeight = maxheight;
}
// FIXME i'm not sure that Windows has this functionality
// though it is nonessential anyway.
void setResizeGranularity (int granx, int grany) {}
ScreenPainter getPainter() {
return ScreenPainter(this, hwnd);
}
HBITMAP buffer;
void setTitle(string title) {
WCharzBuffer bfr = WCharzBuffer(title);
SetWindowTextW(hwnd, bfr.ptr);
}
string getTitle() {
auto len = GetWindowTextLengthW(hwnd);
if (!len)
return null;
wchar[256] tmpBuffer;
wchar[] buffer = (len <= tmpBuffer.length) ? tmpBuffer[] : new wchar[len];
auto len2 = GetWindowTextW(hwnd, buffer.ptr, cast(int) buffer.length);
auto str = buffer[0 .. len2];
return makeUtf8StringFromWindowsString(str);
}
void move(int x, int y) {
RECT rect;
GetWindowRect(hwnd, &rect);
// move it while maintaining the same size...
MoveWindow(hwnd, x, y, rect.right - rect.left, rect.bottom - rect.top, true);
}
void resize(int w, int h) {
RECT rect;
GetWindowRect(hwnd, &rect);
RECT client;
GetClientRect(hwnd, &client);
rect.right = rect.right - client.right + w;
rect.bottom = rect.bottom - client.bottom + h;
// same position, new size for the client rectangle
MoveWindow(hwnd, rect.left, rect.top, rect.right, rect.bottom, true);
version(without_opengl) {} else if (openglMode == OpenGlOptions.yes) glViewport(0, 0, w, h);
}
void moveResize (int x, int y, int w, int h) {
// what's given is the client rectangle, we need to adjust
RECT rect;
rect.left = x;
rect.top = y;
rect.right = w + x;
rect.bottom = h + y;
if(!AdjustWindowRect(&rect, GetWindowLong(hwnd, GWL_STYLE), GetMenu(hwnd) !is null))
throw new Exception("AdjustWindowRect");
MoveWindow(hwnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, true);
version(without_opengl) {} else if (openglMode == OpenGlOptions.yes) glViewport(0, 0, w, h);
if (windowResized !is null) windowResized(w, h);
}
version(without_opengl) {} else {
HGLRC ghRC;
HDC ghDC;
}
void createWindow(int width, int height, string title, OpenGlOptions opengl, SimpleWindow parent) {
import std.conv : to;
string cnamec;
wstring cn;// = "DSimpleWindow\0"w.dup;
if (sdpyWindowClassStr is null) loadBinNameToWindowClassName();
if (sdpyWindowClassStr is null || sdpyWindowClassStr[0] == 0) {
cnamec = "DSimpleWindow";
} else {
cnamec = sdpyWindowClass;
}
cn = cnamec.to!wstring ~ "\0"; // just in case, lol
HINSTANCE hInstance = cast(HINSTANCE) GetModuleHandle(null);
if(cnamec !in knownWinClasses) {
WNDCLASSEX wc;
// FIXME: I might be able to use cbWndExtra to hold the pointer back
// to the object. Maybe.
wc.cbSize = wc.sizeof;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hbrBackground = cast(HBRUSH) (COLOR_WINDOW+1); // GetStockObject(WHITE_BRUSH);
wc.hCursor = LoadCursorW(null, IDC_ARROW);
wc.hIcon = LoadIcon(hInstance, null);
wc.hInstance = hInstance;
wc.lpfnWndProc = &WndProc;
wc.lpszClassName = cn.ptr;
wc.hIconSm = null;
wc.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
if(!RegisterClassExW(&wc))
throw new WindowsApiException("RegisterClassExW");
knownWinClasses[cnamec] = true;
}
int style;
// FIXME: windowType and customizationFlags
final switch(windowType) {
case WindowTypes.normal:
style = WS_OVERLAPPEDWINDOW;
break;
case WindowTypes.undecorated:
style = WS_POPUP | WS_SYSMENU;
break;
case WindowTypes.eventOnly:
_hidden = true;
break;
case WindowTypes.dropdownMenu:
case WindowTypes.popupMenu:
case WindowTypes.notification:
style = WS_POPUP;
break;
case WindowTypes.nestedChild:
style = WS_CHILD;
break;
}
uint flags = WS_EX_ACCEPTFILES; // accept drag-drop files
if ((customizationFlags & WindowFlags.extraComposite) != 0)
flags |= WS_EX_LAYERED; // composite window for better performance and effects support
hwnd = CreateWindowEx(flags, cn.ptr, toWStringz(title), style | WS_CLIPCHILDREN, // the clip children helps avoid flickering in minigui and doesn't seem to harm other use (mostly, sdpy is no child windows anyway) sooo i think it is ok
CW_USEDEFAULT, CW_USEDEFAULT, width, height,
parent is null ? null : parent.impl.hwnd, null, hInstance, null);
if ((customizationFlags & WindowFlags.extraComposite) != 0)
setOpacity(255);
SimpleWindow.nativeMapping[hwnd] = this;
CapableOfHandlingNativeEvent.nativeHandleMapping[hwnd] = this;
if(windowType == WindowTypes.eventOnly)
return;
HDC hdc = GetDC(hwnd);
version(without_opengl) {}
else {
if(opengl == OpenGlOptions.yes) {
static if (SdpyIsUsingIVGLBinds) {if (glbindGetProcAddress("glHint") is null) assert(0, "GL: error loading OpenGL"); } // loads all necessary functions
static if (SdpyIsUsingIVGLBinds) import iv.glbinds; // override druntime windows imports
ghDC = hdc;
PIXELFORMATDESCRIPTOR pfd;
pfd.nSize = PIXELFORMATDESCRIPTOR.sizeof;
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.dwLayerMask = PFD_MAIN_PLANE;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 24;
pfd.cAccumBits = 0;
pfd.cStencilBits = 8; // any reasonable OpenGL implementation should support this anyway
auto pixelformat = ChoosePixelFormat(hdc, &pfd);
if ((pixelformat = ChoosePixelFormat(hdc, &pfd)) == 0)
throw new WindowsApiException("ChoosePixelFormat");
if (SetPixelFormat(hdc, pixelformat, &pfd) == 0)
throw new WindowsApiException("SetPixelFormat");
if (sdpyOpenGLContextVersion && wglCreateContextAttribsARB is null) {
// windoze is idiotic: we have to have OpenGL context to get function addresses
// so we will create fake context to get that stupid address
auto tmpcc = wglCreateContext(ghDC);
if (tmpcc !is null) {
scope(exit) { wglMakeCurrent(ghDC, null); wglDeleteContext(tmpcc); }
wglMakeCurrent(ghDC, tmpcc);
wglInitOtherFunctions();
}
}
if (wglCreateContextAttribsARB !is null && sdpyOpenGLContextVersion) {
int[9] contextAttribs = [
WGL_CONTEXT_MAJOR_VERSION_ARB, (sdpyOpenGLContextVersion>>8),
WGL_CONTEXT_MINOR_VERSION_ARB, (sdpyOpenGLContextVersion&0xff),
WGL_CONTEXT_PROFILE_MASK_ARB, (sdpyOpenGLContextCompatible ? WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB : WGL_CONTEXT_CORE_PROFILE_BIT_ARB),
// for modern context, set "forward compatibility" flag too
(sdpyOpenGLContextCompatible ? 0/*None*/ : WGL_CONTEXT_FLAGS_ARB), WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
0/*None*/,
];
ghRC = wglCreateContextAttribsARB(ghDC, null, contextAttribs.ptr);
if (ghRC is null && sdpyOpenGLContextAllowFallback) {
// activate fallback mode
// sdpyOpenGLContextVeto-type focus management policy leads to race conditions because the window becoming unviewable may coincide with the window manager deciding to move the focus elsrsion = 0;
ghRC = wglCreateContext(ghDC);
}
if (ghRC is null)
throw new WindowsApiException("wglCreateContextAttribsARB");
} else {
// try to do at least something
if (sdpyOpenGLContextAllowFallback || sdpyOpenGLContextVersion == 0) {
sdpyOpenGLContextVersion = 0;
ghRC = wglCreateContext(ghDC);
}
if (ghRC is null)
throw new WindowsApiException("wglCreateContext");
}
}
}
if(opengl == OpenGlOptions.no) {
buffer = CreateCompatibleBitmap(hdc, width, height);
auto hdcBmp = CreateCompatibleDC(hdc);
// make sure it's filled with a blank slate
auto oldBmp = SelectObject(hdcBmp, buffer);
auto oldBrush = SelectObject(hdcBmp, GetStockObject(WHITE_BRUSH));
auto oldPen = SelectObject(hdcBmp, GetStockObject(WHITE_PEN));
gdi.Rectangle(hdcBmp, 0, 0, width, height);
SelectObject(hdcBmp, oldBmp);
SelectObject(hdcBmp, oldBrush);
SelectObject(hdcBmp, oldPen);
DeleteDC(hdcBmp);
ReleaseDC(hwnd, hdc); // we keep this in opengl mode since it is a class member now
}
// We want the window's client area to match the image size
RECT rcClient, rcWindow;
POINT ptDiff;
GetClientRect(hwnd, &rcClient);
GetWindowRect(hwnd, &rcWindow);
ptDiff.x = (rcWindow.right - rcWindow.left) - rcClient.right;
ptDiff.y = (rcWindow.bottom - rcWindow.top) - rcClient.bottom;
MoveWindow(hwnd,rcWindow.left, rcWindow.top, width + ptDiff.x, height + ptDiff.y, true);
if ((customizationFlags&WindowFlags.dontAutoShow) == 0) {
ShowWindow(hwnd, SW_SHOWNORMAL);
} else {
_hidden = true;
}
this._visibleForTheFirstTimeCalled = false; // hack!
}
void dispose() {
if(buffer)
DeleteObject(buffer);
}
void closeWindow() {
DestroyWindow(hwnd);
}
bool setOpacity(ubyte alpha) {
return SetLayeredWindowAttributes(hwnd, 0, alpha, LWA_ALPHA) == TRUE;
}
HANDLE currentCursor;
// returns zero if it recognized the event
static int triggerEvents(HWND hwnd, uint msg, WPARAM wParam, LPARAM lParam, int offsetX, int offsetY, SimpleWindow wind) {
MouseEvent mouse;
void mouseEvent() {
mouse.x = LOWORD(lParam) + offsetX;
mouse.y = HIWORD(lParam) + offsetY;
wind.mdx(mouse);
mouse.modifierState = cast(int) wParam;
mouse.window = wind;
if(wind.handleMouseEvent)
wind.handleMouseEvent(mouse);
}
switch(msg) {
case WM_GETMINMAXINFO:
MINMAXINFO* mmi = cast(MINMAXINFO*) lParam;
if(wind.minWidth > 0) {
RECT rect;
rect.left = 100;
rect.top = 100;
rect.right = wind.minWidth + 100;
rect.bottom = wind.minHeight + 100;
if(!AdjustWindowRect(&rect, GetWindowLong(wind.hwnd, GWL_STYLE), GetMenu(wind.hwnd) !is null))
throw new WindowsApiException("AdjustWindowRect");
mmi.ptMinTrackSize.x = rect.right - rect.left;
mmi.ptMinTrackSize.y = rect.bottom - rect.top;
}
if(wind.maxWidth < int.max) {
RECT rect;
rect.left = 100;
rect.top = 100;
rect.right = wind.maxWidth + 100;
rect.bottom = wind.maxHeight + 100;
if(!AdjustWindowRect(&rect, GetWindowLong(wind.hwnd, GWL_STYLE), GetMenu(wind.hwnd) !is null))
throw new WindowsApiException("AdjustWindowRect");
mmi.ptMaxTrackSize.x = rect.right - rect.left;
mmi.ptMaxTrackSize.y = rect.bottom - rect.top;
}
break;
case WM_CHAR:
wchar c = cast(wchar) wParam;
if(wind.handleCharEvent)
wind.handleCharEvent(cast(dchar) c);
break;
case WM_SETFOCUS:
case WM_KILLFOCUS:
wind._focused = (msg == WM_SETFOCUS);
if (msg == WM_SETFOCUS) altPressed = false; //k8: reset alt state on defocus (it is better than nothing...)
if(wind.onFocusChange)
wind.onFocusChange(msg == WM_SETFOCUS);
break;
case WM_SYSKEYDOWN:
case WM_SYSKEYUP:
case WM_KEYDOWN:
case WM_KEYUP:
KeyEvent ev;
ev.key = cast(Key) wParam;
ev.pressed = (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN);
if ((msg == WM_SYSKEYDOWN || msg == WM_SYSKEYUP) && wParam == 0x12) ev.key = Key.Alt; // windows does it this way
ev.hardwareCode = (lParam & 0xff0000) >> 16;
if(GetKeyState(Key.Shift)&0x8000 || GetKeyState(Key.Shift_r)&0x8000)
ev.modifierState |= ModifierState.shift;
//k8: this doesn't work; thanks for nothing, windows
/*if(GetKeyState(Key.Alt)&0x8000 || GetKeyState(Key.Alt_r)&0x8000)
ev.modifierState |= ModifierState.alt;*/
if ((msg == WM_SYSKEYDOWN || msg == WM_SYSKEYUP) && wParam == 0x12) altPressed = (msg == WM_SYSKEYDOWN);
if (altPressed) ev.modifierState |= ModifierState.alt; else ev.modifierState &= ~ModifierState.alt;
if(GetKeyState(Key.Ctrl)&0x8000 || GetKeyState(Key.Ctrl_r)&0x8000)
ev.modifierState |= ModifierState.ctrl;
if(GetKeyState(Key.Windows)&0x8000 || GetKeyState(Key.Windows_r)&0x8000)
ev.modifierState |= ModifierState.windows;
if(GetKeyState(Key.NumLock))
ev.modifierState |= ModifierState.numLock;
if(GetKeyState(Key.CapsLock))
ev.modifierState |= ModifierState.capsLock;
/+
// we always want to send the character too, so let's convert it
ubyte[256] state;
wchar[16] buffer;
GetKeyboardState(state.ptr);
ToUnicodeEx(wParam, lParam, state.ptr, buffer.ptr, buffer.length, 0, null);
foreach(dchar d; buffer) {
ev.character = d;
break;
}
+/
ev.window = wind;
if(wind.handleKeyEvent)
wind.handleKeyEvent(ev);
break;
case 0x020a /*WM_MOUSEWHEEL*/:
mouse.type = cast(MouseEventType) 1;
mouse.button = ((HIWORD(wParam) > 120) ? MouseButton.wheelDown : MouseButton.wheelUp);
mouseEvent();
break;
case WM_MOUSEMOVE:
mouse.type = cast(MouseEventType) 0;
mouseEvent();
break;
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
mouse.type = cast(MouseEventType) 1;
mouse.button = MouseButton.left;
mouse.doubleClick = msg == WM_LBUTTONDBLCLK;
mouseEvent();
break;
case WM_LBUTTONUP:
mouse.type = cast(MouseEventType) 2;
mouse.button = MouseButton.left;
mouseEvent();
break;
case WM_RBUTTONDOWN:
case WM_RBUTTONDBLCLK:
mouse.type = cast(MouseEventType) 1;
mouse.button = MouseButton.right;
mouse.doubleClick = msg == WM_RBUTTONDBLCLK;
mouseEvent();
break;
case WM_RBUTTONUP:
mouse.type = cast(MouseEventType) 2;
mouse.button = MouseButton.right;
mouseEvent();
break;
case WM_MBUTTONDOWN:
case WM_MBUTTONDBLCLK:
mouse.type = cast(MouseEventType) 1;
mouse.button = MouseButton.middle;
mouse.doubleClick = msg == WM_MBUTTONDBLCLK;
mouseEvent();
break;
case WM_MBUTTONUP:
mouse.type = cast(MouseEventType) 2;
mouse.button = MouseButton.middle;
mouseEvent();
break;
case WM_XBUTTONDOWN:
case WM_XBUTTONDBLCLK:
mouse.type = cast(MouseEventType) 1;
mouse.button = HIWORD(wParam) == 1 ? MouseButton.backButton : MouseButton.forwardButton;
mouse.doubleClick = msg == WM_XBUTTONDBLCLK;
mouseEvent();
return 1; // MSDN says special treatment here, return TRUE to bypass simulation programs
case WM_XBUTTONUP:
mouse.type = cast(MouseEventType) 2;
mouse.button = HIWORD(wParam) == 1 ? MouseButton.backButton : MouseButton.forwardButton;
mouseEvent();
return 1; // see: https://msdn.microsoft.com/en-us/library/windows/desktop/ms646246(v=vs.85).aspx
default: return 1;
}
return 0;
}
HWND hwnd;
int oldWidth;
int oldHeight;
bool inSizeMove;
// the extern(Windows) wndproc should just forward to this
LRESULT windowProcedure(HWND hwnd, uint msg, WPARAM wParam, LPARAM lParam) {
assert(hwnd is this.hwnd);
if(triggerEvents(hwnd, msg, wParam, lParam, 0, 0, this))
switch(msg) {
case WM_SETCURSOR:
if(cast(HWND) wParam !is hwnd)
return 0; // further processing elsewhere
if(LOWORD(lParam) == HTCLIENT && (this.curHidden > 0 || currentCursor !is null)) {
SetCursor(this.curHidden > 0 ? null : currentCursor);
return 1;
} else {
return DefWindowProc(hwnd, msg, wParam, lParam);
}
//break;
case WM_CLOSE:
if (this.closeQuery !is null) this.closeQuery(); else this.close();
break;
case WM_DESTROY:
if (this.onDestroyed !is null) try { this.onDestroyed(); } catch (Exception e) {} // sorry
SimpleWindow.nativeMapping.remove(hwnd);
CapableOfHandlingNativeEvent.nativeHandleMapping.remove(hwnd);
bool anyImportant = false;
foreach(SimpleWindow w; SimpleWindow.nativeMapping)
if(w.beingOpenKeepsAppOpen) {
anyImportant = true;
break;
}
if(!anyImportant) {
PostQuitMessage(0);
}
break;
case WM_SIZE:
if(wParam == 1 /* SIZE_MINIMIZED */)
break;
_width = LOWORD(lParam);
_height = HIWORD(lParam);
// I want to avoid tearing in the windows (my code is inefficient
// so this is a hack around that) so while sizing, we don't trigger,
// but we do want to trigger on events like mazimize.
if(!inSizeMove)
goto size_changed;
break;
// I don't like the tearing I get when redrawing on WM_SIZE
// (I know there's other ways to fix that but I don't like that behavior anyway)
// so instead it is going to redraw only at the end of a size.
case 0x0231: /* WM_ENTERSIZEMOVE */
oldWidth = this.width;
oldHeight = this.height;
inSizeMove = true;
break;
case 0x0232: /* WM_EXITSIZEMOVE */
inSizeMove = false;
// nothing relevant changed, don't bother redrawing
if(oldWidth == width && oldHeight == height)
break;
size_changed:
// note: OpenGL windows don't use a backing bmp, so no need to change them
// if resizability is anything other than allowResizing, it is meant to either stretch the one image or just do nothing
if(openglMode == OpenGlOptions.no) { // && resizability == Resizability.allowResizing) {
// gotta get the double buffer bmp to match the window
// FIXME: could this be more efficient? It isn't really necessary to make
// a new buffer if we're sizing down at least.
auto hdc = GetDC(hwnd);
auto oldBuffer = buffer;
buffer = CreateCompatibleBitmap(hdc, width, height);
auto hdcBmp = CreateCompatibleDC(hdc);
auto oldBmp = SelectObject(hdcBmp, buffer);
auto hdcOldBmp = CreateCompatibleDC(hdc);
auto oldOldBmp = SelectObject(hdcOldBmp, oldBmp);
BitBlt(hdcBmp, 0, 0, width, height, hdcOldBmp, oldWidth, oldHeight, SRCCOPY);
SelectObject(hdcOldBmp, oldOldBmp);
DeleteDC(hdcOldBmp);
SelectObject(hdcBmp, oldBmp);
DeleteDC(hdcBmp);
ReleaseDC(hwnd, hdc);
DeleteObject(oldBuffer);
}
version(without_opengl) {} else
if(openglMode == OpenGlOptions.yes && resizability == Resizability.automaticallyScaleIfPossible) {
glViewport(0, 0, width, height);
}
if(windowResized !is null)
windowResized(width, height);
break;
case WM_ERASEBKGND:
// call `visibleForTheFirstTime` here, so we can do initialization as early as possible
if (!this._visibleForTheFirstTimeCalled) {
this._visibleForTheFirstTimeCalled = true;
if (this.visibleForTheFirstTime !is null) {
version(without_opengl) {} else {
if(openglMode == OpenGlOptions.yes) {
this.setAsCurrentOpenGlContextNT();
glViewport(0, 0, width, height);
}
}
this.visibleForTheFirstTime();
}
}
// block it in OpenGL mode, 'cause no sane person will (or should) draw windows controls over OpenGL scene
version(without_opengl) {} else {
if (openglMode == OpenGlOptions.yes) return 1;
}
// call windows default handler, so it can paint standard controls
goto default;
case WM_CTLCOLORBTN:
case WM_CTLCOLORSTATIC:
SetBkMode(cast(HDC) wParam, TRANSPARENT);
return cast(typeof(return)) //GetStockObject(NULL_BRUSH);
GetSysColorBrush(COLOR_3DFACE);
//break;
case WM_SHOWWINDOW:
this._visible = (wParam != 0);
if (!this._visibleForTheFirstTimeCalled && this._visible) {
this._visibleForTheFirstTimeCalled = true;
if (this.visibleForTheFirstTime !is null) {
version(without_opengl) {} else {
if(openglMode == OpenGlOptions.yes) {
this.setAsCurrentOpenGlContextNT();
glViewport(0, 0, width, height);
}
}
this.visibleForTheFirstTime();
}
}
if (this.visibilityChanged !is null) this.visibilityChanged(this._visible);
break;
case WM_PAINT: {
if (!this._visibleForTheFirstTimeCalled) {
this._visibleForTheFirstTimeCalled = true;
if (this.visibleForTheFirstTime !is null) {
version(without_opengl) {} else {
if(openglMode == OpenGlOptions.yes) {
this.setAsCurrentOpenGlContextNT();
glViewport(0, 0, width, height);
}
}
this.visibleForTheFirstTime();
}
}
BITMAP bm;
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
if(openglMode == OpenGlOptions.no) {
HDC hdcMem = CreateCompatibleDC(hdc);
HBITMAP hbmOld = SelectObject(hdcMem, buffer);
GetObject(buffer, bm.sizeof, &bm);
// FIXME: only BitBlt the invalidated rectangle, not the whole thing
if(resizability == Resizability.automaticallyScaleIfPossible)
StretchBlt(hdc, 0, 0, this.width, this.height, hdcMem, 0, 0, bm.bmWidth, bm.bmHeight, SRCCOPY);
else
BitBlt(hdc, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem, 0, 0, SRCCOPY);
SelectObject(hdcMem, hbmOld);
DeleteDC(hdcMem);
EndPaint(hwnd, &ps);
} else {
EndPaint(hwnd, &ps);
version(without_opengl) {} else
redrawOpenGlSceneNow();
}
} break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
}
mixin template NativeImageImplementation() {
HBITMAP handle;
ubyte* rawData;
final:
Color getPixel(int x, int y) {
auto itemsPerLine = ((cast(int) width * 3 + 3) / 4) * 4;
// remember, bmps are upside down
auto offset = itemsPerLine * (height - y - 1) + x * 3;
Color c;
c.a = 255;
c.b = rawData[offset + 0];
c.g = rawData[offset + 1];
c.r = rawData[offset + 2];
return c;
}
void setPixel(int x, int y, Color c) {
auto itemsPerLine = ((cast(int) width * 3 + 3) / 4) * 4;
// remember, bmps are upside down
auto offset = itemsPerLine * (height - y - 1) + x * 3;
rawData[offset + 0] = c.b;
rawData[offset + 1] = c.g;
rawData[offset + 2] = c.r;
}
void convertToRgbaBytes(ubyte[] where) {
assert(where.length == this.width * this.height * 4);
auto itemsPerLine = ((cast(int) width * 3 + 3) / 4) * 4;
int idx = 0;
int offset = itemsPerLine * (height - 1);
// remember, bmps are upside down
for(int y = height - 1; y >= 0; y--) {
auto offsetStart = offset;
for(int x = 0; x < width; x++) {
where[idx + 0] = rawData[offset + 2]; // r
where[idx + 1] = rawData[offset + 1]; // g
where[idx + 2] = rawData[offset + 0]; // b
where[idx + 3] = 255; // a
idx += 4;
offset += 3;
}
offset = offsetStart - itemsPerLine;
}
}
void setFromRgbaBytes(in ubyte[] what) {
assert(what.length == this.width * this.height * 4);
auto itemsPerLine = ((cast(int) width * 3 + 3) / 4) * 4;
int idx = 0;
int offset = itemsPerLine * (height - 1);
// remember, bmps are upside down
for(int y = height - 1; y >= 0; y--) {
auto offsetStart = offset;
for(int x = 0; x < width; x++) {
rawData[offset + 2] = what[idx + 0]; // r
rawData[offset + 1] = what[idx + 1]; // g
rawData[offset + 0] = what[idx + 2]; // b
//where[idx + 3] = 255; // a
idx += 4;
offset += 3;
}
offset = offsetStart - itemsPerLine;
}
}
void createImage(int width, int height, bool forcexshm=false) {
BITMAPINFO infoheader;
infoheader.bmiHeader.biSize = infoheader.bmiHeader.sizeof;
infoheader.bmiHeader.biWidth = width;
infoheader.bmiHeader.biHeight = height;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biBitCount = 24;
infoheader.bmiHeader.biCompression = BI_RGB;
handle = CreateDIBSection(
null,
&infoheader,
DIB_RGB_COLORS,
cast(void**) &rawData,
null,
0);
if(handle is null)
throw new WindowsApiException("create image failed");
}
void dispose() {
DeleteObject(handle);
}
}
enum KEY_ESCAPE = 27;
}
version(X11) {
/// This is the default font used. You might change this before doing anything else with
/// the library if you want to try something else. Surround that in `static if(UsingSimpledisplayX11)`
/// for cross-platform compatibility.
//__gshared string xfontstr = "-*-dejavu sans-medium-r-*-*-12-*-*-*-*-*-*-*";
//__gshared string xfontstr = "-*-dejavu sans-medium-r-*-*-12-*-*-*-*-*-*-*";
__gshared string xfontstr = "-*-lucida-medium-r-normal-sans-12-*-*-*-*-*-*-*";
//__gshared string xfontstr = "-*-fixed-medium-r-*-*-14-*-*-*-*-*-*-*";
alias int delegate(XEvent) NativeEventHandler;
alias Window NativeWindowHandle;
enum KEY_ESCAPE = 9;
mixin template NativeScreenPainterImplementation() {
Display* display;
Drawable d;
Drawable destiny;
// FIXME: should the gc be static too so it isn't recreated every time draw is called?
GC gc;
__gshared bool fontAttempted;
__gshared XFontStruct* defaultfont;
__gshared XFontSet defaultfontset;
XFontStruct* font;
XFontSet fontset;
void create(NativeWindowHandle window) {
this.display = XDisplayConnection.get();
Drawable buffer = None;
if(auto sw = cast(SimpleWindow) this.window) {
buffer = sw.impl.buffer;
this.destiny = cast(Drawable) window;
} else {
buffer = cast(Drawable) window;
this.destiny = None;
}
this.d = cast(Drawable) buffer;
auto dgc = DefaultGC(display, DefaultScreen(display));
this.gc = XCreateGC(display, d, 0, null);
XCopyGC(display, dgc, 0xffffffff, this.gc);
if(!fontAttempted) {
font = XLoadQueryFont(display, xfontstr.ptr);
// if the user font choice fails, fixed is pretty reliable (required by X to start!) and not bad either
if(font is null)
font = XLoadQueryFont(display, "-*-fixed-medium-r-*-*-13-*-*-*-*-*-*-*".ptr);
char** lol;
int lol2;
char* lol3;
fontset = XCreateFontSet(display, xfontstr.ptr, &lol, &lol2, &lol3);
fontAttempted = true;
defaultfont = font;
defaultfontset = fontset;
}
font = defaultfont;
fontset = defaultfontset;
if(font) {
XSetFont(display, gc, font.fid);
}
}
arsd.color.Rectangle _clipRectangle;
void setClipRectangle(int x, int y, int width, int height) {
_clipRectangle = arsd.color.Rectangle(Point(x, y), Size(width, height));
if(width == 0 || height == 0)
XSetClipMask(display, gc, None);
else {
XRectangle[1] rects;
rects[0] = XRectangle(cast(short)(x), cast(short)(y), cast(short) width, cast(short) height);
XSetClipRectangles(XDisplayConnection.get, gc, 0, 0, rects.ptr, 1, 0);
}
}
void setFont(OperatingSystemFont font) {
if(font && font.font) {
this.font = font.font;
this.fontset = font.fontset;
XSetFont(display, gc, font.font.fid);
} else {
this.font = defaultfont;
this.fontset = defaultfontset;
}
}
void dispose() {
this.rasterOp = RasterOp.normal;
// FIXME: this.window.width/height is probably wrong
// src x,y then dest x, y
if(destiny != None) {
XSetClipMask(display, gc, None);
XCopyArea(display, d, destiny, gc, 0, 0, this.window.width, this.window.height, 0, 0);
}
XFreeGC(display, gc);
version(none) // we don't want to free it because we can use it later
if(font)
XFreeFont(display, font);
version(none) // we don't want to free it because we can use it later
if(fontset)
XFreeFontSet(display, fontset);
XFlush(display);
if(window.paintingFinishedDg !is null)
window.paintingFinishedDg();
}
bool backgroundIsNotTransparent = true;
bool foregroundIsNotTransparent = true;
bool _penInitialized = false;
Pen _activePen;
Color _outlineColor;
Color _fillColor;
@property void pen(Pen p) {
if(_penInitialized && p == _activePen) {
return;
}
_penInitialized = true;
_activePen = p;
_outlineColor = p.color;
int style;
byte dashLength;
final switch(p.style) {
case Pen.Style.Solid:
style = 0 /*LineSolid*/;
break;
case Pen.Style.Dashed:
style = 1 /*LineOnOffDash*/;
dashLength = 4;
break;
case Pen.Style.Dotted:
style = 1 /*LineOnOffDash*/;
dashLength = 1;
break;
}
XSetLineAttributes(display, gc, p.width, style, 0, 0);
if(dashLength)
XSetDashes(display, gc, 0, &dashLength, 1);
if(p.color.a == 0) {
foregroundIsNotTransparent = false;
return;
}
foregroundIsNotTransparent = true;
XSetForeground(display, gc, colorToX(p.color, display));
}
RasterOp _currentRasterOp;
bool _currentRasterOpInitialized = false;
@property void rasterOp(RasterOp op) {
if(_currentRasterOpInitialized && _currentRasterOp == op)
return;
_currentRasterOp = op;
_currentRasterOpInitialized = true;
int mode;
final switch(op) {
case RasterOp.normal:
mode = GXcopy;
break;
case RasterOp.xor:
mode = GXxor;
break;
}
XSetFunction(display, gc, mode);
}
bool _fillColorInitialized = false;
@property void fillColor(Color c) {
if(_fillColorInitialized && _fillColor == c)
return; // already good, no need to waste time calling it
_fillColor = c;
_fillColorInitialized = true;
if(c.a == 0) {
backgroundIsNotTransparent = false;
return;
}
backgroundIsNotTransparent = true;
XSetBackground(display, gc, colorToX(c, display));
}
void swapColors() {
auto tmp = _fillColor;
fillColor = _outlineColor;
auto newPen = _activePen;
newPen.color = tmp;
pen(newPen);
}
uint colorToX(Color c, Display* display) {
auto visual = DefaultVisual(display, DefaultScreen(display));
import core.bitop;
uint color = 0;
{
auto startBit = bsf(visual.red_mask);
auto lastBit = bsr(visual.red_mask);
auto r = cast(uint) c.r;
r >>= 7 - (lastBit - startBit);
r <<= startBit;
color |= r;
}
{
auto startBit = bsf(visual.green_mask);
auto lastBit = bsr(visual.green_mask);
auto g = cast(uint) c.g;
g >>= 7 - (lastBit - startBit);
g <<= startBit;
color |= g;
}
{
auto startBit = bsf(visual.blue_mask);
auto lastBit = bsr(visual.blue_mask);
auto b = cast(uint) c.b;
b >>= 7 - (lastBit - startBit);
b <<= startBit;
color |= b;
}
return color;
}
void drawImage(int x, int y, Image i, int ix, int iy, int w, int h) {
// source x, source y
if(i.usingXshm)
XShmPutImage(display, d, gc, i.handle, ix, iy, x, y, w, h, false);
else
XPutImage(display, d, gc, i.handle, ix, iy, x, y, w, h);
}
void drawPixmap(Sprite s, int x, int y) {
XCopyArea(display, s.handle, d, gc, 0, 0, s.width, s.height, x, y);
}
int fontHeight() {
if(font)
return font.max_bounds.ascent + font.max_bounds.descent;
return 12; // pretty common default...
}
Size textSize(in char[] text) {
auto maxWidth = 0;
auto lineHeight = fontHeight;
int h = text.length ? 0 : lineHeight + 4; // if text is empty, it still gives the line height
foreach(line; text.split('\n')) {
int textWidth;
if(font)
// FIXME: unicode
textWidth = XTextWidth( font, line.ptr, cast(int) line.length);
else
textWidth = fontHeight / 2 * cast(int) line.length; // if no font is loaded, it is prolly Fixed, which is a 2:1 ratio
if(textWidth > maxWidth)
maxWidth = textWidth;
h += lineHeight + 4;
}
return Size(maxWidth, h);
}
void drawText(in int x, in int y, in int x2, in int y2, in char[] originalText, in uint alignment) {
// FIXME: we should actually draw unicode.. but until then, I'm going to strip out multibyte chars
const(char)[] text;
if(fontset)
text = originalText;
else {
text.reserve(originalText.length);
// the first 256 unicode codepoints are the same as ascii and latin-1, which is what X expects, so we can keep all those
// then strip the rest so there isn't garbage
foreach(dchar ch; originalText)
if(ch < 256)
text ~= cast(ubyte) ch;
else
text ~= 191; // FIXME: using a random character to fill the space
}
if(text.length == 0)
return;
int textHeight = 12;
// FIXME: should we clip it to the bounding box?
if(font) {
textHeight = font.max_bounds.ascent + font.max_bounds.descent;
}
auto lines = text.split('\n');
auto lineHeight = textHeight;
textHeight *= lines.length;
int cy = y;
if(alignment & TextAlignment.VerticalBottom) {
assert(y2);
auto h = y2 - y;
if(h > textHeight) {
cy += h - textHeight;
cy -= lineHeight / 2;
}
} else if(alignment & TextAlignment.VerticalCenter) {
assert(y2);
auto h = y2 - y;
if(textHeight < h) {
cy += (h - textHeight) / 2;
//cy -= lineHeight / 4;
}
}
foreach(line; text.split('\n')) {
int textWidth;
if(font)
// FIXME: unicode
textWidth = XTextWidth( font, line.ptr, cast(int) line.length);
else
textWidth = 12 * cast(int) line.length;
int px = x, py = cy;
if(alignment & TextAlignment.Center) {
assert(x2);
auto w = x2 - x;
if(w > textWidth)
px += (w - textWidth) / 2;
} else if(alignment & TextAlignment.Right) {
assert(x2);
auto pos = x2 - textWidth;
if(pos > x)
px = pos;
}
if(fontset)
Xutf8DrawString(display, d, fontset, gc, px, py + (font ? font.max_bounds.ascent : lineHeight), line.ptr, cast(int) line.length);
else
XDrawString(display, d, gc, px, py + (font ? font.max_bounds.ascent : lineHeight), line.ptr, cast(int) line.length);
cy += lineHeight + 4;
}
}
void drawPixel(int x, int y) {
XDrawPoint(display, d, gc, x, y);
}
// The basic shapes, outlined
void drawLine(int x1, int y1, int x2, int y2) {
if(foregroundIsNotTransparent)
XDrawLine(display, d, gc, x1, y1, x2, y2);
}
void drawRectangle(int x, int y, int width, int height) {
if(backgroundIsNotTransparent) {
swapColors();
XFillRectangle(display, d, gc, x+1, y+1, width-2, height-2); // Need to ensure pixels are only drawn once...
swapColors();
}
if(foregroundIsNotTransparent)
XDrawRectangle(display, d, gc, x, y, width - 1, height - 1);
}
/// Arguments are the points of the bounding rectangle
void drawEllipse(int x1, int y1, int x2, int y2) {
drawArc(x1, y1, x2 - x1, y2 - y1, 0, 360 * 64);
}
// NOTE: start and finish are in units of degrees * 64
void drawArc(int x1, int y1, int width, int height, int start, int finish) {
if(backgroundIsNotTransparent) {
swapColors();
XFillArc(display, d, gc, x1, y1, width, height, start, finish);
swapColors();
}
if(foregroundIsNotTransparent)
XDrawArc(display, d, gc, x1, y1, width, height, start, finish);
}
void drawPolygon(Point[] vertexes) {
XPoint[16] pointsBuffer;
XPoint[] points;
if(vertexes.length <= pointsBuffer.length)
points = pointsBuffer[0 .. vertexes.length];
else
points.length = vertexes.length;
foreach(i, p; vertexes) {
points[i].x = cast(short) p.x;
points[i].y = cast(short) p.y;
}
if(backgroundIsNotTransparent) {
swapColors();
XFillPolygon(display, d, gc, points.ptr, cast(int) points.length, PolygonShape.Complex, CoordMode.CoordModeOrigin);
swapColors();
}
if(foregroundIsNotTransparent) {
XDrawLines(display, d, gc, points.ptr, cast(int) points.length, CoordMode.CoordModeOrigin);
}
}
}
class XDisconnectException : Exception {
bool userRequested;
this(bool userRequested = true) {
this.userRequested = userRequested;
super("X disconnected");
}
}
/// Platform-specific for X11. A singleton class (well, all its methods are actually static... so more like a namespace) wrapping a Display*
class XDisplayConnection {
private __gshared Display* display;
private __gshared XIM xim;
private __gshared char* displayName;
private __gshared int connectionSequence_;
/// use this for lazy caching when reconnection
static int connectionSequenceNumber() { return connectionSequence_; }
/// Attempts recreation of state, may require application assistance
/// You MUST call this OUTSIDE the event loop. Let the exception kill the loop,
/// then call this, and if successful, reenter the loop.
static void discardAndRecreate(string newDisplayString = null) {
if(insideXEventLoop)
throw new Error("You MUST call discardAndRecreate from OUTSIDE the event loop");
// auto swnm = SimpleWindow.nativeMapping.dup; // this SHOULD be unnecessary because all simple windows are capable of handling native events, so the latter ought to do it all
auto chnenhm = CapableOfHandlingNativeEvent.nativeHandleMapping.dup;
foreach(handle; chnenhm) {
handle.discardConnectionState();
}
discardState();
if(newDisplayString !is null)
setDisplayName(newDisplayString);
auto display = get();
foreach(handle; chnenhm) {
handle.recreateAfterDisconnect();
}
}
private __gshared EventMask rootEventMask;
/++
Requests the specified input from the root window on the connection, in addition to any other request.
Since plain XSelectInput will replace the existing mask, adding input from multiple locations is tricky. This central function will combine all the masks for you.
$(WARNING it calls XSelectInput itself, which will override any other root window input you have!)
+/
static void addRootInput(EventMask mask) {
auto old = rootEventMask;
rootEventMask |= mask;
get(); // to ensure display connected
if(display !is null && rootEventMask != old)
XSelectInput(display, RootWindow(display, DefaultScreen(display)), rootEventMask);
}
static void discardState() {
freeImages();
foreach(atomPtr; interredAtoms)
*atomPtr = 0;
interredAtoms = null;
interredAtoms.assumeSafeAppend();
ScreenPainterImplementation.fontAttempted = false;
ScreenPainterImplementation.defaultfont = null;
ScreenPainterImplementation.defaultfontset = null;
Image.impl.xshmQueryCompleted = false;
Image.impl._xshmAvailable = false;
SimpleWindow.nativeMapping = null;
CapableOfHandlingNativeEvent.nativeHandleMapping = null;
// GlobalHotkeyManager
display = null;
xim = null;
}
// Do you want to know why do we need all this horrible-looking code? See comment at the bottom.
private static void createXIM () {
import core.stdc.locale : setlocale, LC_ALL;
import core.stdc.stdio : stderr, fprintf;
import core.stdc.stdlib : free;
import core.stdc.string : strdup;
static immutable string[3] mtry = [ null, "@im=local", "@im=" ];
auto olocale = strdup(setlocale(LC_ALL, null));
setlocale(LC_ALL, (sdx_isUTF8Locale ? "" : "en_US.UTF-8"));
scope(exit) { setlocale(LC_ALL, olocale); free(olocale); }
//fprintf(stderr, "opening IM...\n");
foreach (string s; mtry) {
if (s.length) XSetLocaleModifiers(s.ptr); // it's safe, as `s` is string literal
if ((xim = XOpenIM(display, null, null, null)) !is null) return;
}
fprintf(stderr, "createXIM: XOpenIM failed!\n");
}
// for X11 we will keep all XShm-allocated images in this list, so we can free 'em on connection closing.
// we'll use glibc malloc()/free(), 'cause `unregisterImage()` can be called from object dtor.
static struct ImgList {
size_t img; // class; hide it from GC
ImgList* next;
}
static __gshared ImgList* imglist = null;
static __gshared bool imglistLocked = false; // true: don't register and unregister images
static void registerImage (Image img) {
if (!imglistLocked && img !is null) {
import core.stdc.stdlib : malloc;
auto it = cast(ImgList*)malloc(ImgList.sizeof);
assert(it !is null); // do proper checks
it.img = cast(size_t)cast(void*)img;
it.next = imglist;
imglist = it;
version(sdpy_debug_xshm) { import core.stdc.stdio : printf; printf("registering image %p\n", cast(void*)img); }
}
}
static void unregisterImage (Image img) {
if (!imglistLocked && img !is null) {
import core.stdc.stdlib : free;
ImgList* prev = null;
ImgList* cur = imglist;
while (cur !is null) {
if (cur.img == cast(size_t)cast(void*)img) break; // i found her!
prev = cur;
cur = cur.next;
}
if (cur !is null) {
if (prev is null) imglist = cur.next; else prev.next = cur.next;
free(cur);
version(sdpy_debug_xshm) { import core.stdc.stdio : printf; printf("unregistering image %p\n", cast(void*)img); }
} else {
version(sdpy_debug_xshm) { import core.stdc.stdio : printf; printf("trying to unregister unknown image %p\n", cast(void*)img); }
}
}
}
static void freeImages () { // needed for discardAndRecreate
imglistLocked = true;
scope(exit) imglistLocked = false;
ImgList* cur = imglist;
ImgList* next = null;
while (cur !is null) {
import core.stdc.stdlib : free;
next = cur.next;
version(sdpy_debug_xshm) { import core.stdc.stdio : printf; printf("disposing image %p\n", cast(void*)cur.img); }
(cast(Image)cast(void*)cur.img).dispose();
free(cur);
cur = next;
}
imglist = null;
}
/// can be used to override normal handling of display name
/// from environment and/or command line
static setDisplayName(string newDisplayName) {
displayName = cast(char*) (newDisplayName ~ '\0');
}
/// resets to the default display string
static resetDisplayName() {
displayName = null;
}
///
static Display* get() {
if(display is null) {
display = XOpenDisplay(displayName);
connectionSequence_++;
if(display is null)
throw new Exception("Unable to open X display");
XSetIOErrorHandler(&x11ioerrCB);
Bool sup;
XkbSetDetectableAutoRepeat(display, 1, &sup); // so we will not receive KeyRelease until key is really released
createXIM();
version(with_eventloop) {
import arsd.eventloop;
addFileEventListeners(display.fd, &eventListener, null, null);
}
}
return display;
}
extern(C)
static int x11ioerrCB(Display* dpy) {
throw new XDisconnectException(false);
}
version(with_eventloop) {
import arsd.eventloop;
static void eventListener(OsFileHandle fd) {
//this.mtLock();
//scope(exit) this.mtUnlock();
while(XPending(display))
doXNextEvent(display);
}
}
// close connection on program exit -- we need this to properly free all images
shared static ~this () { close(); }
///
static void close() {
if(display is null)
return;
version(with_eventloop) {
import arsd.eventloop;
removeFileEventListeners(display.fd);
}
// now remove all registered images to prevent shared memory leaks
freeImages();
XCloseDisplay(display);
display = null;
}
}
mixin template NativeImageImplementation() {
XImage* handle;
ubyte* rawData;
XShmSegmentInfo shminfo;
__gshared bool xshmQueryCompleted;
__gshared bool _xshmAvailable;
public static @property bool xshmAvailable() {
if(!xshmQueryCompleted) {
int i1, i2, i3;
xshmQueryCompleted = true;
_xshmAvailable = XQueryExtension(XDisplayConnection.get(), "MIT-SHM", &i1, &i2, &i3) != 0;
}
return _xshmAvailable;
}
bool usingXshm;
final:
void createImage(int width, int height, bool forcexshm=false) {
auto display = XDisplayConnection.get();
assert(display !is null);
auto screen = DefaultScreen(display);
// it will only use shared memory for somewhat largish images,
// since otherwise we risk wasting shared memory handles on a lot of little ones
if (xshmAvailable && (forcexshm || (width > 100 && height > 100))) {
usingXshm = true;
handle = XShmCreateImage(
display,
DefaultVisual(display, screen),
24,
ImageFormat.ZPixmap,
null,
&shminfo,
width, height);
assert(handle !is null);
assert(handle.bytes_per_line == 4 * width);
shminfo.shmid = shmget(IPC_PRIVATE, handle.bytes_per_line * height, IPC_CREAT | 511 /* 0777 */);
//import std.conv; import core.stdc.errno;
assert(shminfo.shmid >= 0);//, to!string(errno));
handle.data = shminfo.shmaddr = rawData = cast(ubyte*) shmat(shminfo.shmid, null, 0);
assert(rawData != cast(ubyte*) -1);
shminfo.readOnly = 0;
XShmAttach(display, &shminfo);
XDisplayConnection.registerImage(this);
} else {
if (forcexshm) throw new Exception("can't create XShm Image");
// This actually needs to be malloc to avoid a double free error when XDestroyImage is called
import core.stdc.stdlib : malloc;
rawData = cast(ubyte*) malloc(width * height * 4);
handle = XCreateImage(
display,
DefaultVisual(display, screen),
24, // bpp
ImageFormat.ZPixmap,
0, // offset
rawData,
width, height,
8 /* FIXME */, 4 * width); // padding, bytes per line
}
}
void dispose() {
// note: this calls free(rawData) for us
if(handle) {
if (usingXshm) {
XDisplayConnection.unregisterImage(this);
if (XDisplayConnection.get()) XShmDetach(XDisplayConnection.get(), &shminfo);
}
XDestroyImage(handle);
if(usingXshm) {
shmdt(shminfo.shmaddr);
shmctl(shminfo.shmid, IPC_RMID, null);
}
handle = null;
}
}
Color getPixel(int x, int y) {
auto offset = (y * width + x) * 4;
Color c;
c.a = 255;
c.b = rawData[offset + 0];
c.g = rawData[offset + 1];
c.r = rawData[offset + 2];
return c;
}
void setPixel(int x, int y, Color c) {
auto offset = (y * width + x) * 4;
rawData[offset + 0] = c.b;
rawData[offset + 1] = c.g;
rawData[offset + 2] = c.r;
}
void convertToRgbaBytes(ubyte[] where) {
assert(where.length == this.width * this.height * 4);
// if rawData had a length....
//assert(rawData.length == where.length);
for(int idx = 0; idx < where.length; idx += 4) {
where[idx + 0] = rawData[idx + 2]; // r
where[idx + 1] = rawData[idx + 1]; // g
where[idx + 2] = rawData[idx + 0]; // b
where[idx + 3] = 255; // a
}
}
void setFromRgbaBytes(in ubyte[] where) {
assert(where.length == this.width * this.height * 4);
// if rawData had a length....
//assert(rawData.length == where.length);
for(int idx = 0; idx < where.length; idx += 4) {
rawData[idx + 2] = where[idx + 0]; // r
rawData[idx + 1] = where[idx + 1]; // g
rawData[idx + 0] = where[idx + 2]; // b
//rawData[idx + 3] = 255; // a
}
}
}
mixin template NativeSimpleWindowImplementation() {
GC gc;
Window window;
Display* display;
Pixmap buffer;
int bufferw, bufferh; // size of the buffer; can be bigger than window
XIC xic; // input context
int curHidden = 0; // counter
Cursor blankCurPtr = 0;
int cursorSequenceNumber = 0;
int warpEventCount = 0; // number of mouse movement events to eat
void delegate(XEvent) setSelectionHandler;
void delegate(in char[]) getSelectionHandler;
version(without_opengl) {} else
GLXContext glc;
private void fixFixedSize(bool forced=false) (int width, int height) {
if (forced || this.resizability == Resizability.fixedSize) {
//{ import core.stdc.stdio; printf("fixing size to: %dx%d\n", width, height); }
XSizeHints sh;
static if (!forced) {
c_long spr;
XGetWMNormalHints(display, window, &sh, &spr);
sh.flags |= PMaxSize | PMinSize;
} else {
sh.flags = PMaxSize | PMinSize;
}
sh.min_width = width;
sh.min_height = height;
sh.max_width = width;
sh.max_height = height;
XSetWMNormalHints(display, window, &sh);
//XFlush(display);
}
}
ScreenPainter getPainter() {
return ScreenPainter(this, window);
}
void move(int x, int y) {
XMoveWindow(display, window, x, y);
}
void resize(int w, int h) {
if (w < 1) w = 1;
if (h < 1) h = 1;
XResizeWindow(display, window, w, h);
// FIXME: do we need to set this as the opengl context to do the glViewport change?
version(without_opengl) {} else if (openglMode == OpenGlOptions.yes) glViewport(0, 0, w, h);
}
void moveResize (int x, int y, int w, int h) {
if (w < 1) w = 1;
if (h < 1) h = 1;
XMoveResizeWindow(display, window, x, y, w, h);
version(without_opengl) {} else if (openglMode == OpenGlOptions.yes) glViewport(0, 0, w, h);
}
void hideCursor () {
if (curHidden++ == 0) {
if (!blankCurPtr || cursorSequenceNumber != XDisplayConnection.connectionSequenceNumber) {
static const(char)[1] cmbmp = 0;
XColor blackcolor = { 0, 0, 0, 0, 0, 0 };
Pixmap pm = XCreateBitmapFromData(display, window, cmbmp.ptr, 1, 1);
blankCurPtr = XCreatePixmapCursor(display, pm, pm, &blackcolor, &blackcolor, 0, 0);
cursorSequenceNumber = XDisplayConnection.connectionSequenceNumber;
XFreePixmap(display, pm);
}
XDefineCursor(display, window, blankCurPtr);
}
}
void showCursor () {
if (--curHidden == 0) XUndefineCursor(display, window);
}
void warpMouse (int x, int y) {
// here i will send dummy "ignore next mouse motion" event,
// 'cause `XWarpPointer()` sends synthesised mouse motion,
// and we don't need to report it to the user (as warping is
// used when the user needs movement deltas).
//XClientMessageEvent xclient;
XEvent e;
e.xclient.type = EventType.ClientMessage;
e.xclient.window = window;
e.xclient.message_type = GetAtom!("_X11SDPY_INSMME_FLAG_EVENT_", true)(display); // let's hope nobody else will use such stupid name ;-)
e.xclient.format = 32;
e.xclient.data.l[0] = 0;
debug(x11sdpy_warp_debug) { import core.stdc.stdio : printf; printf("X11: sending \"INSMME\"...\n"); }
//{ import core.stdc.stdio : printf; printf("*X11 CLIENT: w=%u; type=%u; [0]=%u\n", cast(uint)e.xclient.window, cast(uint)e.xclient.message_type, cast(uint)e.xclient.data.l[0]); }
XSendEvent(display, window, false, EventMask.NoEventMask, /*cast(XEvent*)&xclient*/&e);
// now warp pointer...
debug(x11sdpy_warp_debug) { import core.stdc.stdio : printf; printf("X11: sending \"warp\"...\n"); }
XWarpPointer(display, None, window, 0, 0, 0, 0, x, y);
// ...and flush
debug(x11sdpy_warp_debug) { import core.stdc.stdio : printf; printf("X11: flushing...\n"); }
XFlush(display);
}
void sendDummyEvent () {
// here i will send dummy event to ping event queue
XEvent e;
e.xclient.type = EventType.ClientMessage;
e.xclient.window = window;
e.xclient.message_type = GetAtom!("_X11SDPY_DUMMY_EVENT_", true)(display); // let's hope nobody else will use such stupid name ;-)
e.xclient.format = 32;
e.xclient.data.l[0] = 0;
XSendEvent(display, window, false, EventMask.NoEventMask, /*cast(XEvent*)&xclient*/&e);
XFlush(display);
}
void setTitle(string title) {
if (title.ptr is null) title = "";
auto XA_UTF8 = XInternAtom(display, "UTF8_STRING".ptr, false);
auto XA_NETWM_NAME = XInternAtom(display, "_NET_WM_NAME".ptr, false);
XTextProperty windowName;
windowName.value = title.ptr;
windowName.encoding = XA_UTF8; //XA_STRING;
windowName.format = 8;
windowName.nitems = cast(uint)title.length;
XSetWMName(display, window, &windowName);
char[1024] namebuf = 0;
auto maxlen = namebuf.length-1;
if (maxlen > title.length) maxlen = title.length;
namebuf[0..maxlen] = title[0..maxlen];
XStoreName(display, window, namebuf.ptr);
XChangeProperty(display, window, XA_NETWM_NAME, XA_UTF8, 8, PropModeReplace, title.ptr, cast(uint)title.length);
flushGui(); // without this OpenGL windows has a LONG delay before changing title
}
string[] getTitles() {
auto XA_UTF8 = XInternAtom(display, "UTF8_STRING".ptr, false);
auto XA_NETWM_NAME = XInternAtom(display, "_NET_WM_NAME".ptr, false);
XTextProperty textProp;
if (XGetTextProperty(display, window, &textProp, XA_NETWM_NAME) != 0 || XGetWMName(display, window, &textProp) != 0) {
if ((textProp.encoding == XA_UTF8 || textProp.encoding == XA_STRING) && textProp.format == 8) {
return textProp.value[0 .. textProp.nitems].idup.split('\0');
} else
return [];
} else
return null;
}
string getTitle() {
auto titles = getTitles();
return titles.length ? titles[0] : null;
}
void setMinSize (int minwidth, int minheight) {
import core.stdc.config : c_long;
if (minwidth < 1) minwidth = 1;
if (minheight < 1) minheight = 1;
XSizeHints sh;
c_long spr;
XGetWMNormalHints(display, window, &sh, &spr);
sh.min_width = minwidth;
sh.min_height = minheight;
sh.flags |= PMinSize;
XSetWMNormalHints(display, window, &sh);
flushGui();
}
void setMaxSize (int maxwidth, int maxheight) {
import core.stdc.config : c_long;
if (maxwidth < 1) maxwidth = 1;
if (maxheight < 1) maxheight = 1;
XSizeHints sh;
c_long spr;
XGetWMNormalHints(display, window, &sh, &spr);
sh.max_width = maxwidth;
sh.max_height = maxheight;
sh.flags |= PMaxSize;
XSetWMNormalHints(display, window, &sh);
flushGui();
}
void setResizeGranularity (int granx, int grany) {
import core.stdc.config : c_long;
if (granx < 1) granx = 1;
if (grany < 1) grany = 1;
XSizeHints sh;
c_long spr;
XGetWMNormalHints(display, window, &sh, &spr);
sh.width_inc = granx;
sh.height_inc = grany;
sh.flags |= PResizeInc;
XSetWMNormalHints(display, window, &sh);
flushGui();
}
void setOpacity (uint opacity) {
if (opacity == uint.max)
XDeleteProperty(display, window, XInternAtom(display, "_NET_WM_WINDOW_OPACITY".ptr, false));
else
XChangeProperty(display, window, XInternAtom(display, "_NET_WM_WINDOW_OPACITY".ptr, false),
XA_CARDINAL, 32, PropModeReplace, &opacity, 1);
}
void createWindow(int width, int height, string title, in OpenGlOptions opengl, SimpleWindow parent) {
display = XDisplayConnection.get();
auto screen = DefaultScreen(display);
version(without_opengl) {}
else {
if(opengl == OpenGlOptions.yes) {
GLXFBConfig fbconf = null;
XVisualInfo* vi = null;
bool useLegacy = false;
static if (SdpyIsUsingIVGLBinds) {if (glbindGetProcAddress("glHint") is null) assert(0, "GL: error loading OpenGL"); } // loads all necessary functions
if (sdpyOpenGLContextVersion != 0 && glXCreateContextAttribsARB_present()) {
int[23] visualAttribs = [
GLX_X_RENDERABLE , 1/*True*/,
GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
GLX_RENDER_TYPE , GLX_RGBA_BIT,
GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR,
GLX_RED_SIZE , 8,
GLX_GREEN_SIZE , 8,
GLX_BLUE_SIZE , 8,
GLX_ALPHA_SIZE , 8,
GLX_DEPTH_SIZE , 24,
GLX_STENCIL_SIZE , 8,
GLX_DOUBLEBUFFER , 1/*True*/,
0/*None*/,
];
int fbcount;
GLXFBConfig* fbc = glXChooseFBConfig(display, screen, visualAttribs.ptr, &fbcount);
if (fbcount == 0) {
useLegacy = true; // try to do at least something
} else {
// pick the FB config/visual with the most samples per pixel
int bestidx = -1, bestns = -1;
foreach (int fbi; 0..fbcount) {
int sb, samples;
glXGetFBConfigAttrib(display, fbc[fbi], GLX_SAMPLE_BUFFERS, &sb);
glXGetFBConfigAttrib(display, fbc[fbi], GLX_SAMPLES, &samples);
if (bestidx < 0 || sb && samples > bestns) { bestidx = fbi; bestns = samples; }
}
//{ import core.stdc.stdio; printf("found gl visual with %d samples\n", bestns); }
fbconf = fbc[bestidx];
// Be sure to free the FBConfig list allocated by glXChooseFBConfig()
XFree(fbc);
vi = cast(XVisualInfo*)glXGetVisualFromFBConfig(display, fbconf);
}
}
if (vi is null || useLegacy) {
static immutable GLint[5] attrs = [ GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None ];
vi = cast(XVisualInfo*)glXChooseVisual(display, 0, attrs.ptr);
useLegacy = true;
}
if (vi is null) throw new Exception("no open gl visual found");
XSetWindowAttributes swa;
auto root = RootWindow(display, screen);
swa.colormap = XCreateColormap(display, root, vi.visual, AllocNone);
window = XCreateWindow(display, parent is null ? root : parent.impl.window,
0, 0, width, height,
0, vi.depth, 1 /* InputOutput */, vi.visual, CWColormap, &swa);
// now try to use `glXCreateContextAttribsARB()` if it's here
if (!useLegacy) {
// request fairly advanced context, even with stencil buffer!
int[9] contextAttribs = [
GLX_CONTEXT_MAJOR_VERSION_ARB, (sdpyOpenGLContextVersion>>8),
GLX_CONTEXT_MINOR_VERSION_ARB, (sdpyOpenGLContextVersion&0xff),
/*GLX_CONTEXT_PROFILE_MASK_ARB*/0x9126, (sdpyOpenGLContextCompatible ? /*GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB*/0x02 : /*GLX_CONTEXT_CORE_PROFILE_BIT_ARB*/ 0x01),
// for modern context, set "forward compatibility" flag too
(sdpyOpenGLContextCompatible ? None : /*GLX_CONTEXT_FLAGS_ARB*/ 0x2094), /*GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB*/ 0x02,
0/*None*/,
];
glc = glXCreateContextAttribsARB(display, fbconf, null, 1/*True*/, contextAttribs.ptr);
if (glc is null && sdpyOpenGLContextAllowFallback) {
sdpyOpenGLContextVersion = 0;
glc = glXCreateContext(display, vi, null, /*GL_TRUE*/1);
}
//{ import core.stdc.stdio; printf("using modern ogl v%d.%d\n", contextAttribs[1], contextAttribs[3]); }
} else {
// fallback to old GLX call
if (sdpyOpenGLContextAllowFallback || sdpyOpenGLContextVersion == 0) {
sdpyOpenGLContextVersion = 0;
glc = glXCreateContext(display, vi, null, /*GL_TRUE*/1);
}
}
// sync to ensure any errors generated are processed
XSync(display, 0/*False*/);
//{ import core.stdc.stdio; printf("ogl is here\n"); }
if(glc is null)
throw new Exception("glc");
}
}
if(opengl == OpenGlOptions.no) {
bool overrideRedirect = false;
if(windowType == WindowTypes.dropdownMenu || windowType == WindowTypes.popupMenu || windowType == WindowTypes.notification)
overrideRedirect = true;
XSetWindowAttributes swa;
swa.background_pixel = WhitePixel(display, screen);
swa.border_pixel = BlackPixel(display, screen);
swa.override_redirect = overrideRedirect;
auto root = RootWindow(display, screen);
swa.colormap = XCreateColormap(display, root, DefaultVisual(display, screen), AllocNone);
window = XCreateWindow(display, parent is null ? root : parent.impl.window,
0, 0, width, height,
0, CopyFromParent, 1 /* InputOutput */, cast(Visual*) CopyFromParent, CWColormap | CWBackPixel | CWBorderPixel | CWOverrideRedirect, &swa);
/*
window = XCreateSimpleWindow(
display,
parent is null ? RootWindow(display, screen) : parent.impl.window,
0, 0, // x, y
width, height,
1, // border width
BlackPixel(display, screen), // border
WhitePixel(display, screen)); // background
*/
buffer = XCreatePixmap(display, cast(Drawable) window, width, height, DefaultDepthOfDisplay(display));
bufferw = width;
bufferh = height;
gc = DefaultGC(display, screen);
// clear out the buffer to get us started...
XSetForeground(display, gc, WhitePixel(display, screen));
XFillRectangle(display, cast(Drawable) buffer, gc, 0, 0, width, height);
XSetForeground(display, gc, BlackPixel(display, screen));
}
// input context
//TODO: create this only for top-level windows, and reuse that?
if (XDisplayConnection.xim !is null) {
xic = XCreateIC(XDisplayConnection.xim,
/*XNInputStyle*/"inputStyle".ptr, XIMPreeditNothing|XIMStatusNothing,
/*XNClientWindow*/"clientWindow".ptr, window,
/*XNFocusWindow*/"focusWindow".ptr, window,
null);
if (xic is null) {
import core.stdc.stdio : stderr, fprintf;
fprintf(stderr, "XCreateIC failed for window %u\n", cast(uint)window);
}
}
if (sdpyWindowClassStr is null) loadBinNameToWindowClassName();
if (sdpyWindowClassStr is null) sdpyWindowClass = "DSimpleWindow";
// window class
if (sdpyWindowClassStr !is null && sdpyWindowClassStr[0]) {
//{ import core.stdc.stdio; printf("winclass: [%s]\n", sdpyWindowClassStr); }
XClassHint klass;
XWMHints wh;
XSizeHints size;
klass.res_name = sdpyWindowClassStr;
klass.res_class = sdpyWindowClassStr;
XSetWMProperties(display, window, null, null, null, 0, &size, &wh, &klass);
}
setTitle(title);
SimpleWindow.nativeMapping[window] = this;
CapableOfHandlingNativeEvent.nativeHandleMapping[window] = this;
// This gives our window a close button
if (windowType != WindowTypes.eventOnly) {
Atom atom = XInternAtom(display, "WM_DELETE_WINDOW".ptr, true); // FIXME: does this need to be freed?
XSetWMProtocols(display, window, &atom, 1);
}
// FIXME: windowType and customizationFlags
Atom[8] wsatoms; // here, due to goto
int wmsacount = 0; // here, due to goto
try
final switch(windowType) {
case WindowTypes.normal:
setNetWMWindowType(GetAtom!"_NET_WM_WINDOW_TYPE_NORMAL"(display));
break;
case WindowTypes.undecorated:
motifHideDecorations();
setNetWMWindowType(GetAtom!"_NET_WM_WINDOW_TYPE_NORMAL"(display));
break;
case WindowTypes.eventOnly:
_hidden = true;
XSelectInput(display, window, EventMask.StructureNotifyMask); // without this, we won't get destroy notification
goto hiddenWindow;
//break;
case WindowTypes.nestedChild:
break;
case WindowTypes.dropdownMenu:
motifHideDecorations();
setNetWMWindowType(GetAtom!"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU"(display));
customizationFlags |= WindowFlags.skipTaskbar | WindowFlags.alwaysOnTop;
break;
case WindowTypes.popupMenu:
motifHideDecorations();
setNetWMWindowType(GetAtom!"_NET_WM_WINDOW_TYPE_POPUP_MENU"(display));
customizationFlags |= WindowFlags.skipTaskbar | WindowFlags.alwaysOnTop;
break;
case WindowTypes.notification:
motifHideDecorations();
setNetWMWindowType(GetAtom!"_NET_WM_WINDOW_TYPE_NOTIFICATION"(display));
customizationFlags |= WindowFlags.skipTaskbar | WindowFlags.alwaysOnTop;
break;
/+
case WindowTypes.menu:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_MENU"(display);
motifHideDecorations();
break;
case WindowTypes.desktop:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_DESKTOP"(display);
break;
case WindowTypes.dock:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_DOCK"(display);
break;
case WindowTypes.toolbar:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_TOOLBAR"(display);
break;
case WindowTypes.menu:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_MENU"(display);
break;
case WindowTypes.utility:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_UTILITY"(display);
break;
case WindowTypes.splash:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_SPLASH"(display);
break;
case WindowTypes.dialog:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_DIALOG"(display);
break;
case WindowTypes.tooltip:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_TOOLTIP"(display);
break;
case WindowTypes.notification:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_NOTIFICATION"(display);
break;
case WindowTypes.combo:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_COMBO"(display);
break;
case WindowTypes.dnd:
atoms[0] = GetAtom!"_NET_WM_WINDOW_TYPE_DND"(display);
break;
+/
}
catch(Exception e) {
// XInternAtom failed, prolly a WM
// that doesn't support these things
}
if (customizationFlags&WindowFlags.skipTaskbar) wsatoms[wmsacount++] = GetAtom!("_NET_WM_STATE_SKIP_TASKBAR", true)(display);
// the two following flags may be ignored by WM
if (customizationFlags&WindowFlags.alwaysOnTop) wsatoms[wmsacount++] = GetAtom!("_NET_WM_STATE_ABOVE", true)(display);
if (customizationFlags&WindowFlags.alwaysOnBottom) wsatoms[wmsacount++] = GetAtom!("_NET_WM_STATE_BELOW", true)(display);
if (wmsacount != 0) XChangeProperty(display, window, GetAtom!("_NET_WM_STATE", true)(display), XA_ATOM, 32 /* bits */,0 /*PropModeReplace*/, wsatoms.ptr, wmsacount);
if (this.resizability == Resizability.fixedSize || (opengl == OpenGlOptions.no && this.resizability != Resizability.allowResizing)) fixFixedSize!true(width, height);
// What would be ideal here is if they only were
// selected if there was actually an event handler
// for them...
selectDefaultInput((customizationFlags & WindowFlags.alwaysRequestMouseMotionEvents)?true:false);
hiddenWindow:
// set the pid property for lookup later by window managers
// a standard convenience
import core.sys.posix.unistd;
arch_ulong pid = getpid();
XChangeProperty(
display,
impl.window,
GetAtom!("_NET_WM_PID", true)(display),
XA_CARDINAL,
32 /* bits */,
0 /*PropModeReplace*/,
&pid,
1);
if(windowType != WindowTypes.eventOnly && (customizationFlags&WindowFlags.dontAutoShow) == 0) {
XMapWindow(display, window);
} else {
_hidden = true;
}
}
void selectDefaultInput(bool forceIncludeMouseMotion) {
auto mask = EventMask.ExposureMask |
EventMask.KeyPressMask |
EventMask.KeyReleaseMask |
EventMask.PropertyChangeMask |
EventMask.FocusChangeMask |
EventMask.StructureNotifyMask |
EventMask.VisibilityChangeMask
| EventMask.ButtonPressMask
| EventMask.ButtonReleaseMask
;
// xshm is our shortcut for local connections
if(Image.impl.xshmAvailable || forceIncludeMouseMotion)
mask |= EventMask.PointerMotionMask;
XSelectInput(display, window, mask);
}
void setNetWMWindowType(Atom type) {
Atom[2] atoms;
atoms[0] = type;
// generic fallback
atoms[1] = GetAtom!"_NET_WM_WINDOW_TYPE_NORMAL"(display);
XChangeProperty(
display,
impl.window,
GetAtom!"_NET_WM_WINDOW_TYPE"(display),
XA_ATOM,
32 /* bits */,
0 /*PropModeReplace*/,
atoms.ptr,
cast(int) atoms.length);
}
void motifHideDecorations() {
MwmHints hints;
hints.flags = MWM_HINTS_DECORATIONS;
XChangeProperty(
display,
impl.window,
GetAtom!"_MOTIF_WM_HINTS"(display),
GetAtom!"_MOTIF_WM_HINTS"(display),
32 /* bits */,
0 /*PropModeReplace*/,
&hints,
hints.sizeof / 4);
}
/*k8: unused
void createOpenGlContext() {
}
*/
void closeWindow() {
if (customEventFD != -1) {
import core.sys.posix.unistd : close;
close(customEventFD);
customEventFD = -1;
}
if(buffer)
XFreePixmap(display, buffer);
bufferw = bufferh = 0;
if (blankCurPtr && cursorSequenceNumber == XDisplayConnection.connectionSequenceNumber) XFreeCursor(display, blankCurPtr);
XDestroyWindow(display, window);
XFlush(display);
}
void dispose() {
}
bool destroyed = false;
}
bool insideXEventLoop;
}
version(X11) {
int mouseDoubleClickTimeout = 350; /// double click timeout. X only, you probably shouldn't change this.
/// Platform-specific, you might use it when doing a custom event loop
bool doXNextEvent(Display* display) {
bool done;
XEvent e;
XNextEvent(display, &e);
version(sddddd) {
import std.stdio, std.conv : to;
if(auto win = e.xany.window in CapableOfHandlingNativeEvent.nativeHandleMapping) {
if(typeid(cast(Object) *win) == NotificationAreaIcon.classinfo)
writeln("event for: ", e.xany.window, "; type is ", to!string(cast(EventType)e.type));
}
}
// filter out compose events
if (XFilterEvent(&e, None)) {
//{ import core.stdc.stdio : printf; printf("XFilterEvent filtered!\n"); }
//NOTE: we should ungrab keyboard here, but simpledisplay doesn't use keyboard grabbing (yet)
return false;
}
// process keyboard mapping changes
if (e.type == EventType.KeymapNotify) {
//{ import core.stdc.stdio : printf; printf("KeymapNotify processed!\n"); }
XRefreshKeyboardMapping(&e.xmapping);
return false;
}
version(with_eventloop)
import arsd.eventloop;
if(SimpleWindow.handleNativeGlobalEvent !is null) {
// see windows impl's comments
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
auto ret = SimpleWindow.handleNativeGlobalEvent(e);
if(ret == 0)
return done;
}
if(auto win = e.xany.window in CapableOfHandlingNativeEvent.nativeHandleMapping) {
if(win.getNativeEventHandler !is null) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
auto ret = win.getNativeEventHandler()(e);
if(ret == 0)
return done;
}
}
switch(e.type) {
case EventType.SelectionClear:
if(auto win = e.xselectionclear.window in SimpleWindow.nativeMapping)
{ /* FIXME??????? */ }
break;
case EventType.SelectionRequest:
if(auto win = e.xselectionrequest.owner in SimpleWindow.nativeMapping)
if(win.setSelectionHandler !is null) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
win.setSelectionHandler(e);
}
break;
case EventType.PropertyNotify:
break;
case EventType.SelectionNotify:
if(auto win = e.xselection.requestor in SimpleWindow.nativeMapping)
if(win.getSelectionHandler !is null) {
// FIXME: maybe we should call a different handler for PRIMARY vs CLIPBOARD
if(e.xselection.property == None) { // || e.xselection.property == GetAtom!("NULL", true)(e.xselection.display)) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
win.getSelectionHandler(null);
} else {
Atom target;
int format;
arch_ulong bytesafter, length;
void* value;
XGetWindowProperty(
e.xselection.display,
e.xselection.requestor,
e.xselection.property,
0,
100000 /* length */,
//false, /* don't erase it */
true, /* do erase it lol */
0 /*AnyPropertyType*/,
&target, &format, &length, &bytesafter, &value);
// FIXME: I don't have to copy it now since it is in char[] instead of string
{
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
if(target == XA_ATOM) {
// initial request, see what they are able to work with and request the best one
// we can handle, if available
Atom[] answer = (cast(Atom*) value)[0 .. length];
Atom best = None;
foreach(option; answer) {
if(option == GetAtom!"UTF8_STRING"(display)) {
best = option;
break;
} else if(option == XA_STRING) {
best = option;
}
}
//writeln("got ", answer);
if(best != None) {
// actually request the best format
XConvertSelection(e.xselection.display, e.xselection.selection, best, GetAtom!("SDD_DATA", true)(display), e.xselection.requestor, 0 /*CurrentTime*/);
}
} else if(target == GetAtom!"UTF8_STRING"(display) || target == XA_STRING) {
win.getSelectionHandler((cast(char[]) value[0 .. length]).idup);
} else if(target == GetAtom!"INCR"(display)) {
// incremental
//sdpyGettingPaste = true; // FIXME: should prolly be separate for the different selections
// FIXME: handle other events while it goes so app doesn't lock up with big pastes
// can also be optimized if it chunks to the api somehow
char[] s;
do {
XEvent subevent;
do {
XMaskEvent(display, EventMask.PropertyChangeMask, &subevent);
} while(subevent.type != EventType.PropertyNotify || subevent.xproperty.atom != e.xselection.property || subevent.xproperty.state != PropertyNotification.PropertyNewValue);
void* subvalue;
XGetWindowProperty(
e.xselection.display,
e.xselection.requestor,
e.xselection.property,
0,
100000 /* length */,
true, /* erase it to signal we got it and want more */
0 /*AnyPropertyType*/,
&target, &format, &length, &bytesafter, &subvalue);
s ~= (cast(char*) subvalue)[0 .. length];
XFree(subvalue);
} while(length > 0);
win.getSelectionHandler(s);
} else {
// unsupported type
}
}
XFree(value);
/*
XDeleteProperty(
e.xselection.display,
e.xselection.requestor,
e.xselection.property);
*/
}
}
break;
case EventType.ConfigureNotify:
auto event = e.xconfigure;
if(auto win = event.window in SimpleWindow.nativeMapping) {
//version(sdddd) { import std.stdio; writeln(" w=", event.width, "; h=", event.height); }
if(event.width != win.width || event.height != win.height) {
win._width = event.width;
win._height = event.height;
if(win.openglMode == OpenGlOptions.no) {
// FIXME: could this be more efficient?
if (win.bufferw < event.width || win.bufferh < event.height) {
//{ import core.stdc.stdio; printf("new buffer; old size: %dx%d; new size: %dx%d\n", win.bufferw, win.bufferh, cast(int)event.width, cast(int)event.height); }
// grow the internal buffer to match the window...
auto newPixmap = XCreatePixmap(display, cast(Drawable) event.window, event.width, event.height, DefaultDepthOfDisplay(display));
{
GC xgc = XCreateGC(win.display, cast(Drawable)win.window, 0, null);
XCopyGC(win.display, win.gc, 0xffffffff, xgc);
scope(exit) XFreeGC(win.display, xgc);
XSetClipMask(win.display, xgc, None);
XSetForeground(win.display, xgc, 0);
XFillRectangle(display, cast(Drawable)newPixmap, xgc, 0, 0, event.width, event.height);
}
XCopyArea(display,
cast(Drawable) (*win).buffer,
cast(Drawable) newPixmap,
(*win).gc, 0, 0,
win.bufferw < event.width ? win.bufferw : win.width,
win.bufferh < event.height ? win.bufferh : win.height,
0, 0);
XFreePixmap(display, win.buffer);
win.buffer = newPixmap;
win.bufferw = event.width;
win.bufferh = event.height;
}
// clear unused parts of the buffer
if (win.bufferw > event.width || win.bufferh > event.height) {
GC xgc = XCreateGC(win.display, cast(Drawable)win.window, 0, null);
XCopyGC(win.display, win.gc, 0xffffffff, xgc);
scope(exit) XFreeGC(win.display, xgc);
XSetClipMask(win.display, xgc, None);
XSetForeground(win.display, xgc, 0);
immutable int maxw = (win.bufferw > event.width ? win.bufferw : event.width);
immutable int maxh = (win.bufferh > event.height ? win.bufferh : event.height);
XFillRectangle(win.display, cast(Drawable)win.buffer, xgc, event.width, 0, maxw, maxh); // let X11 do clipping
XFillRectangle(win.display, cast(Drawable)win.buffer, xgc, 0, event.height, maxw, maxh); // let X11 do clipping
}
}
version(without_opengl) {} else
if(win.openglMode == OpenGlOptions.yes && win.resizability == Resizability.automaticallyScaleIfPossible) {
glViewport(0, 0, event.width, event.height);
}
win.fixFixedSize(event.width, event.height); //k8: this does nothing on my FluxBox; wtf?!
if(win.windowResized !is null) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
win.windowResized(event.width, event.height);
}
}
}
break;
case EventType.Expose:
if(auto win = e.xexpose.window in SimpleWindow.nativeMapping) {
// if it is closing from a popup menu, it can get
// an Expose event right by the end and trigger a
// BadDrawable error ... we'll just check
// closed to handle that.
if((*win).closed) break;
if((*win).openglMode == OpenGlOptions.no) {
bool doCopy = true;
if (win.handleExpose !is null) doCopy = !win.handleExpose(e.xexpose.x, e.xexpose.y, e.xexpose.width, e.xexpose.height, e.xexpose.count);
if (doCopy) XCopyArea(display, cast(Drawable) (*win).buffer, cast(Drawable) (*win).window, (*win).gc, e.xexpose.x, e.xexpose.y, e.xexpose.width, e.xexpose.height, e.xexpose.x, e.xexpose.y);
} else {
// need to redraw the scene somehow
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
version(without_opengl) {} else
win.redrawOpenGlSceneNow();
}
}
break;
case EventType.FocusIn:
case EventType.FocusOut:
if(auto win = e.xfocus.window in SimpleWindow.nativeMapping) {
if (win.xic !is null) {
//{ import core.stdc.stdio : printf; printf("XIC focus change!\n"); }
if (e.type == EventType.FocusIn) XSetICFocus(win.xic); else XUnsetICFocus(win.xic);
}
win._focused = e.type == EventType.FocusIn;
if(win.demandingAttention)
demandAttention(*win, false);
if(win.onFocusChange) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
win.onFocusChange(e.type == EventType.FocusIn);
}
}
break;
case EventType.VisibilityNotify:
if(auto win = e.xfocus.window in SimpleWindow.nativeMapping) {
if (e.xvisibility.state == VisibilityNotify.VisibilityFullyObscured) {
if (win.visibilityChanged !is null) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
win.visibilityChanged(false);
}
} else {
if (win.visibilityChanged !is null) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
win.visibilityChanged(true);
}
}
}
break;
case EventType.ClientMessage:
if (e.xclient.message_type == GetAtom!("_X11SDPY_INSMME_FLAG_EVENT_", true)(e.xany.display)) {
// "ignore next mouse motion" event, increment ignore counter for teh window
if (auto win = e.xclient.window in SimpleWindow.nativeMapping) {
++(*win).warpEventCount;
debug(x11sdpy_warp_debug) { import core.stdc.stdio : printf; printf("X11: got \"INSMME\" message, new count=%d\n", (*win).warpEventCount); }
} else {
debug(x11sdpy_warp_debug) { import core.stdc.stdio : printf; printf("X11: got \"INSMME\" WTF?!!\n"); }
}
} else if(e.xclient.data.l[0] == GetAtom!"WM_DELETE_WINDOW"(e.xany.display)) {
// user clicked the close button on the window manager
if(auto win = e.xclient.window in SimpleWindow.nativeMapping) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
if ((*win).closeQuery !is null) (*win).closeQuery(); else (*win).close();
}
} else if(e.xclient.message_type == GetAtom!"MANAGER"(e.xany.display)) {
foreach(nai; NotificationAreaIcon.activeIcons)
nai.newManager();
}
break;
case EventType.MapNotify:
if(auto win = e.xmap.window in SimpleWindow.nativeMapping) {
(*win)._visible = true;
if (!(*win)._visibleForTheFirstTimeCalled) {
(*win)._visibleForTheFirstTimeCalled = true;
if ((*win).visibleForTheFirstTime !is null) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
version(without_opengl) {} else {
if((*win).openglMode == OpenGlOptions.yes) {
(*win).setAsCurrentOpenGlContextNT();
glViewport(0, 0, (*win).width, (*win).height);
}
}
(*win).visibleForTheFirstTime();
}
}
if ((*win).visibilityChanged !is null) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
(*win).visibilityChanged(true);
}
}
break;
case EventType.UnmapNotify:
if(auto win = e.xunmap.window in SimpleWindow.nativeMapping) {
win._visible = false;
if (win.visibilityChanged !is null) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
win.visibilityChanged(false);
}
}
break;
case EventType.DestroyNotify:
if(auto win = e.xdestroywindow.window in SimpleWindow.nativeMapping) {
if (win.onDestroyed !is null) try { win.onDestroyed(); } catch (Exception e) {} // sorry
win._closed = true; // just in case
win.destroyed = true;
if (win.xic !is null) {
XDestroyIC(win.xic);
win.xic = null; // just in calse
}
SimpleWindow.nativeMapping.remove(e.xdestroywindow.window);
bool anyImportant = false;
foreach(SimpleWindow w; SimpleWindow.nativeMapping)
if(w.beingOpenKeepsAppOpen) {
anyImportant = true;
break;
}
if(!anyImportant)
done = true;
}
auto window = e.xdestroywindow.window;
if(window in CapableOfHandlingNativeEvent.nativeHandleMapping)
CapableOfHandlingNativeEvent.nativeHandleMapping.remove(window);
version(with_eventloop) {
if(done) exit();
}
break;
case EventType.MotionNotify:
MouseEvent mouse;
auto event = e.xmotion;
mouse.type = MouseEventType.motion;
mouse.x = event.x;
mouse.y = event.y;
mouse.modifierState = event.state;
if(auto win = e.xmotion.window in SimpleWindow.nativeMapping) {
mouse.window = *win;
if (win.warpEventCount > 0) {
debug(x11sdpy_warp_debug) { import core.stdc.stdio : printf; printf("X11: got \"warp motion\" message, current count=%d\n", (*win).warpEventCount); }
--(*win).warpEventCount;
(*win).mdx(mouse); // so deltas will be correctly updated
} else {
win.warpEventCount = 0; // just in case
(*win).mdx(mouse);
if((*win).handleMouseEvent) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
(*win).handleMouseEvent(mouse);
}
}
}
version(with_eventloop)
send(mouse);
break;
case EventType.ButtonPress:
case EventType.ButtonRelease:
MouseEvent mouse;
auto event = e.xbutton;
mouse.type = cast(MouseEventType) (e.type == EventType.ButtonPress ? 1 : 2);
mouse.x = event.x;
mouse.y = event.y;
static Time lastMouseDownTime = 0;
mouse.doubleClick = e.type == EventType.ButtonPress && (event.time - lastMouseDownTime) < mouseDoubleClickTimeout;
if(e.type == EventType.ButtonPress) lastMouseDownTime = event.time;
switch(event.button) {
case 1: mouse.button = MouseButton.left; break; // left
case 2: mouse.button = MouseButton.middle; break; // middle
case 3: mouse.button = MouseButton.right; break; // right
case 4: mouse.button = MouseButton.wheelUp; break; // scroll up
case 5: mouse.button = MouseButton.wheelDown; break; // scroll down
case 6: break; // idk
case 7: break; // idk
case 8: mouse.button = MouseButton.backButton; break;
case 9: mouse.button = MouseButton.forwardButton; break;
default:
}
// FIXME: double check this
mouse.modifierState = event.state;
//mouse.modifierState = event.detail;
if(auto win = e.xbutton.window in SimpleWindow.nativeMapping) {
mouse.window = *win;
(*win).mdx(mouse);
if((*win).handleMouseEvent) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
(*win).handleMouseEvent(mouse);
}
}
version(with_eventloop)
send(mouse);
break;
case EventType.KeyPress:
case EventType.KeyRelease:
//if (e.type == EventType.KeyPress) { import core.stdc.stdio : stderr, fprintf; fprintf(stderr, "X11 keyboard event!\n"); }
KeyEvent ke;
ke.pressed = e.type == EventType.KeyPress;
ke.hardwareCode = cast(ubyte) e.xkey.keycode;
auto sym = XKeycodeToKeysym(
XDisplayConnection.get(),
e.xkey.keycode,
0);
ke.key = cast(Key) sym;//e.xkey.keycode;
ke.modifierState = e.xkey.state;
// import std.stdio; writefln("%x", sym);
wchar_t[128] charbuf = void; // buffer for XwcLookupString; composed value can consist of many chars!
int charbuflen = 0; // return value of XwcLookupString
if (ke.pressed) {
auto win = e.xkey.window in SimpleWindow.nativeMapping;
if (win !is null && win.xic !is null) {
//{ import core.stdc.stdio : printf; printf("using xic!\n"); }
Status status;
charbuflen = XwcLookupString(win.xic, &e.xkey, charbuf.ptr, cast(int)charbuf.length, &sym, &status);
//{ import core.stdc.stdio : printf; printf("charbuflen=%d\n", charbuflen); }
} else {
//{ import core.stdc.stdio : printf; printf("NOT using xic!\n"); }
// If XIM initialization failed, don't process intl chars. Sorry, boys and girls.
char[16] buffer;
auto res = XLookupString(&e.xkey, buffer.ptr, buffer.length, null, null);
if (res && buffer[0] < 128) charbuf[charbuflen++] = cast(wchar_t)buffer[0];
}
}
// if there's no char, subst one
if (charbuflen == 0) {
switch (sym) {
case 0xff09: charbuf[charbuflen++] = '\t'; break;
case 0xff8d: // keypad enter
case 0xff0d: charbuf[charbuflen++] = '\n'; break;
default : // ignore
}
}
if (auto win = e.xkey.window in SimpleWindow.nativeMapping) {
ke.window = *win;
if (win.handleKeyEvent) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
win.handleKeyEvent(ke);
}
// char events are separate since they are on Windows too
// also, xcompose can generate long char sequences
// don't send char events if Meta and/or Hyper is pressed
// TODO: ctrl+char should only send control chars; not yet
if ((e.xkey.state&ModifierState.ctrl) != 0) {
if (charbuflen > 1 || charbuf[0] >= ' ') charbuflen = 0;
}
if (ke.pressed && charbuflen > 0 && (e.xkey.state&(ModifierState.alt|ModifierState.windows)) == 0) {
// FIXME: I think Windows sends these on releases... we should try to match that, but idk about repeats.
foreach (immutable dchar ch; charbuf[0..charbuflen]) {
if (win.handleCharEvent) {
XUnlockDisplay(display);
scope(exit) XLockDisplay(display);
win.handleCharEvent(ch);
}
}
}
}
version(with_eventloop)
send(ke);
break;
default:
}
return done;
}
}
/* *************************************** */
/* Done with simpledisplay stuff */
/* *************************************** */
// Necessary C library bindings follow
version(Windows) {} else
version(X11) {
extern(C) int eventfd (uint initval, int flags) nothrow @trusted @nogc;
// X11 bindings needed here
/*
A little of this is from the bindings project on
D Source and some of it is copy/paste from the C
header.
The DSource listing consistently used D's long
where C used long. That's wrong - C long is 32 bit, so
it should be int in D. I changed that here.
Note:
This isn't complete, just took what I needed for myself.
*/
pragma(lib, "X11");
pragma(lib, "Xext");
import core.stdc.stddef : wchar_t;
extern(C) nothrow @nogc {
Cursor XCreateFontCursor(Display*, uint shape);
int XDefineCursor(Display* display, Window w, Cursor cursor);
int XUndefineCursor(Display* display, Window w);
Pixmap XCreateBitmapFromData(Display* display, Drawable d, const(char)* data, uint width, uint height);
Cursor XCreatePixmapCursor(Display* display, Pixmap source, Pixmap mask, XColor* foreground_color, XColor* background_color, uint x, uint y);
int XFreeCursor(Display* display, Cursor cursor);
int XLookupString(XKeyEvent *event_struct, char *buffer_return, int bytes_buffer, KeySym *keysym_return, void *status_in_out);
int XwcLookupString(XIC ic, XKeyPressedEvent* event, wchar_t* buffer_return, int wchars_buffer, KeySym* keysym_return, Status* status_return);
char *XKeysymToString(KeySym keysym);
KeySym XKeycodeToKeysym(
Display* /* display */,
KeyCode /* keycode */,
int /* index */
);
int XConvertSelection(Display *display, Atom selection, Atom target, Atom property, Window requestor, Time time);
int XFree(void*);
int XDeleteProperty(Display *display, Window w, Atom property);
int XChangeProperty(Display *display, Window w, Atom property, Atom type, int format, int mode, in void *data, int nelements);
int XGetWindowProperty(Display *display, Window w, Atom property, arch_long
long_offset, arch_long long_length, Bool del, Atom req_type, Atom
*actual_type_return, int *actual_format_return, arch_ulong
*nitems_return, arch_ulong *bytes_after_return, void** prop_return);
Atom* XListProperties(Display *display, Window w, int *num_prop_return);
Status XGetTextProperty(Display *display, Window w, XTextProperty *text_prop_return, Atom property);
Status XQueryTree(Display *display, Window w, Window *root_return, Window *parent_return, Window **children_return, uint *nchildren_return);
int XSetSelectionOwner(Display *display, Atom selection, Window owner, Time time);
Window XGetSelectionOwner(Display *display, Atom selection);
struct XVisualInfo {
Visual* visual;
VisualID visualid;
int screen;
uint depth;
int c_class;
c_ulong red_mask;
c_ulong green_mask;
c_ulong blue_mask;
int colormap_size;
int bits_per_rgb;
}
enum VisualNoMask= 0x0;
enum VisualIDMask= 0x1;
enum VisualScreenMask=0x2;
enum VisualDepthMask= 0x4;
enum VisualClassMask= 0x8;
enum VisualRedMaskMask=0x10;
enum VisualGreenMaskMask=0x20;
enum VisualBlueMaskMask=0x40;
enum VisualColormapSizeMask=0x80;
enum VisualBitsPerRGBMask=0x100;
enum VisualAllMask= 0x1FF;
XVisualInfo* XGetVisualInfo(Display*, c_long, XVisualInfo*, int*);
Display* XOpenDisplay(const char*);
int XCloseDisplay(Display*);
Bool XQueryExtension(Display*, const char*, int*, int*, int*);
// XIM and other crap
struct _XOM {}
struct _XIM {}
struct _XIC {}
alias XOM = _XOM*;
alias XIM = _XIM*;
alias XIC = _XIC*;
Bool XSupportsLocale();
char* XSetLocaleModifiers(const(char)* modifier_list);
XOM XOpenOM(Display* display, _XrmHashBucketRec* rdb, const(char)* res_name, const(char)* res_class);
Status XCloseOM(XOM om);
XIM XOpenIM(Display* dpy, _XrmHashBucketRec* rdb, const(char)* res_name, const(char)* res_class);
Status XCloseIM(XIM im);
char* XGetIMValues(XIM im, ...) /*_X_SENTINEL(0)*/;
char* XSetIMValues(XIM im, ...) /*_X_SENTINEL(0)*/;
Display* XDisplayOfIM(XIM im);
char* XLocaleOfIM(XIM im);
XIC XCreateIC(XIM im, ...) /*_X_SENTINEL(0)*/;
void XDestroyIC(XIC ic);
void XSetICFocus(XIC ic);
void XUnsetICFocus(XIC ic);
//wchar_t* XwcResetIC(XIC ic);
char* XmbResetIC(XIC ic);
char* Xutf8ResetIC(XIC ic);
char* XSetICValues(XIC ic, ...) /*_X_SENTINEL(0)*/;
char* XGetICValues(XIC ic, ...) /*_X_SENTINEL(0)*/;
XIM XIMOfIC(XIC ic);
alias XIMStyle = arch_ulong;
enum : arch_ulong {
XIMPreeditArea = 0x0001,
XIMPreeditCallbacks = 0x0002,
XIMPreeditPosition = 0x0004,
XIMPreeditNothing = 0x0008,
XIMPreeditNone = 0x0010,
XIMStatusArea = 0x0100,
XIMStatusCallbacks = 0x0200,
XIMStatusNothing = 0x0400,
XIMStatusNone = 0x0800,
}
/* X Shared Memory Extension functions */
//pragma(lib, "Xshm");
alias arch_ulong ShmSeg;
struct XShmSegmentInfo {
ShmSeg shmseg;
int shmid;
ubyte* shmaddr;
Bool readOnly;
}
Status XShmAttach(Display*, XShmSegmentInfo*);
Status XShmDetach(Display*, XShmSegmentInfo*);
Status XShmPutImage(
Display* /* dpy */,
Drawable /* d */,
GC /* gc */,
XImage* /* image */,
int /* src_x */,
int /* src_y */,
int /* dst_x */,
int /* dst_y */,
uint /* src_width */,
uint /* src_height */,
Bool /* send_event */
);
Status XShmQueryExtension(Display*);
XImage *XShmCreateImage(
Display* /* dpy */,
Visual* /* visual */,
uint /* depth */,
int /* format */,
char* /* data */,
XShmSegmentInfo* /* shminfo */,
uint /* width */,
uint /* height */
);
Pixmap XShmCreatePixmap(
Display* /* dpy */,
Drawable /* d */,
char* /* data */,
XShmSegmentInfo* /* shminfo */,
uint /* width */,
uint /* height */,
uint /* depth */
);
// and the necessary OS functions
int shmget(int, size_t, int);
void* shmat(int, in void*, int);
int shmdt(in void*);
int shmctl (int shmid, int cmd, void* ptr /*struct shmid_ds *buf*/);
enum IPC_PRIVATE = 0;
enum IPC_CREAT = 512;
enum IPC_RMID = 0;
/* MIT-SHM end */
uint XSendEvent(Display* display, Window w, Bool propagate, arch_long event_mask, XEvent* event_send);
enum MappingType:int {
MappingModifier =0,
MappingKeyboard =1,
MappingPointer =2
}
/* ImageFormat -- PutImage, GetImage */
enum ImageFormat:int {
XYBitmap =0, /* depth 1, XYFormat */
XYPixmap =1, /* depth == drawable depth */
ZPixmap =2 /* depth == drawable depth */
}
enum ModifierName:int {
ShiftMapIndex =0,
LockMapIndex =1,
ControlMapIndex =2,
Mod1MapIndex =3,
Mod2MapIndex =4,
Mod3MapIndex =5,
Mod4MapIndex =6,
Mod5MapIndex =7
}
enum ButtonMask:int {
Button1Mask =1<<8,
Button2Mask =1<<9,
Button3Mask =1<<10,
Button4Mask =1<<11,
Button5Mask =1<<12,
AnyModifier =1<<15/* used in GrabButton, GrabKey */
}
enum KeyOrButtonMask:uint {
ShiftMask =1<<0,
LockMask =1<<1,
ControlMask =1<<2,
Mod1Mask =1<<3,
Mod2Mask =1<<4,
Mod3Mask =1<<5,
Mod4Mask =1<<6,
Mod5Mask =1<<7,
Button1Mask =1<<8,
Button2Mask =1<<9,
Button3Mask =1<<10,
Button4Mask =1<<11,
Button5Mask =1<<12,
AnyModifier =1<<15/* used in GrabButton, GrabKey */
}
enum ButtonName:int {
Button1 =1,
Button2 =2,
Button3 =3,
Button4 =4,
Button5 =5
}
/* Notify modes */
enum NotifyModes:int
{
NotifyNormal =0,
NotifyGrab =1,
NotifyUngrab =2,
NotifyWhileGrabbed =3
}
const int NotifyHint =1; /* for MotionNotify events */
/* Notify detail */
enum NotifyDetail:int
{
NotifyAncestor =0,
NotifyVirtual =1,
NotifyInferior =2,
NotifyNonlinear =3,
NotifyNonlinearVirtual =4,
NotifyPointer =5,
NotifyPointerRoot =6,
NotifyDetailNone =7
}
/* Visibility notify */
enum VisibilityNotify:int
{
VisibilityUnobscured =0,
VisibilityPartiallyObscured =1,
VisibilityFullyObscured =2
}
enum WindowStackingMethod:int
{
Above =0,
Below =1,
TopIf =2,
BottomIf =3,
Opposite =4
}
/* Circulation request */
enum CirculationRequest:int
{
PlaceOnTop =0,
PlaceOnBottom =1
}
enum PropertyNotification:int
{
PropertyNewValue =0,
PropertyDelete =1
}
enum ColorMapNotification:int
{
ColormapUninstalled =0,
ColormapInstalled =1
}
struct _XPrivate {}
struct _XrmHashBucketRec {}
alias void* XPointer;
alias void* XExtData;
version( X86_64 ) {
alias ulong XID;
alias ulong arch_ulong;
alias long arch_long;
} else {
alias uint XID;
alias uint arch_ulong;
alias int arch_long;
}
alias XID Window;
alias XID Drawable;
alias XID Pixmap;
alias arch_ulong Atom;
alias int Bool;
alias Display XDisplay;
alias int ByteOrder;
alias arch_ulong Time;
alias void ScreenFormat;
struct XImage {
int width, height; /* size of image */
int xoffset; /* number of pixels offset in X direction */
ImageFormat format; /* XYBitmap, XYPixmap, ZPixmap */
void *data; /* pointer to image data */
ByteOrder byte_order; /* data byte order, LSBFirst, MSBFirst */
int bitmap_unit; /* quant. of scanline 8, 16, 32 */
int bitmap_bit_order; /* LSBFirst, MSBFirst */
int bitmap_pad; /* 8, 16, 32 either XY or ZPixmap */
int depth; /* depth of image */
int bytes_per_line; /* accelarator to next line */
int bits_per_pixel; /* bits per pixel (ZPixmap) */
arch_ulong red_mask; /* bits in z arrangment */
arch_ulong green_mask;
arch_ulong blue_mask;
XPointer obdata; /* hook for the object routines to hang on */
static struct F { /* image manipulation routines */
XImage* function(
XDisplay* /* display */,
Visual* /* visual */,
uint /* depth */,
int /* format */,
int /* offset */,
ubyte* /* data */,
uint /* width */,
uint /* height */,
int /* bitmap_pad */,
int /* bytes_per_line */) create_image;
int function(XImage *) destroy_image;
arch_ulong function(XImage *, int, int) get_pixel;
int function(XImage *, int, int, arch_ulong) put_pixel;
XImage* function(XImage *, int, int, uint, uint) sub_image;
int function(XImage *, arch_long) add_pixel;
}
F f;
}
version(X86_64) static assert(XImage.sizeof == 136);
else version(X86) static assert(XImage.sizeof == 88);
struct XCharStruct {
short lbearing; /* origin to left edge of raster */
short rbearing; /* origin to right edge of raster */
short width; /* advance to next char's origin */
short ascent; /* baseline to top edge of raster */
short descent; /* baseline to bottom edge of raster */
ushort attributes; /* per char flags (not predefined) */
}
/*
* To allow arbitrary information with fonts, there are additional properties
* returned.
*/
struct XFontProp {
Atom name;
arch_ulong card32;
}
alias Atom Font;
struct XFontStruct {
XExtData *ext_data; /* Hook for extension to hang data */
Font fid; /* Font ID for this font */
uint direction; /* Direction the font is painted */
uint min_char_or_byte2; /* First character */
uint max_char_or_byte2; /* Last character */
uint min_byte1; /* First row that exists (for two-byte fonts) */
uint max_byte1; /* Last row that exists (for two-byte fonts) */
Bool all_chars_exist; /* Flag if all characters have nonzero size */
uint default_char; /* Char to print for undefined character */
int n_properties; /* How many properties there are */
XFontProp *properties; /* Pointer to array of additional properties*/
XCharStruct min_bounds; /* Minimum bounds over all existing char*/
XCharStruct max_bounds; /* Maximum bounds over all existing char*/
XCharStruct *per_char; /* first_char to last_char information */
int ascent; /* Max extent above baseline for spacing */
int descent; /* Max descent below baseline for spacing */
}
XFontStruct *XLoadQueryFont(Display *display, in char *name);
int XFreeFont(Display *display, XFontStruct *font_struct);
int XSetFont(Display* display, GC gc, Font font);
int XTextWidth(XFontStruct*, in char*, int);
int XSetLineAttributes(Display *display, GC gc, uint line_width, int line_style, int cap_style, int join_style);
int XSetDashes(Display *display, GC gc, int dash_offset, in byte* dash_list, int n);
/*
* Definitions of specific events.
*/
struct XKeyEvent
{
int type; /* of event */
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window; /* "event" window it is reported relative to */
Window root; /* root window that the event occurred on */
Window subwindow; /* child window */
Time time; /* milliseconds */
int x, y; /* pointer x, y coordinates in event window */
int x_root, y_root; /* coordinates relative to root */
KeyOrButtonMask state; /* key or button mask */
uint keycode; /* detail */
Bool same_screen; /* same screen flag */
}
version(X86_64) static assert(XKeyEvent.sizeof == 96);
alias XKeyEvent XKeyPressedEvent;
alias XKeyEvent XKeyReleasedEvent;
struct XButtonEvent
{
int type; /* of event */
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window; /* "event" window it is reported relative to */
Window root; /* root window that the event occurred on */
Window subwindow; /* child window */
Time time; /* milliseconds */
int x, y; /* pointer x, y coordinates in event window */
int x_root, y_root; /* coordinates relative to root */
KeyOrButtonMask state; /* key or button mask */
uint button; /* detail */
Bool same_screen; /* same screen flag */
}
alias XButtonEvent XButtonPressedEvent;
alias XButtonEvent XButtonReleasedEvent;
struct XMotionEvent{
int type; /* of event */
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window; /* "event" window reported relative to */
Window root; /* root window that the event occurred on */
Window subwindow; /* child window */
Time time; /* milliseconds */
int x, y; /* pointer x, y coordinates in event window */
int x_root, y_root; /* coordinates relative to root */
KeyOrButtonMask state; /* key or button mask */
byte is_hint; /* detail */
Bool same_screen; /* same screen flag */
}
alias XMotionEvent XPointerMovedEvent;
struct XCrossingEvent{
int type; /* of event */
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window; /* "event" window reported relative to */
Window root; /* root window that the event occurred on */
Window subwindow; /* child window */
Time time; /* milliseconds */
int x, y; /* pointer x, y coordinates in event window */
int x_root, y_root; /* coordinates relative to root */
NotifyModes mode; /* NotifyNormal, NotifyGrab, NotifyUngrab */
NotifyDetail detail;
/*
* NotifyAncestor, NotifyVirtual, NotifyInferior,
* NotifyNonlinear,NotifyNonlinearVirtual
*/
Bool same_screen; /* same screen flag */
Bool focus; /* Boolean focus */
KeyOrButtonMask state; /* key or button mask */
}
alias XCrossingEvent XEnterWindowEvent;
alias XCrossingEvent XLeaveWindowEvent;
struct XFocusChangeEvent{
int type; /* FocusIn or FocusOut */
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window; /* window of event */
NotifyModes mode; /* NotifyNormal, NotifyWhileGrabbed,
NotifyGrab, NotifyUngrab */
NotifyDetail detail;
/*
* NotifyAncestor, NotifyVirtual, NotifyInferior,
* NotifyNonlinear,NotifyNonlinearVirtual, NotifyPointer,
* NotifyPointerRoot, NotifyDetailNone
*/
}
alias XFocusChangeEvent XFocusInEvent;
alias XFocusChangeEvent XFocusOutEvent;
Window XCreateSimpleWindow(
Display* /* display */,
Window /* parent */,
int /* x */,
int /* y */,
uint /* width */,
uint /* height */,
uint /* border_width */,
uint /* border */,
uint /* background */
);
Window XCreateWindow(Display *display, Window parent, int x, int y, uint width, uint height, uint border_width, int depth, uint class_, Visual *visual, arch_ulong valuemask, XSetWindowAttributes *attributes);
int XReparentWindow(Display*, Window, Window, int, int);
int XClearWindow(Display*, Window);
int XMoveResizeWindow(Display*, Window, int, int, uint, uint);
int XMoveWindow(Display*, Window, int, int);
int XResizeWindow(Display *display, Window w, uint width, uint height);
Colormap XCreateColormap(Display *display, Window w, Visual *visual, int alloc);
enum CWBackPixmap = (1L<<0);
enum CWBackPixel = (1L<<1);
enum CWBorderPixmap = (1L<<2);
enum CWBorderPixel = (1L<<3);
enum CWBitGravity = (1L<<4);
enum CWWinGravity = (1L<<5);
enum CWBackingStore = (1L<<6);
enum CWBackingPlanes = (1L<<7);
enum CWBackingPixel = (1L<<8);
enum CWOverrideRedirect = (1L<<9);
enum CWSaveUnder = (1L<<10);
enum CWEventMask = (1L<<11);
enum CWDontPropagate = (1L<<12);
enum CWColormap = (1L<<13);
enum CWCursor = (1L<<14);
struct XWindowAttributes {
int x, y; /* location of window */
int width, height; /* width and height of window */
int border_width; /* border width of window */
int depth; /* depth of window */
Visual *visual; /* the associated visual structure */
Window root; /* root of screen containing window */
int class_; /* InputOutput, InputOnly*/
int bit_gravity; /* one of the bit gravity values */
int win_gravity; /* one of the window gravity values */
int backing_store; /* NotUseful, WhenMapped, Always */
arch_ulong backing_planes; /* planes to be preserved if possible */
arch_ulong backing_pixel; /* value to be used when restoring planes */
Bool save_under; /* boolean, should bits under be saved? */
Colormap colormap; /* color map to be associated with window */
Bool map_installed; /* boolean, is color map currently installed*/
int map_state; /* IsUnmapped, IsUnviewable, IsViewable */
arch_long all_event_masks; /* set of events all people have interest in*/
arch_long your_event_mask; /* my event mask */
arch_long do_not_propagate_mask; /* set of events that should not propagate */
Bool override_redirect; /* boolean value for override-redirect */
Screen *screen; /* back pointer to correct screen */
}
enum IsUnmapped = 0;
enum IsUnviewable = 1;
enum IsViewable = 2;
Status XGetWindowAttributes(Display*, Window, XWindowAttributes*);
struct XSetWindowAttributes {
Pixmap background_pixmap;/* background, None, or ParentRelative */
arch_ulong background_pixel;/* background pixel */
Pixmap border_pixmap; /* border of the window or CopyFromParent */
arch_ulong border_pixel;/* border pixel value */
int bit_gravity; /* one of bit gravity values */
int win_gravity; /* one of the window gravity values */
int backing_store; /* NotUseful, WhenMapped, Always */
arch_ulong backing_planes;/* planes to be preserved if possible */
arch_ulong backing_pixel;/* value to use in restoring planes */
Bool save_under; /* should bits under be saved? (popups) */
arch_long event_mask; /* set of events that should be saved */
arch_long do_not_propagate_mask;/* set of events that should not propagate */
Bool override_redirect; /* boolean value for override_redirect */
Colormap colormap; /* color map to be associated with window */
Cursor cursor; /* cursor to be displayed (or None) */
}
XImage *XCreateImage(
Display* /* display */,
Visual* /* visual */,
uint /* depth */,
int /* format */,
int /* offset */,
ubyte* /* data */,
uint /* width */,
uint /* height */,
int /* bitmap_pad */,
int /* bytes_per_line */
);
Status XInitImage (XImage* image);
Atom XInternAtom(
Display* /* display */,
const char* /* atom_name */,
Bool /* only_if_exists */
);
Status XInternAtoms(Display*, const char**, int, Bool, Atom*);
char* XGetAtomName(Display*, Atom);
Status XGetAtomNames(Display*, Atom*, int count, char**);
alias int Status;
enum EventMask:int
{
NoEventMask =0,
KeyPressMask =1<<0,
KeyReleaseMask =1<<1,
ButtonPressMask =1<<2,
ButtonReleaseMask =1<<3,
EnterWindowMask =1<<4,
LeaveWindowMask =1<<5,
PointerMotionMask =1<<6,
PointerMotionHintMask =1<<7,
Button1MotionMask =1<<8,
Button2MotionMask =1<<9,
Button3MotionMask =1<<10,
Button4MotionMask =1<<11,
Button5MotionMask =1<<12,
ButtonMotionMask =1<<13,
KeymapStateMask =1<<14,
ExposureMask =1<<15,
VisibilityChangeMask =1<<16,
StructureNotifyMask =1<<17,
ResizeRedirectMask =1<<18,
SubstructureNotifyMask =1<<19,
SubstructureRedirectMask=1<<20,
FocusChangeMask =1<<21,
PropertyChangeMask =1<<22,
ColormapChangeMask =1<<23,
OwnerGrabButtonMask =1<<24
}
int XPutImage(
Display* /* display */,
Drawable /* d */,
GC /* gc */,
XImage* /* image */,
int /* src_x */,
int /* src_y */,
int /* dest_x */,
int /* dest_y */,
uint /* width */,
uint /* height */
);
int XDestroyWindow(
Display* /* display */,
Window /* w */
);
int XDestroyImage(XImage*);
int XSelectInput(
Display* /* display */,
Window /* w */,
EventMask /* event_mask */
);
int XMapWindow(
Display* /* display */,
Window /* w */
);
struct MwmHints {
int flags;
int functions;
int decorations;
int input_mode;
int status;
}
enum {
MWM_HINTS_FUNCTIONS = (1L << 0),
MWM_HINTS_DECORATIONS = (1L << 1),
MWM_FUNC_ALL = (1L << 0),
MWM_FUNC_RESIZE = (1L << 1),
MWM_FUNC_MOVE = (1L << 2),
MWM_FUNC_MINIMIZE = (1L << 3),
MWM_FUNC_MAXIMIZE = (1L << 4),
MWM_FUNC_CLOSE = (1L << 5)
}
Status XIconifyWindow(Display*, Window, int);
int XMapRaised(Display*, Window);
int XMapSubwindows(Display*, Window);
int XNextEvent(
Display* /* display */,
XEvent* /* event_return */
);
int XMaskEvent(Display*, arch_long, XEvent*);
Bool XFilterEvent(XEvent *event, Window window);
int XRefreshKeyboardMapping(XMappingEvent *event_map);
Status XSetWMProtocols(
Display* /* display */,
Window /* w */,
Atom* /* protocols */,
int /* count */
);
import core.stdc.config : c_long, c_ulong;
void XSetWMNormalHints(Display *display, Window w, XSizeHints *hints);
Status XGetWMNormalHints(Display *display, Window w, XSizeHints *hints, c_long* supplied_return);
/* Size hints mask bits */
enum USPosition = (1L << 0) /* user specified x, y */;
enum USSize = (1L << 1) /* user specified width, height */;
enum PPosition = (1L << 2) /* program specified position */;
enum PSize = (1L << 3) /* program specified size */;
enum PMinSize = (1L << 4) /* program specified minimum size */;
enum PMaxSize = (1L << 5) /* program specified maximum size */;
enum PResizeInc = (1L << 6) /* program specified resize increments */;
enum PAspect = (1L << 7) /* program specified min and max aspect ratios */;
enum PBaseSize = (1L << 8);
enum PWinGravity = (1L << 9);
enum PAllHints = (PPosition|PSize| PMinSize|PMaxSize| PResizeInc|PAspect);
struct XSizeHints {
arch_long flags; /* marks which fields in this structure are defined */
int x, y; /* Obsolete */
int width, height; /* Obsolete */
int min_width, min_height;
int max_width, max_height;
int width_inc, height_inc;
struct Aspect {
int x; /* numerator */
int y; /* denominator */
}
Aspect min_aspect;
Aspect max_aspect;
int base_width, base_height;
int win_gravity;
/* this structure may be extended in the future */
}
enum EventType:int
{
KeyPress =2,
KeyRelease =3,
ButtonPress =4,
ButtonRelease =5,
MotionNotify =6,
EnterNotify =7,
LeaveNotify =8,
FocusIn =9,
FocusOut =10,
KeymapNotify =11,
Expose =12,
GraphicsExpose =13,
NoExpose =14,
VisibilityNotify =15,
CreateNotify =16,
DestroyNotify =17,
UnmapNotify =18,
MapNotify =19,
MapRequest =20,
ReparentNotify =21,
ConfigureNotify =22,
ConfigureRequest =23,
GravityNotify =24,
ResizeRequest =25,
CirculateNotify =26,
CirculateRequest =27,
PropertyNotify =28,
SelectionClear =29,
SelectionRequest =30,
SelectionNotify =31,
ColormapNotify =32,
ClientMessage =33,
MappingNotify =34,
LASTEvent =35 /* must be bigger than any event # */
}
/* generated on EnterWindow and FocusIn when KeyMapState selected */
struct XKeymapEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
byte[32] key_vector;
}
struct XExposeEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
int x, y;
int width, height;
int count; /* if non-zero, at least this many more */
}
struct XGraphicsExposeEvent{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Drawable drawable;
int x, y;
int width, height;
int count; /* if non-zero, at least this many more */
int major_code; /* core is CopyArea or CopyPlane */
int minor_code; /* not defined in the core */
}
struct XNoExposeEvent{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Drawable drawable;
int major_code; /* core is CopyArea or CopyPlane */
int minor_code; /* not defined in the core */
}
struct XVisibilityEvent{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
VisibilityNotify state; /* Visibility state */
}
struct XCreateWindowEvent{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window parent; /* parent of the window */
Window window; /* window id of window created */
int x, y; /* window location */
int width, height; /* size of window */
int border_width; /* border width */
Bool override_redirect; /* creation should be overridden */
}
struct XDestroyWindowEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
}
struct XUnmapEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
Bool from_configure;
}
struct XMapEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
Bool override_redirect; /* Boolean, is override set... */
}
struct XMapRequestEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window parent;
Window window;
}
struct XReparentEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
Window parent;
int x, y;
Bool override_redirect;
}
struct XConfigureEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
int x, y;
int width, height;
int border_width;
Window above;
Bool override_redirect;
}
struct XGravityEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
int x, y;
}
struct XResizeRequestEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
int width, height;
}
struct XConfigureRequestEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window parent;
Window window;
int x, y;
int width, height;
int border_width;
Window above;
WindowStackingMethod detail; /* Above, Below, TopIf, BottomIf, Opposite */
arch_ulong value_mask;
}
struct XCirculateEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
CirculationRequest place; /* PlaceOnTop, PlaceOnBottom */
}
struct XCirculateRequestEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window parent;
Window window;
CirculationRequest place; /* PlaceOnTop, PlaceOnBottom */
}
struct XPropertyEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
Atom atom;
Time time;
PropertyNotification state; /* NewValue, Deleted */
}
struct XSelectionClearEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
Atom selection;
Time time;
}
struct XSelectionRequestEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window owner;
Window requestor;
Atom selection;
Atom target;
Atom property;
Time time;
}
struct XSelectionEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window requestor;
Atom selection;
Atom target;
Atom property; /* ATOM or None */
Time time;
}
version(X86_64) static assert(XSelectionClearEvent.sizeof == 56);
struct XColormapEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
Colormap colormap; /* COLORMAP or None */
Bool new_; /* C++ */
ColorMapNotification state; /* ColormapInstalled, ColormapUninstalled */
}
version(X86_64) static assert(XColormapEvent.sizeof == 56);
struct XClientMessageEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
Atom message_type;
int format;
union Data{
byte[20] b;
short[10] s;
arch_ulong[5] l;
}
Data data;
}
version(X86_64) static assert(XClientMessageEvent.sizeof == 96);
struct XMappingEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window; /* unused */
MappingType request; /* one of MappingModifier, MappingKeyboard,
MappingPointer */
int first_keycode; /* first keycode */
int count; /* defines range of change w. first_keycode*/
}
struct XErrorEvent
{
int type;
Display *display; /* Display the event was read from */
XID resourceid; /* resource id */
arch_ulong serial; /* serial number of failed request */
ubyte error_code; /* error code of failed request */
ubyte request_code; /* Major op-code of failed request */
ubyte minor_code; /* Minor op-code of failed request */
}
struct XAnyEvent
{
int type;
arch_ulong serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display;/* Display the event was read from */
Window window; /* window on which event was requested in event mask */
}
union XEvent{
int type; /* must not be changed; first element */
XAnyEvent xany;
XKeyEvent xkey;
XButtonEvent xbutton;
XMotionEvent xmotion;
XCrossingEvent xcrossing;
XFocusChangeEvent xfocus;
XExposeEvent xexpose;
XGraphicsExposeEvent xgraphicsexpose;
XNoExposeEvent xnoexpose;
XVisibilityEvent xvisibility;
XCreateWindowEvent xcreatewindow;
XDestroyWindowEvent xdestroywindow;
XUnmapEvent xunmap;
XMapEvent xmap;
XMapRequestEvent xmaprequest;
XReparentEvent xreparent;
XConfigureEvent xconfigure;
XGravityEvent xgravity;
XResizeRequestEvent xresizerequest;
XConfigureRequestEvent xconfigurerequest;
XCirculateEvent xcirculate;
XCirculateRequestEvent xcirculaterequest;
XPropertyEvent xproperty;
XSelectionClearEvent xselectionclear;
XSelectionRequestEvent xselectionrequest;
XSelectionEvent xselection;
XColormapEvent xcolormap;
XClientMessageEvent xclient;
XMappingEvent xmapping;
XErrorEvent xerror;
XKeymapEvent xkeymap;
arch_ulong[24] pad;
}
struct Display {
XExtData *ext_data; /* hook for extension to hang data */
_XPrivate *private1;
int fd; /* Network socket. */
int private2;
int proto_major_version;/* major version of server's X protocol */
int proto_minor_version;/* minor version of servers X protocol */
char *vendor; /* vendor of the server hardware */
XID private3;
XID private4;
XID private5;
int private6;
XID function(Display*)resource_alloc;/* allocator function */
ByteOrder byte_order; /* screen byte order, LSBFirst, MSBFirst */
int bitmap_unit; /* padding and data requirements */
int bitmap_pad; /* padding requirements on bitmaps */
ByteOrder bitmap_bit_order; /* LeastSignificant or MostSignificant */
int nformats; /* number of pixmap formats in list */
ScreenFormat *pixmap_format; /* pixmap format list */
int private8;
int release; /* release of the server */
_XPrivate *private9;
_XPrivate *private10;
int qlen; /* Length of input event queue */
arch_ulong last_request_read; /* seq number of last event read */
arch_ulong request; /* sequence number of last request. */
XPointer private11;
XPointer private12;
XPointer private13;
XPointer private14;
uint max_request_size; /* maximum number 32 bit words in request*/
_XrmHashBucketRec *db;
int function (Display*)private15;
char *display_name; /* "host:display" string used on this connect*/
int default_screen; /* default screen for operations */
int nscreens; /* number of screens on this server*/
Screen *screens; /* pointer to list of screens */
arch_ulong motion_buffer; /* size of motion buffer */
arch_ulong private16;
int min_keycode; /* minimum defined keycode */
int max_keycode; /* maximum defined keycode */
XPointer private17;
XPointer private18;
int private19;
byte *xdefaults; /* contents of defaults from server */
/* there is more to this structure, but it is private to Xlib */
}
// I got these numbers from a C program as a sanity test
version(X86_64) {
static assert(Display.sizeof == 296);
static assert(XPointer.sizeof == 8);
static assert(XErrorEvent.sizeof == 40);
static assert(XAnyEvent.sizeof == 40);
static assert(XMappingEvent.sizeof == 56);
static assert(XEvent.sizeof == 192);
} else {
static assert(Display.sizeof == 176);
static assert(XPointer.sizeof == 4);
static assert(XEvent.sizeof == 96);
}
struct Depth
{
int depth; /* this depth (Z) of the depth */
int nvisuals; /* number of Visual types at this depth */
Visual *visuals; /* list of visuals possible at this depth */
}
alias void* GC;
alias c_ulong VisualID;
alias XID Colormap;
alias XID Cursor;
alias XID KeySym;
alias uint KeyCode;
enum None = 0;
}
version(without_opengl) {}
else {
extern(C) nothrow @nogc {
static if(!SdpyIsUsingIVGLBinds) {
enum GLX_USE_GL= 1; /* support GLX rendering */
enum GLX_BUFFER_SIZE= 2; /* depth of the color buffer */
enum GLX_LEVEL= 3; /* level in plane stacking */
enum GLX_RGBA= 4; /* true if RGBA mode */
enum GLX_DOUBLEBUFFER= 5; /* double buffering supported */
enum GLX_STEREO= 6; /* stereo buffering supported */
enum GLX_AUX_BUFFERS= 7; /* number of aux buffers */
enum GLX_RED_SIZE= 8; /* number of red component bits */
enum GLX_GREEN_SIZE= 9; /* number of green component bits */
enum GLX_BLUE_SIZE= 10; /* number of blue component bits */
enum GLX_ALPHA_SIZE= 11; /* number of alpha component bits */
enum GLX_DEPTH_SIZE= 12; /* number of depth bits */
enum GLX_STENCIL_SIZE= 13; /* number of stencil bits */
enum GLX_ACCUM_RED_SIZE= 14; /* number of red accum bits */
enum GLX_ACCUM_GREEN_SIZE= 15; /* number of green accum bits */
enum GLX_ACCUM_BLUE_SIZE= 16; /* number of blue accum bits */
enum GLX_ACCUM_ALPHA_SIZE= 17; /* number of alpha accum bits */
//XVisualInfo* glXChooseVisual(Display *dpy, int screen, in int *attrib_list);
enum GL_TRUE = 1;
enum GL_FALSE = 0;
alias int GLint;
}
alias XID GLXContextID;
alias XID GLXPixmap;
alias XID GLXDrawable;
alias XID GLXPbuffer;
alias XID GLXWindow;
alias XID GLXFBConfigID;
alias void* GLXContext;
static if (!SdpyIsUsingIVGLBinds) {
XVisualInfo* glXChooseVisual(Display *dpy, int screen,
const int *attrib_list);
void glXCopyContext(Display *dpy, GLXContext src,
GLXContext dst, arch_ulong mask);
GLXContext glXCreateContext(Display *dpy, XVisualInfo *vis,
GLXContext share_list, Bool direct);
GLXPixmap glXCreateGLXPixmap(Display *dpy, XVisualInfo *vis,
Pixmap pixmap);
void glXDestroyContext(Display *dpy, GLXContext ctx);
void glXDestroyGLXPixmap(Display *dpy, GLXPixmap pix);
int glXGetConfig(Display *dpy, XVisualInfo *vis,
int attrib, int *value);
GLXContext glXGetCurrentContext();
GLXDrawable glXGetCurrentDrawable();
Bool glXIsDirect(Display *dpy, GLXContext ctx);
Bool glXMakeCurrent(Display *dpy, GLXDrawable drawable,
GLXContext ctx);
Bool glXQueryExtension(Display *dpy, int *error_base, int *event_base);
Bool glXQueryVersion(Display *dpy, int *major, int *minor);
void glXSwapBuffers(Display *dpy, GLXDrawable drawable);
void glXUseXFont(Font font, int first, int count, int list_base);
void glXWaitGL();
void glXWaitX();
}
}
}
enum AllocNone = 0;
extern(C) {
/* WARNING, this type not in Xlib spec */
extern(C) alias XIOErrorHandler = int function (Display* display);
XIOErrorHandler XSetIOErrorHandler (XIOErrorHandler handler);
}
extern(C) nothrow @nogc {
struct Screen{
XExtData *ext_data; /* hook for extension to hang data */
Display *display; /* back pointer to display structure */
Window root; /* Root window id. */
int width, height; /* width and height of screen */
int mwidth, mheight; /* width and height of in millimeters */
int ndepths; /* number of depths possible */
Depth *depths; /* list of allowable depths on the screen */
int root_depth; /* bits per pixel */
Visual *root_visual; /* root visual */
GC default_gc; /* GC for the root root visual */
Colormap cmap; /* default color map */
uint white_pixel;
uint black_pixel; /* White and Black pixel values */
int max_maps, min_maps; /* max and min color maps */
int backing_store; /* Never, WhenMapped, Always */
bool save_unders;
int root_input_mask; /* initial root input mask */
}
struct Visual
{
XExtData *ext_data; /* hook for extension to hang data */
VisualID visualid; /* visual id of this visual */
int class_; /* class of screen (monochrome, etc.) */
c_ulong red_mask, green_mask, blue_mask; /* mask values */
int bits_per_rgb; /* log base 2 of distinct color values */
int map_entries; /* color map entries */
}
alias Display* _XPrivDisplay;
Screen* ScreenOfDisplay(Display* dpy, int scr) {
assert(dpy !is null);
return &dpy.screens[scr];
}
Window RootWindow(Display *dpy,int scr) {
return ScreenOfDisplay(dpy,scr).root;
}
struct XWMHints {
arch_long flags;
Bool input;
int initial_state;
Pixmap icon_pixmap;
Window icon_window;
int icon_x, icon_y;
Pixmap icon_mask;
XID window_group;
}
struct XClassHint {
char* res_name;
char* res_class;
}
Status XInitThreads();
void XLockDisplay (Display* display);
void XUnlockDisplay (Display* display);
void XSetWMProperties(Display*, Window, XTextProperty*, XTextProperty*, char**, int, XSizeHints*, XWMHints*, XClassHint*);
int XSetWindowBackground (Display* display, Window w, c_ulong background_pixel);
int XSetWindowBackgroundPixmap (Display* display, Window w, Pixmap background_pixmap);
//int XSetWindowBorder (Display* display, Window w, c_ulong border_pixel);
//int XSetWindowBorderPixmap (Display* display, Window w, Pixmap border_pixmap);
//int XSetWindowBorderWidth (Display* display, Window w, uint width);
// this requires -lXpm
int XpmCreatePixmapFromData(Display*, Drawable, in char**, Pixmap*, Pixmap*, void*); // FIXME: void* should be XpmAttributes
int DefaultScreen(Display *dpy) {
return dpy.default_screen;
}
int DefaultDepth(Display* dpy, int scr) { return ScreenOfDisplay(dpy, scr).root_depth; }
int DisplayWidth(Display* dpy, int scr) { return ScreenOfDisplay(dpy, scr).width; }
int DisplayHeight(Display* dpy, int scr) { return ScreenOfDisplay(dpy, scr).height; }
int DisplayWidthMM(Display* dpy, int scr) { return ScreenOfDisplay(dpy, scr).mwidth; }
int DisplayHeightMM(Display* dpy, int scr) { return ScreenOfDisplay(dpy, scr).mheight; }
auto DefaultColormap(Display* dpy, int scr) { return ScreenOfDisplay(dpy, scr).cmap; }
int ConnectionNumber(Display* dpy) { return dpy.fd; }
enum int AnyPropertyType = 0;
enum int Success = 0;
enum int RevertToNone = None;
enum int PointerRoot = 1;
enum Time CurrentTime = 0;
enum int RevertToPointerRoot = PointerRoot;
enum int RevertToParent = 2;
int DefaultDepthOfDisplay(Display* dpy) {
return ScreenOfDisplay(dpy, DefaultScreen(dpy)).root_depth;
}
Visual* DefaultVisual(Display *dpy,int scr) {
return ScreenOfDisplay(dpy,scr).root_visual;
}
GC DefaultGC(Display *dpy,int scr) {
return ScreenOfDisplay(dpy,scr).default_gc;
}
uint BlackPixel(Display *dpy,int scr) {
return ScreenOfDisplay(dpy,scr).black_pixel;
}
uint WhitePixel(Display *dpy,int scr) {
return ScreenOfDisplay(dpy,scr).white_pixel;
}
// check out Xft too: http://www.keithp.com/~keithp/render/Xft.tutorial
int XDrawString(Display*, Drawable, GC, int, int, in char*, int);
int XDrawLine(Display*, Drawable, GC, int, int, int, int);
int XDrawRectangle(Display*, Drawable, GC, int, int, uint, uint);
int XDrawArc(Display*, Drawable, GC, int, int, uint, uint, int, int);
int XFillRectangle(Display*, Drawable, GC, int, int, uint, uint);
int XFillArc(Display*, Drawable, GC, int, int, uint, uint, int, int);
int XDrawPoint(Display*, Drawable, GC, int, int);
int XSetForeground(Display*, GC, uint);
int XSetBackground(Display*, GC, uint);
alias void* XFontSet; // i think
XFontSet XCreateFontSet(Display*, const char*, char***, int*, char**);
void XFreeFontSet(Display*, XFontSet);
void Xutf8DrawString(Display*, Drawable, XFontSet, GC, int, int, in char*, int);
void Xutf8DrawText(Display*, Drawable, GC, int, int, XmbTextItem*, int);
struct XmbTextItem {
char* chars;
int nchars;
int delta;
XFontSet font_set;
}
void XDrawText(Display*, Drawable, GC, int, int, XTextItem*, int);
struct XTextItem {
char* chars;
int nchars;
int delta;
Font font;
}
int XSetFunction(Display*, GC, int);
enum {
GXclear = 0x0, /* 0 */
GXand = 0x1, /* src AND dst */
GXandReverse = 0x2, /* src AND NOT dst */
GXcopy = 0x3, /* src */
GXandInverted = 0x4, /* NOT src AND dst */
GXnoop = 0x5, /* dst */
GXxor = 0x6, /* src XOR dst */
GXor = 0x7, /* src OR dst */
GXnor = 0x8, /* NOT src AND NOT dst */
GXequiv = 0x9, /* NOT src XOR dst */
GXinvert = 0xa, /* NOT dst */
GXorReverse = 0xb, /* src OR NOT dst */
GXcopyInverted = 0xc, /* NOT src */
GXorInverted = 0xd, /* NOT src OR dst */
GXnand = 0xe, /* NOT src OR NOT dst */
GXset = 0xf, /* 1 */
}
GC XCreateGC(Display*, Drawable, uint, void*);
int XCopyGC(Display*, GC, uint, GC);
int XFreeGC(Display*, GC);
bool XCheckWindowEvent(Display*, Window, int, XEvent*);
bool XCheckMaskEvent(Display*, int, XEvent*);
int XPending(Display*);
int XEventsQueued(Display* display, int mode);
enum QueueMode : int {
QueuedAlready,
QueuedAfterReading,
QueuedAfterFlush
}
Pixmap XCreatePixmap(Display*, Drawable, uint, uint, uint);
int XFreePixmap(Display*, Pixmap);
int XCopyArea(Display*, Drawable, Drawable, GC, int, int, uint, uint, int, int);
int XFlush(Display*);
int XBell(Display*, int);
int XSync(Display*, bool);
enum GrabMode { GrabModeSync = 0, GrabModeAsync = 1 }
int XGrabKey (Display* display, int keycode, uint modifiers, Window grab_window, Bool owner_events, int pointer_mode, int keyboard_mode);
int XUngrabKey (Display* display, int keycode, uint modifiers, Window grab_window);
KeyCode XKeysymToKeycode (Display* display, KeySym keysym);
struct XPoint {
short x;
short y;
}
int XDrawLines(Display*, Drawable, GC, XPoint*, int, CoordMode);
int XFillPolygon(Display*, Drawable, GC, XPoint*, int, PolygonShape, CoordMode);
enum CoordMode:int {
CoordModeOrigin = 0,
CoordModePrevious = 1
}
enum PolygonShape:int {
Complex = 0,
Nonconvex = 1,
Convex = 2
}
struct XTextProperty {
const(char)* value; /* same as Property routines */
Atom encoding; /* prop type */
int format; /* prop data format: 8, 16, or 32 */
arch_ulong nitems; /* number of data items in value */
}
version( X86_64 ) {
static assert(XTextProperty.sizeof == 32);
}
struct XGCValues {
int function_; /* logical operation */
arch_ulong plane_mask;/* plane mask */
arch_ulong foreground;/* foreground pixel */
arch_ulong background;/* background pixel */
int line_width; /* line width */
int line_style; /* LineSolid, LineOnOffDash, LineDoubleDash */
int cap_style; /* CapNotLast, CapButt,
CapRound, CapProjecting */
int join_style; /* JoinMiter, JoinRound, JoinBevel */
int fill_style; /* FillSolid, FillTiled,
FillStippled, FillOpaeueStippled */
int fill_rule; /* EvenOddRule, WindingRule */
int arc_mode; /* ArcChord, ArcPieSlice */
Pixmap tile; /* tile pixmap for tiling operations */
Pixmap stipple; /* stipple 1 plane pixmap for stipping */
int ts_x_origin; /* offset for tile or stipple operations */
int ts_y_origin;
Font font; /* default text font for text operations */
int subwindow_mode; /* ClipByChildren, IncludeInferiors */
Bool graphics_exposures;/* boolean, should exposures be generated */
int clip_x_origin; /* origin for clipping */
int clip_y_origin;
Pixmap clip_mask; /* bitmap clipping; other calls for rects */
int dash_offset; /* patterned/dashed line information */
char dashes;
}
struct XColor {
arch_ulong pixel;
ushort red, green, blue;
byte flags;
byte pad;
}
Status XAllocColor(Display*, Colormap, XColor*);
int XWithdrawWindow(Display*, Window, int);
int XUnmapWindow(Display*, Window);
int XLowerWindow(Display*, Window);
int XRaiseWindow(Display*, Window);
int XWarpPointer(Display *display, Window src_w, Window dest_w, int src_x, int src_y, uint src_width, uint src_height, int dest_x, int dest_y);
Bool XTranslateCoordinates(Display *display, Window src_w, Window dest_w, int src_x, int src_y, int *dest_x_return, int *dest_y_return, Window *child_return);
int XGetInputFocus(Display*, Window*, int*);
int XSetInputFocus(Display*, Window, int, Time);
alias XErrorHandler = int function(Display*, XErrorEvent*);
XErrorHandler XSetErrorHandler(XErrorHandler);
int XGetErrorText(Display*, int, char*, int);
Bool XkbSetDetectableAutoRepeat(Display* dpy, Bool detectable, Bool* supported);
int XGrabPointer(Display *display, Window grab_window, Bool owner_events, uint event_mask, int pointer_mode, int keyboard_mode, Window confine_to, Cursor cursor, Time time);
int XUngrabPointer(Display *display, Time time);
int XChangeActivePointerGrab(Display *display, uint event_mask, Cursor cursor, Time time);
int XCopyPlane(Display*, Drawable, Drawable, GC, int, int, uint, uint, int, int, arch_ulong);
Status XGetGeometry(Display*, Drawable, Window*, int*, int*, uint*, uint*, uint*, uint*);
int XSetClipMask(Display*, GC, Pixmap);
int XSetClipOrigin(Display*, GC, int, int);
void XSetClipRectangles(Display*, GC, int, int, XRectangle*, int, int);
struct XRectangle {
short x;
short y;
ushort width;
ushort height;
}
void XSetWMName(Display*, Window, XTextProperty*);
Status XGetWMName(Display*, Window, XTextProperty*);
int XStoreName(Display* display, Window w, const(char)* window_name);
enum ClipByChildren = 0;
enum IncludeInferiors = 1;
enum Atom XA_PRIMARY = 1;
enum Atom XA_SECONDARY = 2;
enum Atom XA_STRING = 31;
enum Atom XA_CARDINAL = 6;
enum Atom XA_WM_NAME = 39;
enum Atom XA_ATOM = 4;
enum Atom XA_WINDOW = 33;
enum Atom XA_WM_HINTS = 35;
enum int PropModeAppend = 2;
enum int PropModeReplace = 0;
enum int PropModePrepend = 1;
enum int CopyFromParent = 0;
enum int InputOutput = 1;
// XWMHints
enum InputHint = 1 << 0;
enum StateHint = 1 << 1;
enum IconPixmapHint = (1L << 2);
enum IconWindowHint = (1L << 3);
enum IconPositionHint = (1L << 4);
enum IconMaskHint = (1L << 5);
enum WindowGroupHint = (1L << 6);
enum AllHints = (InputHint|StateHint|IconPixmapHint|IconWindowHint|IconPositionHint|IconMaskHint|WindowGroupHint);
enum XUrgencyHint = (1L << 8);
// GC Components
enum GCFunction = (1L<<0);
enum GCPlaneMask = (1L<<1);
enum GCForeground = (1L<<2);
enum GCBackground = (1L<<3);
enum GCLineWidth = (1L<<4);
enum GCLineStyle = (1L<<5);
enum GCCapStyle = (1L<<6);
enum GCJoinStyle = (1L<<7);
enum GCFillStyle = (1L<<8);
enum GCFillRule = (1L<<9);
enum GCTile = (1L<<10);
enum GCStipple = (1L<<11);
enum GCTileStipXOrigin = (1L<<12);
enum GCTileStipYOrigin = (1L<<13);
enum GCFont = (1L<<14);
enum GCSubwindowMode = (1L<<15);
enum GCGraphicsExposures= (1L<<16);
enum GCClipXOrigin = (1L<<17);
enum GCClipYOrigin = (1L<<18);
enum GCClipMask = (1L<<19);
enum GCDashOffset = (1L<<20);
enum GCDashList = (1L<<21);
enum GCArcMode = (1L<<22);
enum GCLastBit = 22;
enum int WithdrawnState = 0;
enum int NormalState = 1;
enum int IconicState = 3;
}
} else version (OSXCocoa) {
private:
alias void* id;
alias void* Class;
alias void* SEL;
alias void* IMP;
alias void* Ivar;
alias byte BOOL;
alias const(void)* CFStringRef;
alias const(void)* CFAllocatorRef;
alias const(void)* CFTypeRef;
alias const(void)* CGContextRef;
alias const(void)* CGColorSpaceRef;
alias const(void)* CGImageRef;
alias uint CGBitmapInfo;
struct objc_super {
id self;
Class superclass;
}
struct CFRange {
int location, length;
}
struct NSPoint {
float x, y;
static fromTuple(T)(T tupl) {
return NSPoint(tupl.tupleof);
}
}
struct NSSize {
float width, height;
}
struct NSRect {
NSPoint origin;
NSSize size;
}
alias NSPoint CGPoint;
alias NSSize CGSize;
alias NSRect CGRect;
struct CGAffineTransform {
float a, b, c, d, tx, ty;
}
enum NSApplicationActivationPolicyRegular = 0;
enum NSBackingStoreBuffered = 2;
enum kCFStringEncodingUTF8 = 0x08000100;
enum : size_t {
NSBorderlessWindowMask = 0,
NSTitledWindowMask = 1 << 0,
NSClosableWindowMask = 1 << 1,
NSMiniaturizableWindowMask = 1 << 2,
NSResizableWindowMask = 1 << 3,
NSTexturedBackgroundWindowMask = 1 << 8
}
enum : uint {
kCGImageAlphaNone,
kCGImageAlphaPremultipliedLast,
kCGImageAlphaPremultipliedFirst,
kCGImageAlphaLast,
kCGImageAlphaFirst,
kCGImageAlphaNoneSkipLast,
kCGImageAlphaNoneSkipFirst
}
enum : uint {
kCGBitmapAlphaInfoMask = 0x1F,
kCGBitmapFloatComponents = (1 << 8),
kCGBitmapByteOrderMask = 0x7000,
kCGBitmapByteOrderDefault = (0 << 12),
kCGBitmapByteOrder16Little = (1 << 12),
kCGBitmapByteOrder32Little = (2 << 12),
kCGBitmapByteOrder16Big = (3 << 12),
kCGBitmapByteOrder32Big = (4 << 12)
}
enum CGPathDrawingMode {
kCGPathFill,
kCGPathEOFill,
kCGPathStroke,
kCGPathFillStroke,
kCGPathEOFillStroke
}
enum objc_AssociationPolicy : size_t {
OBJC_ASSOCIATION_ASSIGN = 0,
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,
OBJC_ASSOCIATION_COPY_NONATOMIC = 3,
OBJC_ASSOCIATION_RETAIN = 0x301, //01401,
OBJC_ASSOCIATION_COPY = 0x303 //01403
}
extern(C) {
id objc_msgSend(id receiver, SEL selector, ...);
id objc_msgSendSuper(objc_super* superStruct, SEL selector, ...);
id objc_getClass(const(char)* name);
SEL sel_registerName(const(char)* str);
Class objc_allocateClassPair(Class superclass, const(char)* name,
size_t extra_bytes);
void objc_registerClassPair(Class cls);
BOOL class_addMethod(Class cls, SEL name, IMP imp, const(char)* types);
id objc_getAssociatedObject(id object, void* key);
void objc_setAssociatedObject(id object, void* key, id value,
objc_AssociationPolicy policy);
Ivar class_getInstanceVariable(Class cls, const(char)* name);
id object_getIvar(id object, Ivar ivar);
void object_setIvar(id object, Ivar ivar, id value);
BOOL class_addIvar(Class cls, const(char)* name,
size_t size, ubyte alignment, const(char)* types);
extern __gshared id NSApp;
void CFRelease(CFTypeRef obj);
CFStringRef CFStringCreateWithBytes(CFAllocatorRef allocator,
const(char)* bytes, long numBytes,
int encoding,
BOOL isExternalRepresentation);
int CFStringGetBytes(CFStringRef theString, CFRange range, int encoding,
char lossByte, bool isExternalRepresentation,
char* buffer, long maxBufLen, long* usedBufLen);
int CFStringGetLength(CFStringRef theString);
CGContextRef CGBitmapContextCreate(void* data,
size_t width, size_t height,
size_t bitsPerComponent,
size_t bytesPerRow,
CGColorSpaceRef colorspace,
CGBitmapInfo bitmapInfo);
void CGContextRelease(CGContextRef c);
ubyte* CGBitmapContextGetData(CGContextRef c);
CGImageRef CGBitmapContextCreateImage(CGContextRef c);
size_t CGBitmapContextGetWidth(CGContextRef c);
size_t CGBitmapContextGetHeight(CGContextRef c);
CGColorSpaceRef CGColorSpaceCreateDeviceRGB();
void CGColorSpaceRelease(CGColorSpaceRef cs);
void CGContextSetRGBStrokeColor(CGContextRef c,
float red, float green, float blue,
float alpha);
void CGContextSetRGBFillColor(CGContextRef c,
float red, float green, float blue,
float alpha);
void CGContextDrawImage(CGContextRef c, CGRect rect, CGImageRef image);
void CGContextShowTextAtPoint(CGContextRef c, float x, float y,
const(char)* str, size_t length);
void CGContextStrokeLineSegments(CGContextRef c,
const(CGPoint)* points, size_t count);
void CGContextBeginPath(CGContextRef c);
void CGContextDrawPath(CGContextRef c, CGPathDrawingMode mode);
void CGContextAddEllipseInRect(CGContextRef c, CGRect rect);
void CGContextAddArc(CGContextRef c, float x, float y, float radius,
float startAngle, float endAngle, int clockwise);
void CGContextAddRect(CGContextRef c, CGRect rect);
void CGContextAddLines(CGContextRef c,
const(CGPoint)* points, size_t count);
void CGContextSaveGState(CGContextRef c);
void CGContextRestoreGState(CGContextRef c);
void CGContextSelectFont(CGContextRef c, const(char)* name, float size,
uint textEncoding);
CGAffineTransform CGContextGetTextMatrix(CGContextRef c);
void CGContextSetTextMatrix(CGContextRef c, CGAffineTransform t);
void CGImageRelease(CGImageRef image);
}
private:
// A convenient method to create a CFString (=NSString) from a D string.
CFStringRef createCFString(string str) {
return CFStringCreateWithBytes(null, str.ptr, cast(int) str.length,
kCFStringEncodingUTF8, false);
}
// Objective-C calls.
RetType objc_msgSend_specialized(string selector, RetType, T...)(id self, T args) {
auto _cmd = sel_registerName(selector.ptr);
alias extern(C) RetType function(id, SEL, T) ExpectedType;
return (cast(ExpectedType)&objc_msgSend)(self, _cmd, args);
}
RetType objc_msgSend_classMethod(string selector, RetType, T...)(const(char)* className, T args) {
auto _cmd = sel_registerName(selector.ptr);
auto cls = objc_getClass(className);
alias extern(C) RetType function(id, SEL, T) ExpectedType;
return (cast(ExpectedType)&objc_msgSend)(cls, _cmd, args);
}
RetType objc_msgSend_classMethod(string className, string selector, RetType, T...)(T args) {
return objc_msgSend_classMethod!(selector, RetType, T)(className.ptr, args);
}
alias objc_msgSend_specialized!("setNeedsDisplay:", void, BOOL) setNeedsDisplay;
alias objc_msgSend_classMethod!("alloc", id) alloc;
alias objc_msgSend_specialized!("initWithContentRect:styleMask:backing:defer:",
id, NSRect, size_t, size_t, BOOL) initWithContentRect;
alias objc_msgSend_specialized!("setTitle:", void, CFStringRef) setTitle;
alias objc_msgSend_specialized!("center", void) center;
alias objc_msgSend_specialized!("initWithFrame:", id, NSRect) initWithFrame;
alias objc_msgSend_specialized!("setContentView:", void, id) setContentView;
alias objc_msgSend_specialized!("release", void) release;
alias objc_msgSend_classMethod!("NSColor", "whiteColor", id) whiteNSColor;
alias objc_msgSend_specialized!("setBackgroundColor:", void, id) setBackgroundColor;
alias objc_msgSend_specialized!("makeKeyAndOrderFront:", void, id) makeKeyAndOrderFront;
alias objc_msgSend_specialized!("invalidate", void) invalidate;
alias objc_msgSend_specialized!("close", void) close;
alias objc_msgSend_classMethod!("NSTimer", "scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:",
id, double, id, SEL, id, BOOL) scheduledTimer;
alias objc_msgSend_specialized!("run", void) run;
alias objc_msgSend_classMethod!("NSGraphicsContext", "currentContext",
id) currentNSGraphicsContext;
alias objc_msgSend_specialized!("graphicsPort", CGContextRef) graphicsPort;
alias objc_msgSend_specialized!("characters", CFStringRef) characters;
alias objc_msgSend_specialized!("superclass", Class) superclass;
alias objc_msgSend_specialized!("init", id) init;
alias objc_msgSend_specialized!("addItem:", void, id) addItem;
alias objc_msgSend_specialized!("setMainMenu:", void, id) setMainMenu;
alias objc_msgSend_specialized!("initWithTitle:action:keyEquivalent:",
id, CFStringRef, SEL, CFStringRef) initWithTitle;
alias objc_msgSend_specialized!("setSubmenu:", void, id) setSubmenu;
alias objc_msgSend_specialized!("setDelegate:", void, id) setDelegate;
alias objc_msgSend_specialized!("activateIgnoringOtherApps:",
void, BOOL) activateIgnoringOtherApps;
alias objc_msgSend_classMethod!("NSApplication", "sharedApplication",
id) sharedNSApplication;
alias objc_msgSend_specialized!("setActivationPolicy:", void, ptrdiff_t) setActivationPolicy;
} else static assert(0, "Unsupported operating system");
version(OSXCocoa) {
// I don't know anything about the Mac, but a couple years ago, KennyTM on the newsgroup wrote this for me
//
// http://forum.dlang.org/thread/innr0v$1deh$1@digitalmars.com?page=4#post-int88l:24uaf:241:40digitalmars.com
// https://github.com/kennytm/simpledisplay.d/blob/osx/simpledisplay.d
//
// and it is about time I merged it in here. It is available with -version=OSXCocoa until someone tests it for me!
// Probably won't even fully compile right now
import std.math : PI;
import std.algorithm : map;
import std.array : array;
alias SimpleWindow NativeWindowHandle;
alias void delegate(id) NativeEventHandler;
__gshared Ivar simpleWindowIvar;
enum KEY_ESCAPE = 27;
mixin template NativeImageImplementation() {
CGContextRef context;
ubyte* rawData;
final:
void convertToRgbaBytes(ubyte[] where) {
assert(where.length == this.width * this.height * 4);
// if rawData had a length....
//assert(rawData.length == where.length);
for(int idx = 0; idx < where.length; idx += 4) {
auto alpha = rawData[idx + 3];
if(alpha == 255) {
where[idx + 0] = rawData[idx + 0]; // r
where[idx + 1] = rawData[idx + 1]; // g
where[idx + 2] = rawData[idx + 2]; // b
where[idx + 3] = rawData[idx + 3]; // a
} else {
where[idx + 0] = cast(ubyte)(rawData[idx + 0] * 255 / alpha); // r
where[idx + 1] = cast(ubyte)(rawData[idx + 1] * 255 / alpha); // g
where[idx + 2] = cast(ubyte)(rawData[idx + 2] * 255 / alpha); // b
where[idx + 3] = rawData[idx + 3]; // a
}
}
}
void setFromRgbaBytes(in ubyte[] where) {
// FIXME: this is probably wrong
assert(where.length == this.width * this.height * 4);
// if rawData had a length....
//assert(rawData.length == where.length);
for(int idx = 0; idx < where.length; idx += 4) {
auto alpha = rawData[idx + 3];
if(alpha == 255) {
rawData[idx + 0] = where[idx + 0]; // r
rawData[idx + 1] = where[idx + 1]; // g
rawData[idx + 2] = where[idx + 2]; // b
rawData[idx + 3] = where[idx + 3]; // a
} else {
rawData[idx + 0] = cast(ubyte)(where[idx + 0] * 255 / alpha); // r
rawData[idx + 1] = cast(ubyte)(where[idx + 1] * 255 / alpha); // g
rawData[idx + 2] = cast(ubyte)(where[idx + 2] * 255 / alpha); // b
rawData[idx + 3] = where[idx + 3]; // a
}
}
}
void createImage(int width, int height, bool forcexshm=false) {
auto colorSpace = CGColorSpaceCreateDeviceRGB();
context = CGBitmapContextCreate(null, width, height, 8, 4*width,
colorSpace,
kCGImageAlphaPremultipliedLast
|kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
rawData = CGBitmapContextGetData(context);
}
void dispose() {
CGContextRelease(context);
}
void setPixel(int x, int y, Color c) {
auto offset = (y * width + x) * 4;
if (c.a == 255) {
rawData[offset + 0] = c.r;
rawData[offset + 1] = c.g;
rawData[offset + 2] = c.b;
rawData[offset + 3] = c.a;
} else {
rawData[offset + 0] = cast(ubyte)(c.r*c.a/255);
rawData[offset + 1] = cast(ubyte)(c.g*c.a/255);
rawData[offset + 2] = cast(ubyte)(c.b*c.a/255);
rawData[offset + 3] = c.a;
}
}
}
mixin template NativeScreenPainterImplementation() {
CGContextRef context;
ubyte[4] _outlineComponents;
void create(NativeWindowHandle window) {
context = window.drawingContext;
}
void dispose() {
}
// NotYetImplementedException
Size textSize(in char[] txt) { return Size(32, 16); throw new NotYetImplementedException(); }
void pen(Pen p) {}
void rasterOp(RasterOp op) {}
Pen _activePen;
Color _fillColor;
Rectangle _clipRectangle;
void setClipRectangle(int, int, int, int) {}
void setFont(OperatingSystemFont) {}
int fontHeight() { return 14; }
// end
@property void outlineColor(Color color) {
float alphaComponent = color.a/255.0f;
CGContextSetRGBStrokeColor(context,
color.r/255.0f, color.g/255.0f, color.b/255.0f, alphaComponent);
if (color.a != 255) {
_outlineComponents[0] = cast(ubyte)(color.r*color.a/255);
_outlineComponents[1] = cast(ubyte)(color.g*color.a/255);
_outlineComponents[2] = cast(ubyte)(color.b*color.a/255);
_outlineComponents[3] = color.a;
} else {
_outlineComponents[0] = color.r;
_outlineComponents[1] = color.g;
_outlineComponents[2] = color.b;
_outlineComponents[3] = color.a;
}
}
@property void fillColor(Color color) {
CGContextSetRGBFillColor(context,
color.r/255.0f, color.g/255.0f, color.b/255.0f, color.a/255.0f);
}
void drawImage(int x, int y, Image image, int ulx, int upy, int width, int height) {
// NotYetImplementedException for upper left/width/height
auto cgImage = CGBitmapContextCreateImage(image.context);
auto size = CGSize(CGBitmapContextGetWidth(image.context),
CGBitmapContextGetHeight(image.context));
CGContextDrawImage(context, CGRect(CGPoint(x, y), size), cgImage);
CGImageRelease(cgImage);
}
version(OSXCocoa) {} else // NotYetImplementedException
void drawPixmap(Sprite image, int x, int y) {
// FIXME: is this efficient?
auto cgImage = CGBitmapContextCreateImage(image.context);
auto size = CGSize(CGBitmapContextGetWidth(image.context),
CGBitmapContextGetHeight(image.context));
CGContextDrawImage(context, CGRect(CGPoint(x, y), size), cgImage);
CGImageRelease(cgImage);
}
void drawText(int x, int y, int x2, int y2, in char[] text, uint alignment) {
// FIXME: alignment
if (_outlineComponents[3] != 0) {
CGContextSaveGState(context);
auto invAlpha = 1.0f/_outlineComponents[3];
CGContextSetRGBFillColor(context, _outlineComponents[0]*invAlpha,
_outlineComponents[1]*invAlpha,
_outlineComponents[2]*invAlpha,
_outlineComponents[3]/255.0f);
CGContextShowTextAtPoint(context, x, y, text.ptr, text.length);
// auto cfstr = cast(id)createCFString(text);
// objc_msgSend(cfstr, sel_registerName("drawAtPoint:withAttributes:"),
// NSPoint(x, y), null);
// CFRelease(cfstr);
CGContextRestoreGState(context);
}
}
void drawPixel(int x, int y) {
auto rawData = CGBitmapContextGetData(context);
auto width = CGBitmapContextGetWidth(context);
auto height = CGBitmapContextGetHeight(context);
auto offset = ((height - y - 1) * width + x) * 4;
rawData[offset .. offset+4] = _outlineComponents;
}
void drawLine(int x1, int y1, int x2, int y2) {
CGPoint[2] linePoints;
linePoints[0] = CGPoint(x1, y1);
linePoints[1] = CGPoint(x2, y2);
CGContextStrokeLineSegments(context, linePoints.ptr, linePoints.length);
}
void drawRectangle(int x, int y, int width, int height) {
CGContextBeginPath(context);
auto rect = CGRect(CGPoint(x, y), CGSize(width, height));
CGContextAddRect(context, rect);
CGContextDrawPath(context, CGPathDrawingMode.kCGPathFillStroke);
}
void drawEllipse(int x1, int y1, int x2, int y2) {
CGContextBeginPath(context);
auto rect = CGRect(CGPoint(x1, y1), CGSize(x2-x1, y2-y1));
CGContextAddEllipseInRect(context, rect);
CGContextDrawPath(context, CGPathDrawingMode.kCGPathFillStroke);
}
void drawArc(int x1, int y1, int width, int height, int start, int finish) {
// @@@BUG@@@ Does not support elliptic arc (width != height).
CGContextBeginPath(context);
CGContextAddArc(context, x1+width*0.5f, y1+height*0.5f, width,
start*PI/(180*64), finish*PI/(180*64), 0);
CGContextDrawPath(context, CGPathDrawingMode.kCGPathFillStroke);
}
void drawPolygon(Point[] intPoints) {
CGContextBeginPath(context);
auto points = array(map!(CGPoint.fromTuple)(intPoints));
CGContextAddLines(context, points.ptr, points.length);
CGContextDrawPath(context, CGPathDrawingMode.kCGPathFillStroke);
}
}
mixin template NativeSimpleWindowImplementation() {
void createWindow(int width, int height, string title, OpenGlOptions opengl, SimpleWindow parent) {
synchronized {
if (NSApp == null) initializeApp();
}
auto contentRect = NSRect(NSPoint(0, 0), NSSize(width, height));
// create the window.
window = initWithContentRect(alloc("NSWindow"),
contentRect,
NSTitledWindowMask
|NSClosableWindowMask
|NSMiniaturizableWindowMask
|NSResizableWindowMask,
NSBackingStoreBuffered,
true);
// set the title & move the window to center.
auto windowTitle = createCFString(title);
setTitle(window, windowTitle);
CFRelease(windowTitle);
center(window);
// create area to draw on.
auto colorSpace = CGColorSpaceCreateDeviceRGB();
drawingContext = CGBitmapContextCreate(null, width, height,
8, 4*width, colorSpace,
kCGImageAlphaPremultipliedLast
|kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextSelectFont(drawingContext, "Lucida Grande", 12.0f, 1);
auto matrix = CGContextGetTextMatrix(drawingContext);
matrix.c = -matrix.c;
matrix.d = -matrix.d;
CGContextSetTextMatrix(drawingContext, matrix);
// create the subview that things will be drawn on.
view = initWithFrame(alloc("SDGraphicsView"), contentRect);
setContentView(window, view);
object_setIvar(view, simpleWindowIvar, cast(id)this);
release(view);
setBackgroundColor(window, whiteNSColor);
makeKeyAndOrderFront(window, null);
}
void dispose() {
closeWindow();
release(window);
}
void closeWindow() {
invalidate(timer);
.close(window);
}
ScreenPainter getPainter() {
return ScreenPainter(this, this);
}
id window;
id timer;
id view;
CGContextRef drawingContext;
}
extern(C) {
private:
BOOL returnTrue3(id self, SEL _cmd, id app) {
return true;
}
BOOL returnTrue2(id self, SEL _cmd) {
return true;
}
void pulse(id self, SEL _cmd) {
auto simpleWindow = cast(SimpleWindow)object_getIvar(self, simpleWindowIvar);
simpleWindow.handlePulse();
setNeedsDisplay(self, true);
}
void drawRect(id self, SEL _cmd, NSRect rect) {
auto simpleWindow = cast(SimpleWindow)object_getIvar(self, simpleWindowIvar);
auto curCtx = graphicsPort(currentNSGraphicsContext);
auto cgImage = CGBitmapContextCreateImage(simpleWindow.drawingContext);
auto size = CGSize(CGBitmapContextGetWidth(simpleWindow.drawingContext),
CGBitmapContextGetHeight(simpleWindow.drawingContext));
CGContextDrawImage(curCtx, CGRect(CGPoint(0, 0), size), cgImage);
CGImageRelease(cgImage);
}
void keyDown(id self, SEL _cmd, id event) {
auto simpleWindow = cast(SimpleWindow)object_getIvar(self, simpleWindowIvar);
// the event may have multiple characters, and we send them all at
// once.
if (simpleWindow.handleCharEvent || simpleWindow.handleKeyEvent) {
auto chars = characters(event);
auto range = CFRange(0, CFStringGetLength(chars));
auto buffer = new char[range.length*3];
long actualLength;
CFStringGetBytes(chars, range, kCFStringEncodingUTF8, 0, false,
buffer.ptr, cast(int) buffer.length, &actualLength);
foreach (dchar dc; buffer[0..actualLength]) {
if (simpleWindow.handleCharEvent)
simpleWindow.handleCharEvent(dc);
// NotYetImplementedException
//if (simpleWindow.handleKeyEvent)
//simpleWindow.handleKeyEvent(KeyEvent(dc)); // FIXME: what about keyUp?
}
}
// the event's 'keyCode' is hardware-dependent. I don't think people
// will like it. Let's leave it to the native handler.
// perform the default action.
auto superData = objc_super(self, superclass(self));
alias extern(C) void function(objc_super*, SEL, id) T;
(cast(T)&objc_msgSendSuper)(&superData, _cmd, event);
}
}
// initialize the app so that it can be interacted with the user.
// based on http://cocoawithlove.com/2010/09/minimalist-cocoa-programming.html
private void initializeApp() {
// push an autorelease pool to avoid leaking.
init(alloc("NSAutoreleasePool"));
// create a new NSApp instance
sharedNSApplication;
setActivationPolicy(NSApp, NSApplicationActivationPolicyRegular);
// create the "Quit" menu.
auto menuBar = init(alloc("NSMenu"));
auto appMenuItem = init(alloc("NSMenuItem"));
addItem(menuBar, appMenuItem);
setMainMenu(NSApp, menuBar);
release(appMenuItem);
release(menuBar);
auto appMenu = init(alloc("NSMenu"));
auto quitTitle = createCFString("Quit");
auto q = createCFString("q");
auto quitItem = initWithTitle(alloc("NSMenuItem"),
quitTitle, sel_registerName("terminate:"), q);
addItem(appMenu, quitItem);
setSubmenu(appMenuItem, appMenu);
release(quitItem);
release(appMenu);
CFRelease(q);
CFRelease(quitTitle);
// assign a delegate for the application, allow it to quit when the last
// window is closed.
auto delegateClass = objc_allocateClassPair(objc_getClass("NSObject"),
"SDWindowCloseDelegate", 0);
class_addMethod(delegateClass,
sel_registerName("applicationShouldTerminateAfterLastWindowClosed:"),
&returnTrue3, "c@:@");
objc_registerClassPair(delegateClass);
auto appDelegate = init(alloc("SDWindowCloseDelegate"));
setDelegate(NSApp, appDelegate);
activateIgnoringOtherApps(NSApp, true);
// create a new view that draws the graphics and respond to keyDown
// events.
auto viewClass = objc_allocateClassPair(objc_getClass("NSView"),
"SDGraphicsView", (void*).sizeof);
class_addIvar(viewClass, "simpledisplay_simpleWindow",
(void*).sizeof, (void*).alignof, "^v");
class_addMethod(viewClass, sel_registerName("simpledisplay_pulse"),
&pulse, "v@:");
class_addMethod(viewClass, sel_registerName("drawRect:"),
&drawRect, "v@:{NSRect={NSPoint=ff}{NSSize=ff}}");
class_addMethod(viewClass, sel_registerName("isFlipped"),
&returnTrue2, "c@:");
class_addMethod(viewClass, sel_registerName("acceptsFirstResponder"),
&returnTrue2, "c@:");
class_addMethod(viewClass, sel_registerName("keyDown:"),
&keyDown, "v@:@");
objc_registerClassPair(viewClass);
simpleWindowIvar = class_getInstanceVariable(viewClass,
"simpledisplay_simpleWindow");
}
}
version(without_opengl) {} else
extern(System) nothrow @nogc {
//enum uint GL_VERSION = 0x1F02;
//const(char)* glGetString (/*GLenum*/uint);
version(X11) {
static if (!SdpyIsUsingIVGLBinds) {
struct __GLXFBConfigRec {}
alias GLXFBConfig = __GLXFBConfigRec*;
enum GLX_X_RENDERABLE = 0x8012;
enum GLX_DRAWABLE_TYPE = 0x8010;
enum GLX_RENDER_TYPE = 0x8011;
enum GLX_X_VISUAL_TYPE = 0x22;
enum GLX_TRUE_COLOR = 0x8002;
enum GLX_WINDOW_BIT = 0x00000001;
enum GLX_RGBA_BIT = 0x00000001;
enum GLX_COLOR_INDEX_BIT = 0x00000002;
enum GLX_SAMPLE_BUFFERS = 0x186a0;
enum GLX_SAMPLES = 0x186a1;
enum GLX_CONTEXT_MAJOR_VERSION_ARB = 0x2091;
enum GLX_CONTEXT_MINOR_VERSION_ARB = 0x2092;
GLXFBConfig* glXChooseFBConfig (Display*, int, int*, int*);
int glXGetFBConfigAttrib (Display*, GLXFBConfig, int, int*);
XVisualInfo* glXGetVisualFromFBConfig (Display*, GLXFBConfig);
char* glXQueryExtensionsString (Display*, int);
void* glXGetProcAddress (const(char)*);
alias glbindGetProcAddress = glXGetProcAddress;
}
// GLX_EXT_swap_control
alias glXSwapIntervalEXT = void function (Display* dpy, /*GLXDrawable*/Drawable drawable, int interval);
private __gshared glXSwapIntervalEXT _glx_swapInterval_fn = null;
//k8: ugly code to prevent warnings when sdpy is compiled into .a
extern(System) {
alias glXCreateContextAttribsARB_fna = GLXContext function (Display *dpy, GLXFBConfig config, GLXContext share_context, /*Bool*/int direct, const(int)* attrib_list);
}
private __gshared /*glXCreateContextAttribsARB_fna*/void* glXCreateContextAttribsARBFn = cast(void*)1; //HACK!
// this made public so we don't have to get it again and again
public bool glXCreateContextAttribsARB_present () {
if (glXCreateContextAttribsARBFn is cast(void*)1) {
// get it
glXCreateContextAttribsARBFn = cast(void*)glbindGetProcAddress("glXCreateContextAttribsARB");
//{ import core.stdc.stdio; printf("checking glXCreateContextAttribsARB: %shere\n", (glXCreateContextAttribsARBFn !is null ? "".ptr : "not ".ptr)); }
}
return (glXCreateContextAttribsARBFn !is null);
}
// this made public so we don't have to get it again and again
public GLXContext glXCreateContextAttribsARB (Display *dpy, GLXFBConfig config, GLXContext share_context, /*Bool*/int direct, const(int)* attrib_list) {
if (!glXCreateContextAttribsARB_present()) assert(0, "glXCreateContextAttribsARB is not present");
return (cast(glXCreateContextAttribsARB_fna)glXCreateContextAttribsARBFn)(dpy, config, share_context, direct, attrib_list);
}
void glxSetVSync (Display* dpy, /*GLXDrawable*/Drawable drawable, bool wait) {
if (cast(void*)_glx_swapInterval_fn is cast(void*)1) return;
if (_glx_swapInterval_fn is null) {
_glx_swapInterval_fn = cast(glXSwapIntervalEXT)glXGetProcAddress("glXSwapIntervalEXT");
if (_glx_swapInterval_fn is null) {
_glx_swapInterval_fn = cast(glXSwapIntervalEXT)1;
return;
}
version(sdddd) { import std.stdio; writeln("glXSwapIntervalEXT found!"); }
}
_glx_swapInterval_fn(dpy, drawable, (wait ? 1 : 0));
}
} else version(Windows) {
static if (!SdpyIsUsingIVGLBinds) {
enum GL_TRUE = 1;
enum GL_FALSE = 0;
alias int GLint;
public void* glbindGetProcAddress (const(char)* name) {
void* res = wglGetProcAddress(name);
if (res is null) {
//{ import core.stdc.stdio; printf("GL: '%s' not found (0)\n", name); }
import core.sys.windows.windef, core.sys.windows.winbase;
__gshared HINSTANCE dll = null;
if (dll is null) {
dll = LoadLibraryA("opengl32.dll");
if (dll is null) return null; // <32, but idc
}
res = GetProcAddress(dll, name);
}
//{ import core.stdc.stdio; printf(" GL: '%s' is 0x%08x\n", name, cast(uint)res); }
return res;
}
}
enum WGL_CONTEXT_MAJOR_VERSION_ARB = 0x2091;
enum WGL_CONTEXT_MINOR_VERSION_ARB = 0x2092;
enum WGL_CONTEXT_LAYER_PLANE_ARB = 0x2093;
enum WGL_CONTEXT_FLAGS_ARB = 0x2094;
enum WGL_CONTEXT_PROFILE_MASK_ARB = 0x9126;
enum WGL_CONTEXT_DEBUG_BIT_ARB = 0x0001;
enum WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB = 0x0002;
enum WGL_CONTEXT_CORE_PROFILE_BIT_ARB = 0x00000001;
enum WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB = 0x00000002;
alias wglCreateContextAttribsARB_fna = HGLRC function (HDC hDC, HGLRC hShareContext, const(int)* attribList);
__gshared wglCreateContextAttribsARB_fna wglCreateContextAttribsARB = null;
void wglInitOtherFunctions () {
if (wglCreateContextAttribsARB is null) {
wglCreateContextAttribsARB = cast(wglCreateContextAttribsARB_fna)glbindGetProcAddress("wglCreateContextAttribsARB");
}
}
}
static if (!SdpyIsUsingIVGLBinds) {
void glGetIntegerv(int, void*);
void glMatrixMode(int);
void glPushMatrix();
void glLoadIdentity();
void glOrtho(double, double, double, double, double, double);
void glFrustum(double, double, double, double, double, double);
void gluLookAt(double, double, double, double, double, double, double, double, double);
void gluPerspective(double, double, double, double);
void glPopMatrix();
void glEnable(int);
void glDisable(int);
void glClear(int);
void glBegin(int);
void glVertex2f(float, float);
void glVertex3f(float, float, float);
void glEnd();
void glColor3b(byte, byte, byte);
void glColor3ub(ubyte, ubyte, ubyte);
void glColor4b(byte, byte, byte, byte);
void glColor4ub(ubyte, ubyte, ubyte, ubyte);
void glColor3i(int, int, int);
void glColor3ui(uint, uint, uint);
void glColor4i(int, int, int, int);
void glColor4ui(uint, uint, uint, uint);
void glColor3f(float, float, float);
void glColor4f(float, float, float, float);
void glTranslatef(float, float, float);
void glScalef(float, float, float);
void glSecondaryColor3b(byte, byte, byte);
void glSecondaryColor3ub(ubyte, ubyte, ubyte);
void glSecondaryColor3i(int, int, int);
void glSecondaryColor3ui(uint, uint, uint);
void glSecondaryColor3f(float, float, float);
void glDrawElements(int, int, int, void*);
void glRotatef(float, float, float, float);
uint glGetError();
void glDeleteTextures(int, uint*);
char* gluErrorString(uint);
void glRasterPos2i(int, int);
void glDrawPixels(int, int, uint, uint, void*);
void glClearColor(float, float, float, float);
void glGenTextures(uint, uint*);
void glBindTexture(int, int);
void glTexParameteri(uint, uint, int);
void glTexParameterf(uint/*GLenum*/ target, uint/*GLenum*/ pname, float param);
void glTexImage2D(int, int, int, int, int, int, int, int, in void*);
void glTexSubImage2D(uint/*GLenum*/ target, int level, int xoffset, int yoffset,
/*GLsizei*/int width, /*GLsizei*/int height,
uint/*GLenum*/ format, uint/*GLenum*/ type, in void* pixels);
void glTextureSubImage2D(uint texture, int level, int xoffset, int yoffset,
/*GLsizei*/int width, /*GLsizei*/int height,
uint/*GLenum*/ format, uint/*GLenum*/ type, in void* pixels);
void glTexEnvf(uint/*GLenum*/ target, uint/*GLenum*/ pname, float param);
void glTexCoord2f(float, float);
void glVertex2i(int, int);
void glBlendFunc (int, int);
void glDepthFunc (int);
void glViewport(int, int, int, int);
void glClearDepth(double);
void glReadBuffer(uint);
void glReadPixels(int, int, int, int, int, int, void*);
void glFlush();
void glFinish();
enum uint GL_FRONT = 0x0404;
enum uint GL_BLEND = 0x0be2;
enum uint GL_SRC_ALPHA = 0x0302;
enum uint GL_ONE_MINUS_SRC_ALPHA = 0x0303;
enum uint GL_LEQUAL = 0x0203;
enum uint GL_UNSIGNED_BYTE = 0x1401;
enum uint GL_RGB = 0x1907;
enum uint GL_BGRA = 0x80e1;
enum uint GL_RGBA = 0x1908;
enum uint GL_TEXTURE_2D = 0x0DE1;
enum uint GL_TEXTURE_MIN_FILTER = 0x2801;
enum uint GL_NEAREST = 0x2600;
enum uint GL_LINEAR = 0x2601;
enum uint GL_TEXTURE_MAG_FILTER = 0x2800;
enum uint GL_TEXTURE_WRAP_S = 0x2802;
enum uint GL_TEXTURE_WRAP_T = 0x2803;
enum uint GL_REPEAT = 0x2901;
enum uint GL_CLAMP = 0x2900;
enum uint GL_CLAMP_TO_EDGE = 0x812F;
enum uint GL_CLAMP_TO_BORDER = 0x812D;
enum uint GL_DECAL = 0x2101;
enum uint GL_MODULATE = 0x2100;
enum uint GL_TEXTURE_ENV = 0x2300;
enum uint GL_TEXTURE_ENV_MODE = 0x2200;
enum uint GL_REPLACE = 0x1E01;
enum uint GL_LIGHTING = 0x0B50;
enum uint GL_DITHER = 0x0BD0;
enum uint GL_NO_ERROR = 0;
enum int GL_VIEWPORT = 0x0BA2;
enum int GL_MODELVIEW = 0x1700;
enum int GL_TEXTURE = 0x1702;
enum int GL_PROJECTION = 0x1701;
enum int GL_DEPTH_TEST = 0x0B71;
enum int GL_COLOR_BUFFER_BIT = 0x00004000;
enum int GL_ACCUM_BUFFER_BIT = 0x00000200;
enum int GL_DEPTH_BUFFER_BIT = 0x00000100;
enum uint GL_STENCIL_BUFFER_BIT = 0x00000400;
enum int GL_POINTS = 0x0000;
enum int GL_LINES = 0x0001;
enum int GL_LINE_LOOP = 0x0002;
enum int GL_LINE_STRIP = 0x0003;
enum int GL_TRIANGLES = 0x0004;
enum int GL_TRIANGLE_STRIP = 5;
enum int GL_TRIANGLE_FAN = 6;
enum int GL_QUADS = 7;
enum int GL_QUAD_STRIP = 8;
enum int GL_POLYGON = 9;
}
}
version(linux) {
version(with_eventloop) {} else {
private int epollFd = -1;
void prepareEventLoop() {
if(epollFd != -1)
return; // already initialized, no need to do it again
import ep = core.sys.linux.epoll;
epollFd = ep.epoll_create1(ep.EPOLL_CLOEXEC);
if(epollFd == -1)
throw new Exception("epoll create failure");
}
}
}
version(X11) {
import core.stdc.locale : LC_ALL; // rdmd fix
__gshared bool sdx_isUTF8Locale;
// This whole crap is used to initialize X11 locale, so that you can use XIM methods later.
// Yes, there are people with non-utf locale (it's me, Ketmar!), but XIM (composing) will
// not work right if app/X11 locale is not utf. This sux. That's why all that "utf detection"
// anal magic is here. I (Ketmar) hope you like it.
// We will use `sdx_isUTF8Locale` on XIM creation to enforce UTF-8 locale, so XCompose will
// always return correct unicode symbols. The detection is here 'cause user can change locale
// later.
shared static this () {
import core.stdc.locale : setlocale, LC_ALL, LC_CTYPE;
// this doesn't hurt; it may add some locking, but the speed is still
// allows doing 60 FPS videogames; also, ignore the result, as most
// users will probably won't do mulththreaded X11 anyway (and I (ketmar)
// never seen this failing).
if (XInitThreads() == 0) { import core.stdc.stdio; fprintf(stderr, "XInitThreads() failed!\n"); }
setlocale(LC_ALL, "");
// check if out locale is UTF-8
auto lct = setlocale(LC_CTYPE, null);
if (lct is null) {
sdx_isUTF8Locale = false;
} else {
for (size_t idx = 0; lct[idx] && lct[idx+1] && lct[idx+2]; ++idx) {
if ((lct[idx+0] == 'u' || lct[idx+0] == 'U') &&
(lct[idx+1] == 't' || lct[idx+1] == 'T') &&
(lct[idx+2] == 'f' || lct[idx+2] == 'F'))
{
sdx_isUTF8Locale = true;
break;
}
}
}
//{ import core.stdc.stdio : stderr, fprintf; fprintf(stderr, "UTF8: %s\n", sdx_isUTF8Locale ? "tan".ptr : "ona".ptr); }
}
}
mixin template ExperimentalTextComponent2() {
/+
Stage 1: get it working monospace
Stage 2: use proportional font
Stage 3: allow changes in inline style
Stage 4: allow new fonts and sizes in the middle
Stage 5: optimize gap buffer
Stage 6: optimize layout
Stage 7: word wrap
Stage 8: justification
Stage 9: editing, selection, etc.
+/
}
// Don't use this yet. When I'm happy with it, I will move it to the
// regular module namespace.
mixin template ExperimentalTextComponent() {
alias Rectangle = arsd.color.Rectangle;
struct ForegroundColor {
Color color;
alias color this;
this(Color c) {
color = c;
}
this(int r, int g, int b, int a = 255) {
color = Color(r, g, b, a);
}
static ForegroundColor opDispatch(string s)() if(__traits(compiles, ForegroundColor(mixin("Color." ~ s)))) {
return ForegroundColor(mixin("Color." ~ s));
}
}
struct BackgroundColor {
Color color;
alias color this;
this(Color c) {
color = c;
}
this(int r, int g, int b, int a = 255) {
color = Color(r, g, b, a);
}
static BackgroundColor opDispatch(string s)() if(__traits(compiles, BackgroundColor(mixin("Color." ~ s)))) {
return BackgroundColor(mixin("Color." ~ s));
}
}
static class InlineElement {
string text;
BlockElement containingBlock;
Color color = Color.black;
Color backgroundColor = Color.transparent;
ushort styles;
string font;
int fontSize;
int lineHeight;
void* identifier;
Rectangle boundingBox;
int[] letterXs; // FIXME: maybe i should do bounding boxes for every character
bool isMergeCompatible(InlineElement other) {
return
containingBlock is other.containingBlock &&
color == other.color &&
backgroundColor == other.backgroundColor &&
styles == other.styles &&
font == other.font &&
fontSize == other.fontSize &&
lineHeight == other.lineHeight &&
true;
}
int xOfIndex(size_t index) {
if(index < letterXs.length)
return letterXs[index];
else
return boundingBox.right;
}
InlineElement clone() {
auto ie = new InlineElement();
ie.tupleof = this.tupleof;
return ie;
}
InlineElement getPreviousInlineElement() {
InlineElement prev = null;
foreach(ie; this.containingBlock.parts) {
if(ie is this)
break;
prev = ie;
}
if(prev is null) {
BlockElement pb;
BlockElement cb = this.containingBlock;
moar:
foreach(ie; this.containingBlock.containingLayout.blocks) {
if(ie is cb)
break;
pb = ie;
}
if(pb is null)
return null;
if(pb.parts.length == 0) {
cb = pb;
goto moar;
}
prev = pb.parts[$-1];
}
return prev;
}
InlineElement getNextInlineElement() {
InlineElement next = null;
foreach(idx, ie; this.containingBlock.parts) {
if(ie is this) {
if(idx + 1 < this.containingBlock.parts.length)
next = this.containingBlock.parts[idx + 1];
break;
}
}
if(next is null) {
BlockElement n;
foreach(idx, ie; this.containingBlock.containingLayout.blocks) {
if(ie is this.containingBlock) {
if(idx + 1 < this.containingBlock.containingLayout.blocks.length)
n = this.containingBlock.containingLayout.blocks[idx + 1];
break;
}
}
if(n is null)
return null;
if(n.parts.length)
next = n.parts[0];
else {} // FIXME
}
return next;
}
}
// Block elements are used entirely for positioning inline elements,
// which are the things that are actually drawn.
class BlockElement {
InlineElement[] parts;
uint alignment;
int whiteSpace; // pre, pre-wrap, wrap
TextLayout containingLayout;
// inputs
Point where;
Size minimumSize;
Size maximumSize;
Rectangle[] excludedBoxes; // like if you want it to write around a floated image or something. Coordinates are relative to the bounding box.
void* identifier;
Rectangle margin;
Rectangle padding;
// outputs
Rectangle[] boundingBoxes;
}
struct TextIdentifyResult {
InlineElement element;
int offset;
private TextIdentifyResult fixupNewline() {
if(element !is null && offset < element.text.length && element.text[offset] == '\n') {
offset--;
} else if(element !is null && offset == element.text.length && element.text.length > 1 && element.text[$-1] == '\n') {
offset--;
}
return this;
}
}
class TextLayout {
BlockElement[] blocks;
Rectangle boundingBox_;
Rectangle boundingBox() { return boundingBox_; }
void boundingBox(Rectangle r) {
if(r != boundingBox_) {
boundingBox_ = r;
layoutInvalidated = true;
}
}
Rectangle contentBoundingBox() {
Rectangle r;
foreach(block; blocks)
foreach(ie; block.parts) {
if(ie.boundingBox.right > r.right)
r.right = ie.boundingBox.right;
if(ie.boundingBox.bottom > r.bottom)
r.bottom = ie.boundingBox.bottom;
}
return r;
}
BlockElement[] getBlocks() {
return blocks;
}
InlineElement[] getTexts() {
InlineElement[] elements;
foreach(block; blocks)
elements ~= block.parts;
return elements;
}
string getPlainText() {
string text;
foreach(block; blocks)
foreach(part; block.parts)
text ~= part.text;
return text;
}
string getHtml() {
return null; // FIXME
}
this(Rectangle boundingBox) {
this.boundingBox = boundingBox;
}
BlockElement addBlock(InlineElement after = null, Rectangle margin = Rectangle(0, 0, 0, 0), Rectangle padding = Rectangle(0, 0, 0, 0)) {
auto be = new BlockElement();
be.containingLayout = this;
if(after is null)
blocks ~= be;
else {
foreach(idx, b; blocks) {
if(b is after.containingBlock) {
blocks = blocks[0 .. idx + 1] ~ be ~ blocks[idx + 1 .. $];
break;
}
}
}
return be;
}
void clear() {
blocks = null;
selectionStart = selectionEnd = caret = Caret.init;
}
void addText(Args...)(Args args) {
if(blocks.length == 0)
addBlock();
InlineElement ie = new InlineElement();
foreach(idx, arg; args) {
static if(is(typeof(arg) == ForegroundColor))
ie.color = arg;
else static if(is(typeof(arg) == TextFormat)) {
if(arg & 0x8000) // ~TextFormat.something turns it off
ie.styles &= arg;
else
ie.styles |= arg;
} else static if(is(typeof(arg) == string)) {
static if(idx == 0 && args.length > 1)
static assert(0, "Put styles before the string.");
size_t lastLineIndex;
foreach(cidx, char a; arg) {
if(a == '\n') {
ie.text = arg[lastLineIndex .. cidx + 1];
lastLineIndex = cidx + 1;
ie.containingBlock = blocks[$-1];
blocks[$-1].parts ~= ie.clone;
ie.text = null;
} else {
}
}
ie.text = arg[lastLineIndex .. $];
ie.containingBlock = blocks[$-1];
blocks[$-1].parts ~= ie.clone;
caret = Caret(this, blocks[$-1].parts[$-1], cast(int) blocks[$-1].parts[$-1].text.length);
}
}
invalidateLayout();
}
void tryMerge(InlineElement into, InlineElement what) {
if(!into.isMergeCompatible(what)) {
return; // cannot merge, different configs
}
// cool, can merge, bring text together...
into.text ~= what.text;
// and remove what
for(size_t a = 0; a < what.containingBlock.parts.length; a++) {
if(what.containingBlock.parts[a] is what) {
for(size_t i = a; i < what.containingBlock.parts.length - 1; i++)
what.containingBlock.parts[i] = what.containingBlock.parts[i + 1];
what.containingBlock.parts = what.containingBlock.parts[0 .. $-1];
}
}
// FIXME: ensure no other carets have a reference to it
}
/// exact = true means return null if no match. otherwise, get the closest one that makes sense for a mouse click.
TextIdentifyResult identify(int x, int y, bool exact = false) {
TextIdentifyResult inexactMatch;
foreach(block; blocks) {
foreach(part; block.parts) {
if(x >= part.boundingBox.left && x < part.boundingBox.right && y >= part.boundingBox.top && y < part.boundingBox.bottom) {
// FIXME binary search
int tidx;
int lastX;
foreach_reverse(idxo, lx; part.letterXs) {
int idx = cast(int) idxo;
if(lx <= x) {
if(lastX && lastX - x < x - lx)
tidx = idx + 1;
else
tidx = idx;
break;
}
lastX = lx;
}
return TextIdentifyResult(part, tidx).fixupNewline;
} else if(!exact) {
// we're not in the box, but are we on the same line?
if(y >= part.boundingBox.top && y < part.boundingBox.bottom)
inexactMatch = TextIdentifyResult(part, x == 0 ? 0 : cast(int) part.text.length);
}
}
}
if(!exact && inexactMatch is TextIdentifyResult.init && blocks.length && blocks[$-1].parts.length)
return TextIdentifyResult(blocks[$-1].parts[$-1], cast(int) blocks[$-1].parts[$-1].text.length).fixupNewline;
return exact ? TextIdentifyResult.init : inexactMatch.fixupNewline;
}
void moveCaretToPixelCoordinates(int x, int y) {
auto result = identify(x, y);
caret.inlineElement = result.element;
caret.offset = result.offset;
}
void selectToPixelCoordinates(int x, int y) {
auto result = identify(x, y);
if(y < caretLastDrawnY1) {
// on a previous line, carat is selectionEnd
selectionEnd = caret;
selectionStart = Caret(this, result.element, result.offset);
} else if(y > caretLastDrawnY2) {
// on a later line
selectionStart = caret;
selectionEnd = Caret(this, result.element, result.offset);
} else {
// on the same line...
if(x <= caretLastDrawnX) {
selectionEnd = caret;
selectionStart = Caret(this, result.element, result.offset);
} else {
selectionStart = caret;
selectionEnd = Caret(this, result.element, result.offset);
}
}
}
/// Call this if the inputs change. It will reflow everything
void redoLayout(ScreenPainter painter) {
//painter.setClipRectangle(boundingBox);
auto pos = Point(boundingBox.left, boundingBox.top);
int lastHeight;
void nl() {
pos.x = boundingBox.left;
pos.y += lastHeight;
}
foreach(block; blocks) {
nl();
foreach(part; block.parts) {
part.letterXs = null;
auto size = painter.textSize(part.text);
version(Windows)
if(part.text.length && part.text[$-1] == '\n')
size.height /= 2; // windows counts the new line at the end, but we don't want that
part.boundingBox = Rectangle(pos.x, pos.y, pos.x + size.width, pos.y + size.height);
foreach(idx, char c; part.text) {
// FIXME: unicode
part.letterXs ~= painter.textSize(part.text[0 .. idx]).width + pos.x;
}
pos.x += size.width;
if(pos.x >= boundingBox.right) {
pos.y += size.height;
pos.x = boundingBox.left;
lastHeight = 0;
} else {
lastHeight = size.height;
}
if(part.text.length && part.text[$-1] == '\n')
nl();
}
}
layoutInvalidated = false;
}
bool layoutInvalidated = true;
void invalidateLayout() {
layoutInvalidated = true;
}
// FIXME: caret can remain sometimes when inserting
// FIXME: inserting at the beginning once you already have something can eff it up.
void drawInto(ScreenPainter painter, bool focused = false) {
if(layoutInvalidated)
redoLayout(painter);
foreach(block; blocks) {
foreach(part; block.parts) {
painter.outlineColor = part.color;
painter.fillColor = part.backgroundColor;
auto pos = part.boundingBox.upperLeft;
auto size = part.boundingBox.size;
painter.drawText(pos, part.text);
if(part.styles & TextFormat.underline)
painter.drawLine(Point(pos.x, pos.y + size.height - 4), Point(pos.x + size.width, pos.y + size.height - 4));
if(part.styles & TextFormat.strikethrough)
painter.drawLine(Point(pos.x, pos.y + size.height/2), Point(pos.x + size.width, pos.y + size.height/2));
}
}
// on every redraw, I will force the caret to be
// redrawn too, in order to eliminate perceived lag
// when moving around with the mouse.
eraseCaret(painter);
if(focused) {
highlightSelection(painter);
drawCaret(painter);
}
}
void highlightSelection(ScreenPainter painter) {
if(selectionStart is selectionEnd)
return; // no selection
if(selectionStart.inlineElement is null) return;
if(selectionEnd.inlineElement is null) return;
assert(selectionStart.inlineElement !is null);
assert(selectionEnd.inlineElement !is null);
painter.rasterOp = RasterOp.xor;
painter.outlineColor = Color.transparent;
painter.fillColor = Color(255, 255, 127);
auto at = selectionStart.inlineElement;
auto atOffset = selectionStart.offset;
bool done;
while(at) {
auto box = at.boundingBox;
if(atOffset < at.letterXs.length)
box.left = at.letterXs[atOffset];
if(at is selectionEnd.inlineElement) {
if(selectionEnd.offset < at.letterXs.length)
box.right = at.letterXs[selectionEnd.offset];
done = true;
}
painter.drawRectangle(box.upperLeft, box.width, box.height);
if(done)
break;
at = at.getNextInlineElement();
atOffset = 0;
}
}
int caretLastDrawnX, caretLastDrawnY1, caretLastDrawnY2;
bool caretShowingOnScreen = false;
void drawCaret(ScreenPainter painter) {
//painter.setClipRectangle(boundingBox);
int x, y1, y2;
if(caret.inlineElement is null) {
x = boundingBox.left;
y1 = boundingBox.top + 2;
y2 = boundingBox.top + painter.fontHeight;
} else {
x = caret.inlineElement.xOfIndex(caret.offset);
y1 = caret.inlineElement.boundingBox.top + 2;
y2 = caret.inlineElement.boundingBox.bottom - 2;
}
if(caretShowingOnScreen && (x != caretLastDrawnX || y1 != caretLastDrawnY1 || y2 != caretLastDrawnY2))
eraseCaret(painter);
painter.pen = Pen(Color.white, 1);
painter.rasterOp = RasterOp.xor;
painter.drawLine(
Point(x, y1),
Point(x, y2)
);
painter.rasterOp = RasterOp.normal;
caretShowingOnScreen = !caretShowingOnScreen;
if(caretShowingOnScreen) {
caretLastDrawnX = x;
caretLastDrawnY1 = y1;
caretLastDrawnY2 = y2;
}
}
Rectangle caretBoundingBox() {
int x, y1, y2;
if(caret.inlineElement is null) {
x = boundingBox.left;
y1 = boundingBox.top + 2;
y2 = boundingBox.top + 16;
} else {
x = caret.inlineElement.xOfIndex(caret.offset);
y1 = caret.inlineElement.boundingBox.top + 2;
y2 = caret.inlineElement.boundingBox.bottom - 2;
}
return Rectangle(x, y1, x + 1, y2);
}
void eraseCaret(ScreenPainter painter) {
//painter.setClipRectangle(boundingBox);
if(!caretShowingOnScreen) return;
painter.pen = Pen(Color.white, 1);
painter.rasterOp = RasterOp.xor;
painter.drawLine(
Point(caretLastDrawnX, caretLastDrawnY1),
Point(caretLastDrawnX, caretLastDrawnY2)
);
caretShowingOnScreen = false;
painter.rasterOp = RasterOp.normal;
}
/// Caret movement api
/// These should give the user a logical result based on what they see on screen...
/// thus they locate predominately by *pixels* not char index. (These will generally coincide with monospace fonts tho!)
void moveUp() {
if(caret.inlineElement is null) return;
auto x = caret.inlineElement.xOfIndex(caret.offset);
auto y = caret.inlineElement.boundingBox.top + 2;
y -= caret.inlineElement.boundingBox.bottom - caret.inlineElement.boundingBox.top;
if(y < 0)
return;
auto i = identify(x, y);
if(i.element) {
caret.inlineElement = i.element;
caret.offset = i.offset;
}
}
void moveDown() {
if(caret.inlineElement is null) return;
auto x = caret.inlineElement.xOfIndex(caret.offset);
auto y = caret.inlineElement.boundingBox.bottom - 2;
y += caret.inlineElement.boundingBox.bottom - caret.inlineElement.boundingBox.top;
auto i = identify(x, y);
if(i.element) {
caret.inlineElement = i.element;
caret.offset = i.offset;
}
}
void moveLeft() {
if(caret.inlineElement is null) return;
if(caret.offset)
caret.offset--;
else {
auto p = caret.inlineElement.getPreviousInlineElement();
if(p) {
caret.inlineElement = p;
if(p.text.length && p.text[$-1] == '\n')
caret.offset = cast(int) p.text.length - 1;
else
caret.offset = cast(int) p.text.length;
}
}
}
void moveRight() {
if(caret.inlineElement is null) return;
if(caret.offset < caret.inlineElement.text.length && caret.inlineElement.text[caret.offset] != '\n') {
caret.offset++;
} else {
auto p = caret.inlineElement.getNextInlineElement();
if(p) {
caret.inlineElement = p;
caret.offset = 0;
}
}
}
void moveHome() {
if(caret.inlineElement is null) return;
auto x = 0;
auto y = caret.inlineElement.boundingBox.top + 2;
auto i = identify(x, y);
if(i.element) {
caret.inlineElement = i.element;
caret.offset = i.offset;
}
}
void moveEnd() {
if(caret.inlineElement is null) return;
auto x = int.max;
auto y = caret.inlineElement.boundingBox.top + 2;
auto i = identify(x, y);
if(i.element) {
caret.inlineElement = i.element;
caret.offset = i.offset;
}
}
void movePageUp(ref Caret caret) {}
void movePageDown(ref Caret caret) {}
void moveDocumentStart(ref Caret caret) {
if(blocks.length && blocks[0].parts.length)
caret = Caret(this, blocks[0].parts[0], 0);
else
caret = Caret.init;
}
void moveDocumentEnd(ref Caret caret) {
if(blocks.length) {
auto parts = blocks[$-1].parts;
if(parts.length) {
caret = Caret(this, parts[$-1], cast(int) parts[$-1].text.length);
} else {
caret = Caret.init;
}
} else
caret = Caret.init;
}
void deleteSelection() {
if(selectionStart is selectionEnd)
return;
if(selectionStart.inlineElement is null) return;
if(selectionEnd.inlineElement is null) return;
assert(selectionStart.inlineElement !is null);
assert(selectionEnd.inlineElement !is null);
auto at = selectionStart.inlineElement;
if(selectionEnd.inlineElement is at) {
// same element, need to chop out
at.text = at.text[0 .. selectionStart.offset] ~ at.text[selectionEnd.offset .. $];
at.letterXs = at.letterXs[0 .. selectionStart.offset] ~ at.letterXs[selectionEnd.offset .. $];
selectionEnd.offset -= selectionEnd.offset - selectionStart.offset;
} else {
// different elements, we can do it with slicing
at.text = at.text[0 .. selectionStart.offset];
if(selectionStart.offset < at.letterXs.length)
at.letterXs = at.letterXs[0 .. selectionStart.offset];
at = at.getNextInlineElement();
while(at) {
if(at is selectionEnd.inlineElement) {
at.text = at.text[selectionEnd.offset .. $];
if(selectionEnd.offset < at.letterXs.length)
at.letterXs = at.letterXs[selectionEnd.offset .. $];
selectionEnd.offset = 0;
break;
} else {
auto cfd = at;
cfd.text = null; // delete the whole thing
at = at.getNextInlineElement();
if(cfd.text.length == 0) {
// and remove cfd
for(size_t a = 0; a < cfd.containingBlock.parts.length; a++) {
if(cfd.containingBlock.parts[a] is cfd) {
for(size_t i = a; i < cfd.containingBlock.parts.length - 1; i++)
cfd.containingBlock.parts[i] = cfd.containingBlock.parts[i + 1];
cfd.containingBlock.parts = cfd.containingBlock.parts[0 .. $-1];
}
}
}
}
}
}
caret = selectionEnd;
selectNone();
invalidateLayout();
}
/// Plain text editing api. These work at the current caret inside the selected inline element.
void insert(in char[] text) {
foreach(dchar ch; text)
insert(ch);
}
/// ditto
void insert(dchar ch) {
bool selectionDeleted = false;
if(selectionStart !is selectionEnd) {
deleteSelection();
selectionDeleted = true;
}
if(ch == 127) {
delete_();
return;
}
if(ch == 8) {
if(!selectionDeleted)
backspace();
return;
}
invalidateLayout();
if(ch == 13) ch = 10;
auto e = caret.inlineElement;
if(e is null) {
addText("" ~ cast(char) ch) ; // FIXME
return;
}
if(caret.offset == e.text.length) {
e.text ~= cast(char) ch; // FIXME
caret.offset++;
if(ch == 10) {
auto c = caret.inlineElement.clone;
c.text = null;
c.letterXs = null;
insertPartAfter(c,e);
caret = Caret(this, c, 0);
}
} else {
// FIXME cast char sucks
if(ch == 10) {
auto c = caret.inlineElement.clone;
c.text = e.text[caret.offset .. $];
if(caret.offset < c.letterXs.length)
c.letterXs = e.letterXs[caret.offset .. $]; // FIXME boundingBox
e.text = e.text[0 .. caret.offset] ~ cast(char) ch;
if(caret.offset <= e.letterXs.length) {
e.letterXs = e.letterXs[0 .. caret.offset] ~ 0; // FIXME bounding box
}
insertPartAfter(c,e);
caret = Caret(this, c, 0);
} else {
e.text = e.text[0 .. caret.offset] ~ cast(char) ch ~ e.text[caret.offset .. $];
caret.offset++;
}
}
}
void insertPartAfter(InlineElement what, InlineElement where) {
foreach(idx, p; where.containingBlock.parts) {
if(p is where) {
if(idx + 1 == where.containingBlock.parts.length)
where.containingBlock.parts ~= what;
else
where.containingBlock.parts = where.containingBlock.parts[0 .. idx + 1] ~ what ~ where.containingBlock.parts[idx + 1 .. $];
return;
}
}
}
void cleanupStructures() {
for(size_t i = 0; i < blocks.length; i++) {
auto block = blocks[i];
for(size_t a = 0; a < block.parts.length; a++) {
auto part = block.parts[a];
if(part.text.length == 0) {
for(size_t b = a; b < block.parts.length - 1; b++)
block.parts[b] = block.parts[b+1];
block.parts = block.parts[0 .. $-1];
}
}
if(block.parts.length == 0) {
for(size_t a = i; a < blocks.length - 1; a++)
blocks[a] = blocks[a+1];
blocks = blocks[0 .. $-1];
}
}
}
void backspace() {
try_again:
auto e = caret.inlineElement;
if(e is null)
return;
if(caret.offset == 0) {
auto prev = e.getPreviousInlineElement();
if(prev is null)
return;
auto newOffset = cast(int) prev.text.length;
tryMerge(prev, e);
caret.inlineElement = prev;
caret.offset = prev is null ? 0 : newOffset;
goto try_again;
} else if(caret.offset == e.text.length) {
e.text = e.text[0 .. $-1];
caret.offset--;
} else {
e.text = e.text[0 .. caret.offset - 1] ~ e.text[caret.offset .. $];
caret.offset--;
}
//cleanupStructures();
invalidateLayout();
}
void delete_() {
if(selectionStart !is selectionEnd)
deleteSelection();
else {
auto before = caret;
moveRight();
if(caret != before) {
backspace();
}
}
invalidateLayout();
}
void overstrike() {}
/// Selection API. See also: caret movement.
void selectAll() {
moveDocumentStart(selectionStart);
moveDocumentEnd(selectionEnd);
}
bool selectNone() {
if(selectionStart != selectionEnd) {
selectionStart = selectionEnd = Caret.init;
return true;
}
return false;
}
/// Rich text editing api. These allow you to manipulate the meta data of the current element and add new elements.
/// They will modify the current selection if there is one and will splice one in if needed.
void changeAttributes() {}
/// Text search api. They manipulate the selection and/or caret.
void findText(string text) {}
void findIndex(size_t textIndex) {}
// sample event handlers
void handleEvent(KeyEvent event) {
//if(event.type == KeyEvent.Type.KeyPressed) {
//}
}
void handleEvent(dchar ch) {
}
void handleEvent(MouseEvent event) {
}
bool contentEditable; // can it be edited?
bool contentCaretable; // is there a caret/cursor that moves around in there?
bool contentSelectable; // selectable?
Caret caret;
Caret selectionStart;
Caret selectionEnd;
bool insertMode;
}
struct Caret {
TextLayout layout;
InlineElement inlineElement;
int offset;
}
enum TextFormat : ushort {
// decorations
underline = 1,
strikethrough = 2,
// font selectors
bold = 0x4000 | 1, // weight 700
light = 0x4000 | 2, // weight 300
veryBoldOrLight = 0x4000 | 4, // weight 100 with light, weight 900 with bold
// bold | light is really invalid but should give weight 500
// veryBoldOrLight without one of the others should just give the default for the font; it should be ignored.
italic = 0x4000 | 8,
smallcaps = 0x4000 | 16,
}
void* findFont(string family, int weight, TextFormat formats) {
return null;
}
}
static if(UsingSimpledisplayX11) {
enum _NET_WM_STATE_ADD = 1;
enum _NET_WM_STATE_REMOVE = 0;
enum _NET_WM_STATE_TOGGLE = 2;
/// X-specific. Use [SimpleWindow.requestAttention] instead for most casesl
void demandAttention(SimpleWindow window, bool needs = true) {
auto display = XDisplayConnection.get();
auto atom = XInternAtom(display, "_NET_WM_STATE_DEMANDS_ATTENTION", true);
if(atom == None)
return; // non-failure error
//auto atom2 = GetAtom!"_NET_WM_STATE_SHADED"(display);
XClientMessageEvent xclient;
xclient.type = EventType.ClientMessage;
xclient.window = window.impl.window;
xclient.message_type = GetAtom!"_NET_WM_STATE"(display);
xclient.format = 32;
xclient.data.l[0] = needs ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
xclient.data.l[1] = atom;
//xclient.data.l[2] = atom2;
// [2] == a second property
// [3] == source. 0 == unknown, 1 == app, 2 == else
XSendEvent(
display,
RootWindow(display, DefaultScreen(display)),
false,
EventMask.SubstructureRedirectMask | EventMask.SubstructureNotifyMask,
cast(XEvent*) &xclient
);
/+
XChangeProperty(
display,
window.impl.window,
GetAtom!"_NET_WM_STATE"(display),
XA_ATOM,
32 /* bits */,
PropModeAppend,
&atom,
1);
+/
}
/// X-specific
TrueColorImage getWindowNetWmIcon(Window window) {
auto display = XDisplayConnection.get;
auto data = getX11PropertyData (window, GetAtom!"_NET_WM_ICON"(display), XA_CARDINAL);
if (data.length > arch_ulong.sizeof * 2) {
auto meta = cast(arch_ulong[]) (data[0 .. arch_ulong.sizeof * 2]);
// these are an array of rgba images that we have to convert into pixmaps ourself
int width = cast(int) meta[0];
int height = cast(int) meta[1];
auto bytes = cast(ubyte[]) (data[arch_ulong.sizeof * 2 .. $]);
static if(arch_ulong.sizeof == 4) {
bytes = bytes[0 .. width * height * 4];
alias imageData = bytes;
} else static if(arch_ulong.sizeof == 8) {
bytes = bytes[0 .. width * height * 8];
auto imageData = new ubyte[](4 * width * height);
} else static assert(0);
// this returns ARGB. Remember it is little-endian so
// we have BGRA
// our thing uses RGBA, which in little endian, is ABGR
for(int idx = 0, idx2 = 0; idx < bytes.length; idx += arch_ulong.sizeof, idx2 += 4) {
auto r = bytes[idx + 2];
auto g = bytes[idx + 1];
auto b = bytes[idx + 0];
auto a = bytes[idx + 3];
imageData[idx2 + 0] = r;
imageData[idx2 + 1] = g;
imageData[idx2 + 2] = b;
imageData[idx2 + 3] = a;
}
return new TrueColorImage(width, height, imageData);
}
return null;
}
}
void loadBinNameToWindowClassName () {
import core.stdc.stdlib : realloc;
version(linux) {
// args[0] MAY be empty, so we'll just use this
import core.sys.posix.unistd : readlink;
char[1024] ebuf = void; // 1KB should be enough for everyone!
auto len = readlink("/proc/self/exe", ebuf.ptr, ebuf.length);
if (len < 1) return;
} else /*version(Windows)*/ {
import core.runtime : Runtime;
if (Runtime.args.length == 0 || Runtime.args[0].length == 0) return;
auto ebuf = Runtime.args[0];
auto len = ebuf.length;
}
auto pos = len;
while (pos > 0 && ebuf[pos-1] != '/') --pos;
sdpyWindowClassStr = cast(char*)realloc(sdpyWindowClassStr, len-pos+1);
if (sdpyWindowClassStr is null) return; // oops
sdpyWindowClassStr[0..len-pos+1] = 0; // just in case
sdpyWindowClassStr[0..len-pos] = ebuf[pos..len];
}
/++
An interface representing a font.
This is still MAJOR work in progress.
+/
interface DrawableFont {
void drawString(ScreenPainter painter, Point upperLeft, in char[] text);
}
/++
Loads a true type font using [arsd.ttf]. That module must be compiled
in if you choose to use this function.
Be warned: this can be slow and memory hungry, especially on remote connections
to the X server.
This is still MAJOR work in progress.
+/
DrawableFont arsdTtfFont()(in ubyte[] data, int size) {
import arsd.ttf;
static class ArsdTtfFont : DrawableFont {
TtfFont font;
int size;
this(in ubyte[] data, int size) {
font = TtfFont(data);
this.size = size;
}
Sprite[string] cache;
void drawString(ScreenPainter painter, Point upperLeft, in char[] text) {
Sprite sprite = (text in cache) ? *(text in cache) : null;
auto fg = painter.impl._outlineColor;
auto bg = painter.impl._fillColor;
if(sprite is null) {
int width, height;
auto data = font.renderString(text, size, width, height);
auto image = new TrueColorImage(width, height);
int pos = 0;
foreach(y; 0 .. height)
foreach(x; 0 .. width) {
fg.a = data[0];
bg.a = 255;
auto color = alphaBlend(fg, bg);
image.imageData.bytes[pos++] = color.r;
image.imageData.bytes[pos++] = color.g;
image.imageData.bytes[pos++] = color.b;
image.imageData.bytes[pos++] = data[0];
data = data[1 .. $];
}
assert(data.length == 0);
sprite = new Sprite(painter.window, Image.fromMemoryImage(image));
cache[text.idup] = sprite;
}
sprite.drawAt(painter, upperLeft);
}
}
return new ArsdTtfFont(data, size);
}
class NotYetImplementedException : Exception {
this(string file = __FILE__, size_t line = __LINE__) {
super("Not yet implemented", file, line);
}
}
private alias scriptable = arsd_jsvar_compatible;
| D |
module util.random;
import std.range;
import std.base64;
import std.random;
import std.algorithm;
string randomBase64(size_t length) {
rndGen.seed(unpredictableSeed);
auto bytes = rndGen.map!(a => cast(ubyte)a).take(length);
return Base64URL.encode(bytes);
}
| D |
E: c56, c28, c53, c17, c54, c37, c65, c6, c2, c40, c14, c64, c62, c12, c29, c43, c23, c59, c61, c18, c36, c7, c52, c48, c35, c27, c8, c13, c26, c47, c50, c22, c31, c15, c33, c42, c0, c67, c49, c38, c16, c5, c24, c45, c60, c30, c4, c55, c20, c3, c11, c1, c39.
p8(E,E)
c56,c28
c53,c17
c54,c37
c65,c2
c14,c64
c65,c64
c14,c28
c29,c56
c43,c23
c59,c61
c36,c7
c52,c64
c54,c48
c6,c29
c52,c17
c61,c48
c52,c27
c6,c27
c8,c13
c14,c26
c47,c50
c22,c7
c31,c36
c43,c15
c14,c17
c53,c62
c64,c64
c61,c28
c64,c17
c0,c17
c14,c27
c64,c62
c36,c28
c36,c64
c7,c38
c53,c27
c14,c43
c16,c5
c64,c48
c36,c43
c36,c67
c54,c43
c14,c67
c52,c62
c54,c27
c14,c48
c56,c48
c35,c6
c61,c67
c53,c26
c48,c2
c64,c26
c56,c67
c52,c43
c64,c4
c22,c28
c53,c48
c64,c27
c22,c62
c55,c6
c36,c17
c6,c67
c53,c7
c20,c3
c61,c7
c61,c27
c54,c20
c29,c11
c52,c48
c61,c26
c56,c17
c56,c27
c56,c43
c24,c53
c22,c52
c38,c38
c6,c64
c54,c64
c6,c28
c64,c43
c52,c67
c6,c7
c54,c62
c64,c18
c54,c17
.
p9(E,E)
c65,c6
c40,c54
c14,c14
c12,c52
c65,c61
c24,c56
c62,c64
c30,c64
c62,c36
c12,c14
c1,c64
.
p1(E,E)
c62,c12
c33,c42
c62,c35
c38,c48
.
p7(E,E)
c18,c53
.
p2(E,E)
c62,c35
c62,c62
c67,c49
c64,c64
c43,c33
c67,c67
c7,c60
c7,c7
c26,c26
c28,c28
.
p5(E,E)
c64,c64
c27,c27
c17,c17
c28,c45
.
p0(E,E)
c12,c54
c49,c43
.
p6(E,E)
c14,c14
c22,c33
c53,c18
c3,c0
.
p10(E,E)
c27,c27
.
p3(E,E)
c65,c61
c62,c36
c39,c4
.
p4(E,E)
c53,c53
.
| D |
module cc.lexer;
import core.stdc.ctype;
import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string;
import cc.identifier;
import cc.tokens;
__gshared Token* tokens;
// Returns a newly allocated Token.
Token* allocateToken() nothrow
{
return new Token();
}
void tokenizer(const(char)* p) nothrow
{
tokens = allocateToken();
Token* token = tokens;
while (*p)
{
if (isspace(*p))
{
p++;
continue;
}
else if (*p == '+')
{
token.value = TOK.ADD;
token.ptr = p;
token = token.next = allocateToken();
p++;
continue;
}
else if (*p == '-')
{
token.value = TOK.MIN;
token.ptr = p;
token = token.next = allocateToken();
p++;
continue;
}
else if (*p == '*')
{
token.value = TOK.MUL;
token.ptr = p;
token = token.next = allocateToken();
p++;
continue;
}
else if (*p == '/')
{
token.value = TOK.DIV;
token.ptr = p;
token = token.next = allocateToken();
p++;
continue;
}
else if (*p == '(')
{
token.value = TOK.LEFTPARENT;
token.ptr = p;
token = token.next = allocateToken();
p++;
continue;
}
else if (*p == ')')
{
token.value = TOK.RIGHTPARENT;
token.ptr = p;
token = token.next = allocateToken();
p++;
continue;
}
else if (*p == '<')
{
token.ptr = p;
p++;
if (*p == '=')
{
p++;
token.value = TOK.LESS_OR_EQUAL;
}
else
{
token.value = TOK.LESS_THAN;
}
token = token.next = allocateToken();
continue;
}
else if (*p == '>')
{
token.ptr = p;
p++;
if (*p == '=')
{
p++;
token.value = TOK.GREATER_OR_EQUAL;
}
else
{
token.value = TOK.GREATER_THAN;
}
token = token.next = allocateToken();
continue;
}
else if (*p == '=')
{
token.ptr = p;
p++;
if (*p == '=')
{
p++;
token.value = TOK.EQUAL;
}
else
{
token.value = TOK.ASSIGN;
}
token = token.next = allocateToken();
continue;
}
else if (*p == '!')
{
token.ptr = p;
p++;
if (*p == '=')
{
p++;
token.value = TOK.NOTEQUAL;
token = token.next = allocateToken();
continue;
}
// fallthrough: fail to tokenize.
}
else if (*p == ';')
{
token.value = TOK.SEMICOLON;
token.ptr = p;
token = token.next = allocateToken();
p++;
continue;
}
else if ('a' <= *p && *p <= 'z')
{
token.ptr = p;
while (1)
{
const c = *++p;
if (c < 'a' || 'z' < c)
break;
}
const(size_t) len = p - token.ptr;
if (len == 2 && !strncmp(token.ptr, "if", 2))
{
token.value = TOK.IF;
}
else if (len == 4 && !strncmp(token.ptr, "else", 4))
{
token.value = TOK.ELSE;
}
else if (len == 6 && !strncmp(token.ptr, "return", 6))
{
token.value = TOK.RETURN;
}
else
{
token.ident = Identifier.idPool(token.ptr[0 .. len]);
token.value = TOK.IDENT;
}
token = token.next = allocateToken();
continue;
}
else if (isdigit(*p))
{
token.value = TOK.NUM;
token.ptr = p;
token.intvalue = strtol(p, &p, 10);
token = token.next = allocateToken();
continue;
}
fprintf(stderr, "トークナイズできません: %s\n", p);
exit(EXIT_FAILURE);
}
token.value = TOK.EOF;
token.ptr = p;
}
| D |
/Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/TemplateKit.build/AST/TemplateConditional.swift.o : /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Data/TemplateData.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateEmbed.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Deprecated.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateSource.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Data/TemplateDataStorage.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/ASTCache.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Data/TemplateDataRepresentable.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Utilities/HTMLEscape.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateSyntaxType.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Uppercase.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Lowercase.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Capitalize.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateTag.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateConditional.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateCustom.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateExpression.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Var.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Data/TemplateDataEncoder.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateIdentifier.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/TemplateByteScanner.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/TemplateRenderer.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/TagRenderer.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/PlaintextRenderer.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/ViewRenderer.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/TemplateParser.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/TemplateSerializer.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Utilities/TemplateError.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateIterator.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Contains.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Utilities/Exports.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/DateFormat.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateConstant.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Comment.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Print.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Count.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateDataContext.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/TagContext.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Raw.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateRaw.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/View.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateSyntax.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/NIO.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/Async.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/Service.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/checkouts/swift-nio.git-8756902686293799568/Sources/CNIOAtomics/include/cpp_magic.h /Users/lb/Documents/Project/LearnVapor/.build/checkouts/swift-nio.git-8756902686293799568/Sources/CNIODarwin/include/c_nio_darwin.h /Users/lb/Documents/Project/LearnVapor/.build/checkouts/swift-nio.git-8756902686293799568/Sources/CNIOAtomics/include/c-atomics.h /Users/lb/Documents/Project/LearnVapor/.build/checkouts/swift-nio.git-8756902686293799568/Sources/CNIOLinux/include/c_nio_linux.h /Users/lb/Documents/Project/LearnVapor/.build/checkouts/swift-nio-zlib-support.git--4783613459776704231/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CCryptoOpenSSL.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOLinux.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/TemplateKit.build/TemplateConditional~partial.swiftmodule : /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Data/TemplateData.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateEmbed.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Deprecated.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateSource.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Data/TemplateDataStorage.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/ASTCache.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Data/TemplateDataRepresentable.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Utilities/HTMLEscape.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateSyntaxType.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Uppercase.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Lowercase.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Capitalize.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateTag.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateConditional.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateCustom.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateExpression.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Var.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Data/TemplateDataEncoder.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateIdentifier.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/TemplateByteScanner.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/TemplateRenderer.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/TagRenderer.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/PlaintextRenderer.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/ViewRenderer.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/TemplateParser.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/TemplateSerializer.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Utilities/TemplateError.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateIterator.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Contains.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Utilities/Exports.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/DateFormat.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateConstant.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Comment.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Print.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Count.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateDataContext.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/TagContext.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Raw.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateRaw.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/View.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateSyntax.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/NIO.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/Async.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/Service.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/checkouts/swift-nio.git-8756902686293799568/Sources/CNIOAtomics/include/cpp_magic.h /Users/lb/Documents/Project/LearnVapor/.build/checkouts/swift-nio.git-8756902686293799568/Sources/CNIODarwin/include/c_nio_darwin.h /Users/lb/Documents/Project/LearnVapor/.build/checkouts/swift-nio.git-8756902686293799568/Sources/CNIOAtomics/include/c-atomics.h /Users/lb/Documents/Project/LearnVapor/.build/checkouts/swift-nio.git-8756902686293799568/Sources/CNIOLinux/include/c_nio_linux.h /Users/lb/Documents/Project/LearnVapor/.build/checkouts/swift-nio-zlib-support.git--4783613459776704231/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CCryptoOpenSSL.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOLinux.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/TemplateKit.build/TemplateConditional~partial.swiftdoc : /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Data/TemplateData.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateEmbed.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Deprecated.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateSource.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Data/TemplateDataStorage.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/ASTCache.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Data/TemplateDataRepresentable.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Utilities/HTMLEscape.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateSyntaxType.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Uppercase.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Lowercase.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Capitalize.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateTag.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateConditional.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateCustom.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateExpression.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Var.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Data/TemplateDataEncoder.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateIdentifier.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/TemplateByteScanner.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/TemplateRenderer.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/TagRenderer.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/PlaintextRenderer.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/ViewRenderer.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/TemplateParser.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Pipeline/TemplateSerializer.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Utilities/TemplateError.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateIterator.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Contains.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Utilities/Exports.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/DateFormat.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateConstant.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Comment.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Print.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Count.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateDataContext.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/TagContext.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/Tag/Raw.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateRaw.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/View.swift /Users/lb/Documents/Project/LearnVapor/.build/checkouts/template-kit.git-6616349092713276412/Sources/TemplateKit/AST/TemplateSyntax.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/NIO.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/Async.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/Service.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/lb/Documents/Project/LearnVapor/.build/checkouts/swift-nio.git-8756902686293799568/Sources/CNIOAtomics/include/cpp_magic.h /Users/lb/Documents/Project/LearnVapor/.build/checkouts/swift-nio.git-8756902686293799568/Sources/CNIODarwin/include/c_nio_darwin.h /Users/lb/Documents/Project/LearnVapor/.build/checkouts/swift-nio.git-8756902686293799568/Sources/CNIOAtomics/include/c-atomics.h /Users/lb/Documents/Project/LearnVapor/.build/checkouts/swift-nio.git-8756902686293799568/Sources/CNIOLinux/include/c_nio_linux.h /Users/lb/Documents/Project/LearnVapor/.build/checkouts/swift-nio-zlib-support.git--4783613459776704231/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CCryptoOpenSSL.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/lb/Documents/Project/LearnVapor/.build/x86_64-apple-macosx10.10/debug/CNIOLinux.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
| D |
# FIXED
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/osal/src/common/osal.c
OSAL/osal.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/string.h
OSAL/osal.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/_ti_config.h
OSAL/osal.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/linkage.h
OSAL/osal.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/sys/cdefs.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/osal/src/inc/comdef.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/target/_common/hal_types.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/target/_common/../_common/cc26xx/_hal_types.h
OSAL/osal.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/stdint.h
OSAL/osal.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/sys/stdint.h
OSAL/osal.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/sys/_types.h
OSAL/osal.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/machine/_types.h
OSAL/osal.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/machine/_stdint.h
OSAL/osal.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/sys/_stdint.h
OSAL/osal.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/stdbool.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/inc/hal_defs.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/inc/hal_board.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/target/_common/hal_board_cfg.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/target/_common/hal_mcu.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/target/_common/hal_types.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/inc/hw_nvic.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/inc/hw_ints.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/inc/hw_types.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/inc/../inc/hw_chip_def.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/inc/hw_gpio.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/inc/hw_memmap.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/systick.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/debug.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/interrupt.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/cpu.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_cpu_scs.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../driverlib/rom.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/uart.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_uart.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/gpio.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/flash.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_flash.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_aon_pmctl.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_fcfg1.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/ioc.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_ioc.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/icall/src/inc/icall.h
OSAL/osal.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/stdlib.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/inc/hal_assert.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/target/_common/hal_types.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/target/_common/hal_types.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/osal/src/inc/osal.h
OSAL/osal.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/limits.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/osal/src/inc/osal_memory.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/osal/src/inc/osal_timers.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/osal/src/inc/osal_tasks.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/osal/src/inc/osal_pwrmgr.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/osal/src/inc/osal_clock.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/common/cc26xx/onboard.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/sys_ctrl.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_sysctl.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_prcm.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_aon_ioc.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_ddi_0_osc.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_rfc_pwr.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_adi_3_refsys.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_aon_rtc.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/pwr_ctrl.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_adi_2_refsys.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/osc.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_ccfg.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_ddi.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/ddi.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_aux_smph.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/prcm.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/aon_ioc.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/adi.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_adi.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/vims.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_vims.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/inc/hal_sleep.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/inc/hal_drivers.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/target/_common/hal_types.h
OSAL/osal.obj: C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/icall/src/inc/icall_jt.h
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/osal/src/common/osal.c:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/string.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/_ti_config.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/linkage.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/sys/cdefs.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/osal/src/inc/comdef.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/target/_common/hal_types.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/target/_common/../_common/cc26xx/_hal_types.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/stdint.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/sys/stdint.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/sys/_types.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/machine/_types.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/machine/_stdint.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/sys/_stdint.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/stdbool.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/inc/hal_defs.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/inc/hal_board.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/target/_common/hal_board_cfg.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/target/_common/hal_mcu.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/target/_common/hal_types.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/inc/hw_nvic.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/inc/hw_ints.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/inc/hw_types.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/inc/../inc/hw_chip_def.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/inc/hw_gpio.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/inc/hw_memmap.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/systick.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/debug.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/interrupt.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/cpu.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_cpu_scs.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../driverlib/rom.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/uart.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_uart.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/gpio.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/flash.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_flash.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_aon_pmctl.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_fcfg1.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/ioc.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_ioc.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/icall/src/inc/icall.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/stdlib.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/inc/hal_assert.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/target/_common/hal_types.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/target/_common/hal_types.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/osal/src/inc/osal.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.3.LTS/include/limits.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/osal/src/inc/osal_memory.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/osal/src/inc/osal_timers.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/osal/src/inc/osal_tasks.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/osal/src/inc/osal_pwrmgr.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/osal/src/inc/osal_clock.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/common/cc26xx/onboard.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/sys_ctrl.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_sysctl.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_prcm.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_aon_ioc.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_ddi_0_osc.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_rfc_pwr.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_adi_3_refsys.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_aon_rtc.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/pwr_ctrl.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_adi_2_refsys.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/osc.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_ccfg.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_ddi.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/ddi.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_aux_smph.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/prcm.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/aon_ioc.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/adi.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_adi.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/vims.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/devices/cc13x2_cc26x2/driverlib/../inc/hw_vims.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/inc/hal_sleep.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/inc/hal_drivers.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/hal/src/target/_common/hal_types.h:
C:/ti/simplelink_cc2652rb_ble_sdk_3_10_00_15/source/ti/ble5stack/icall/src/inc/icall_jt.h:
| D |
/*
* Copyright (c) 2017-2018 sel-project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
/**
* Copyright: Copyright (c) 2017-2018 sel-project
* License: MIT
* Authors: Kripth
* Source: $(HTTP github.com/sel-project/selery/source/selery/crash.d, selery/crash.d)
*/
module selery.crash;
import std.algorithm : min, max;
import std.ascii : newline;
import std.conv : to;
import std.datetime : Clock;
import std.file : write, read, exists, mkdir;
import std.string : split, replace;
import sel.format : Format;
import sel.terminal : writeln;
import selery.about : Software;
import selery.lang : LanguageManager;
public string logCrash(string type, inout LanguageManager lang, Throwable e) {
string filename = "crash/" ~ type ~ "_" ~ Clock.currTime().toSimpleString().split(".")[0].replace(" ", "_").replace(":", ".") ~ ".txt";
writeln(Format.red ~ lang.translate("warning.crash", [typeid(e).to!string.split(".")[$-1], e.msg, e.file, e.line.to!string]));
string file = "Critical " ~ (cast(Error)e ? "error" : "exception") ~ " on " ~ Software.display ~ newline ~ newline;
file ~= "Message: " ~ e.msg ~ newline;
file ~= "Type: " ~ typeid(e).to!string.split(".")[$-1] ~ newline;
file ~= "File: " ~ e.file ~ newline;
file ~= "Line: " ~ e.line.to!string ~ newline ~ newline;
file ~= e.info.to!string.replace("\n", newline) ~ newline;
if(exists(e.file)) {
file ~= newline;
string[] errfile = (cast(string)read(e.file)).split(newline);
foreach(uint i ; to!uint(max(0, e.line-32))..to!uint(min(errfile.length, e.line+32))) {
file ~= "[" ~ (i + 1).to!string ~ "] " ~ errfile[i] ~ newline;
}
}
if(!exists("crash")) mkdir("crash");
write(filename, file);
writeln(Format.red ~ lang.translate("warning.savedCrash", [filename]));
return filename;
}
| D |
module core.locales.en_us;
import core.locale;
import core.time;
import core.date;
import core.definitions;
import core.string;
class LocaleEnglish_US : LocaleInterface {
string formatTime(Time time) {
long hour = time.hours;
bool pm = false;
if (hour >= 12) {
hour -= 12;
pm = true;
}
string ret;
ret = toStr(hour);
ret ~= ":";
long min = time.minutes % 60;
if (min < 10) {
ret ~= "0";
}
ret ~= toStr(min);
ret ~= ":";
long sec = time.seconds % 60;
if (sec < 10) {
ret ~= "0";
}
ret ~= toStr(sec);
if (pm) {
ret ~= "pm";
}
else {
ret ~= "PM";
}
return ret;
}
string formatDate(Date date) {
string ret;
switch(date.month) {
case Month.January:
ret = "January ";
break;
case Month.February:
ret = "February ";
break;
case Month.March:
ret = "March ";
break;
case Month.April:
ret = "April ";
break;
case Month.May:
ret = "May ";
break;
case Month.June:
ret = "June ";
break;
case Month.July:
ret = "July ";
break;
case Month.August:
ret = "August ";
break;
case Month.September:
ret = "September ";
break;
case Month.October:
ret = "October ";
break;
case Month.November:
ret = "November ";
break;
case Month.December:
ret = "December ";
break;
default:
ret = "??? ";
break;
}
string day = toStr(date.day);
ret ~= day;
ret ~= ", " ~ toStr(date.year);
return ret;
}
string formatCurrency(long whole, long scale) {
return "$" ~ formatNumber(whole, scale, 2);
}
string formatCurrency(double amount) {
return "$" ~ formatNumber(amount);
}
string formatNumber(long whole, long scale, long round = -1) {
long intPart;
long baseScale;
long fracPart;
// Get integer part of decimal
intPart = whole;
baseScale = 1;
int precision;
for (long i; i < scale; i++) {
intPart /= 10;
baseScale *= 10;
precision++;
}
// Get fraction as an integer
fracPart = whole % baseScale;
// Round down
for ( ; precision > round ; precision-- ) {
fracPart /= 10;
}
return formatNumber(intPart) ~ "." ~ formatNumber(fracPart);
}
string formatNumber(long value) {
if (value == 0) {
return "0";
}
string ret;
while (value > 0) {
long part = value % 1000;
value /= 1000;
if (ret !is null) {
ret = toStr(part) ~ "," ~ ret;
}
else {
ret = toStr(part);
}
}
return ret;
}
string formatNumber(double value) {
string ret;
long intPart = cast(long)value;
while (intPart > 0) {
long part = intPart % 1000;
intPart /= 1000;
if (ret !is null) {
ret = toStr(part) ~ "," ~ ret;
}
else {
ret = toStr(part);
}
}
ret ~= ".";
ret ~= toStr(value);
// round last digit
bool roundUp = (ret[$-1] >= '5');
ret = ret[0..$-1];
while (roundUp) {
if (ret.length == 0) {
return "0";
}
else if (ret[$-1] == '.' || ret[$-1] == '9') {
ret = ret[0..$-1];
continue;
}
ret[$-1]++;
break;
}
// get rid of useless zeroes (and point if necessary)
foreach_reverse(uint i, chr; ret) {
if (chr != '0' && chr != '.') {
ret = ret[0..i+1];
break;
}
}
return ret;
}
}
| D |
# FIXED
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/Comun/common/F2837xD_Upp.c
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_device.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/ti-cgt-c2000_16.9.6.LTS/include/assert.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/ti-cgt-c2000_16.9.6.LTS/include/linkage.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/ti-cgt-c2000_16.9.6.LTS/include/stdarg.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/ti-cgt-c2000_16.9.6.LTS/include/stdbool.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/ti-cgt-c2000_16.9.6.LTS/include/stddef.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/ti-cgt-c2000_16.9.6.LTS/include/stdint.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_adc.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_analogsubsys.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_can.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_cla.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_cmpss.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_cputimer.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_dac.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_dcsm.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_dma.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_ecap.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_emif.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_epwm.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_epwm_xbar.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_eqep.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_flash.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_gpio.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_i2c.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_input_xbar.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_ipc.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_mcbsp.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_memconfig.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_nmiintrupt.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_output_xbar.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_piectrl.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_pievect.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_sci.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_sdfm.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_spi.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_sysctrl.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_upp.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_xbar.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_xint.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Examples.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_GlobalPrototypes.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_cputimervars.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Cla_defines.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_EPwm_defines.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Adc_defines.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Emif_defines.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Gpio_defines.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_I2c_defines.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Ipc_defines.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Pie_defines.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Dma_defines.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_SysCtrl_defines.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Upp_defines.h
Comun/common/F2837xD_Upp.obj: C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_defaultisr.h
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/Comun/common/F2837xD_Upp.c:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_device.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/ti-cgt-c2000_16.9.6.LTS/include/assert.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/ti-cgt-c2000_16.9.6.LTS/include/linkage.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/ti-cgt-c2000_16.9.6.LTS/include/stdarg.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/ti-cgt-c2000_16.9.6.LTS/include/stdbool.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/ti-cgt-c2000_16.9.6.LTS/include/stddef.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/ti-cgt-c2000_16.9.6.LTS/include/stdint.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_adc.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_analogsubsys.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_can.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_cla.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_cmpss.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_cputimer.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_dac.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_dcsm.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_dma.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_ecap.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_emif.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_epwm.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_epwm_xbar.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_eqep.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_flash.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_gpio.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_i2c.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_input_xbar.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_ipc.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_mcbsp.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_memconfig.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_nmiintrupt.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_output_xbar.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_piectrl.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_pievect.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_sci.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_sdfm.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_spi.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_sysctrl.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_upp.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_xbar.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_headers/include/F2837xD_xint.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Examples.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_GlobalPrototypes.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_cputimervars.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Cla_defines.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_EPwm_defines.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Adc_defines.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Emif_defines.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Gpio_defines.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_I2c_defines.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Ipc_defines.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Pie_defines.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Dma_defines.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_SysCtrl_defines.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_Upp_defines.h:
C:/Users/jeniher/PROYECTOS/Workspace_CCS7/UFCharger/F2837xD/F2837xD_common/include/F2837xD_defaultisr.h:
| D |
module android.java.javax.net.ssl.X509TrustManager_d_interface;
import arsd.jni : IJavaObjectImplementation, JavaPackageId, JavaName, IJavaObject, ImportExportImpl, JavaInterfaceMembers;
static import arsd.jni;
import import0 = android.java.java.security.cert.X509Certificate_d_interface;
import import1 = android.java.java.lang.Class_d_interface;
final class X509TrustManager : IJavaObject {
static immutable string[] _d_canCastTo = [
"javax/net/ssl/TrustManager",
];
@Import void checkClientTrusted(import0.X509Certificate, string[]);
@Import void checkServerTrusted(import0.X509Certificate, string[]);
@Import import0.X509Certificate[] getAcceptedIssuers();
@Import import1.Class getClass();
@Import int hashCode();
@Import bool equals(IJavaObject);
@Import @JavaName("toString") string toString_();
override string toString() { return arsd.jni.javaObjectToString(this); }
@Import void notify();
@Import void notifyAll();
@Import void wait(long);
@Import void wait(long, int);
@Import void wait();
mixin IJavaObjectImplementation!(false);
public static immutable string _javaParameterString = "Ljavax/net/ssl/X509TrustManager;";
}
| D |
/*
Copyright © 2020, Luna Nielsen
Distributed under the 2-Clause BSD License, see LICENSE file.
Authors: Luna Nielsen
*/
module engine.ui.widget;
import engine;
import std.algorithm.mutation : remove;
import bindbc.opengl;
import std.exception;
import std.format;
/**
A widget
*/
abstract class Widget {
private:
string typeName;
Widget parent_;
Widget[] children;
ptrdiff_t findSelfInParent() {
// Can't find self if we don't have a parent
if (parent_ is null) return -1;
// Iterate through parent's children and find our instance
foreach(i, widget; parent_.children) {
if (widget == this) return i;
}
// We couldn't find ourselves?
AppLog.warn("UI", "Widget %s could not find self in parent", this);
return -1;
}
protected:
/**
The parent widget
*/
Widget parent() {
return parent_;
}
/**
Base widget instance requires type name
*/
this(string type) {
this.typeName = type;
}
/**
Code run when updating the widget
*/
abstract void onUpdate();
/**
Code run when drawing
*/
abstract void onDraw();
public:
/**
Whether the widget is visible
*/
bool visible = true;
/**
The position of the widget
*/
vec2 position = vec2(0);
/**
Changes the parent of a widget to the specified other widget.
*/
void changeParent(Widget newParent) {
// Once we're done we need to update our bounds
// We'll skip this if we threw an exception earlier
scope(success) update();
// Remove ourselves from our current parent if we have any
if (parent_ !is null) {
// Find ourselves in our parent
ptrdiff_t self = findSelfInParent();
enforce(self >= 0, "Invalid parent widget");
// Remove ourselves from our current parent
parent_.children.remove(self);
}
// If our new parent is null we'll end early
if (newParent is null) {
this.parent_ = null;
return;
}
// Set our parent to our new parent and add ourselves to our new parent's list
this.parent_ = newParent;
this.parent_.children ~= this;
}
/**
Update the widget
Automatically updates all the children first
*/
void update() {
// Update all our children
foreach(child; children) {
child.update();
}
// Update ourselves
this.onUpdate();
}
/**
Draw the widget
For widget implementing: override onDraw
*/
final void draw() {
// Don't draw this widget or its children if we're invisible
if (!visible) return;
if (parent_ is null) UI.setScissor(vec4i(0, 0, GameWindow.width, GameWindow.height));
// Draw ourselves first
this.onDraw();
// We set our scissor rectangle to our rendering area
UI.setScissor(scissorArea);
// Draw all the children
foreach(child; children) {
child.draw();
}
}
/**
Gets the calculated position of the widget
*/
final vec2 calculatedPosition() {
return parent_ !is null ? parent_.calculatedPosition+position : position;
}
abstract {
/**
Area of the widget
*/
vec4 area();
/**
Area in which the widget cuts out child widgets
*/
vec4i scissorArea();
}
override {
/**
Gets this widget as a string
This returns the tree for this instance of the widget ordered by type name.
*/
final string toString() const {
return parent_ is null ? typeName : "%s->%s".format(parent_.toString, typeName);
}
}
} | D |
module prometheus.histogram;
import prometheus.collector;
import prometheus.common;
public class Histogram : Collector {
this() {
noLabelsChild = new Histogram.Child();
}
this(string name, string help, string[] labels) {
noLabelsChild = new Histogram.Child();
super(name, help, labels);
}
mixin BasicCollectorClassConstructor!Histogram;
public auto buckets(double[] buckets) {
if (_upperBounds.length)
throw new IllegalArgumentException("Cannot call this on an initialized histogram");
import std.algorithm;
if (!buckets.isSorted)
throw new IllegalArgumentException("The buckets array needs to be sorted");
_upperBounds = buckets;
auto child = cast(Histogram.Child)(noLabelsChild);
child.initializeBucketCounters();
return this;
}
public auto get() {
auto child = cast(Histogram.Child)(noLabelsChild);
return child.get();
}
public auto observe(double amt) {
auto child = cast(Histogram.Child)(noLabelsChild);
return child.observe(amt);
}
enum DEFAULT_BUCKETS = [.005, .01, .025, .05, .075, .1, .25, .5, .75, 1, 2.5, 5, 7.5, 10];
private double[] _upperBounds;
class Child : Collector.Child {
private ulong[] _bucketCounters;
private ulong _count;
private double _sum;
this() {
_sum = 0;
_count = 0;
initializeBucketCounters();
}
private void initializeBucketCounters() {
_bucketCounters.reserve(_upperBounds.length);
for(uint i; i < _upperBounds.length; ++i)
_bucketCounters ~= 0;
}
public auto get() {
static struct Value {
double _sum;
ulong _count;
ulong[] _bucketCounters;
}
return Value(_sum, _count, _bucketCounters);
}
public void observe(double amt) {
synchronized {
for (int i = 0; i < _upperBounds.length; ++i) {
// The last bucket is +Inf, so we always increment.
if (amt <= _upperBounds[i])
++_bucketCounters[i];
}
++_count;
_sum += amt;
}
}
}
override public string getType() {
return "histogram";
}
override public string getTextExposition() {
import prometheus.exposition.text;
import std.format;
import std.array;
string[] text;
text ~= HELP_LINE.format(_name, escape(_help));
text ~= TYPE_LINE.format(_name, getType());
if (!_labelNames.length) {
auto child = cast(Histogram.Child)(noLabelsChild);
text ~= getChildRepresentation(child);
text ~= METRIC_LINE.format(_name ~ "_sum", "", child._sum);
text ~= METRIC_LINE.format(_name ~ "_count", "", child._count);
}
else if (children.length) {
foreach (labelValues, ziChild; children) {
auto child = cast(Histogram.Child)(ziChild);
text ~= getChildRepresentation(child, labelValues);
text ~= METRIC_LINE.format(_name ~ "_sum", getLabelsTextExposition(_labelNames, labelValues), child._sum);
text ~= METRIC_LINE.format(_name ~ "_count", getLabelsTextExposition(_labelNames, labelValues), child._count);
}
}
return text.join(DELIMITER);
}
private string[] getChildRepresentation(Histogram.Child child, in string[] ziLabelValues = []) {
import prometheus.exposition.text;
import std.conv;
import std.format;
// when the histogram has not observed anything yet, there will be no labelValues
auto labelNamesToUse = ziLabelValues.length ? _labelNames : [];
enum BUCKET = "%s_bucket";
string[] text;
foreach (i, value; this._upperBounds) {
auto labelNames = labelNamesToUse.dup;
labelNames ~= "le";
auto labelValues = ziLabelValues.dup;
labelValues ~= value.to!string;
text ~= METRIC_LINE.format(BUCKET.format(_name), getLabelsTextExposition(labelNames, labelValues), child._bucketCounters[i]);
}
text ~= METRIC_LINE.format(BUCKET.format(_name), getLabelsTextExposition(labelNamesToUse.dup ~ "le", ziLabelValues.dup ~ "+Inf"), child._count);
return text;
}
}
unittest {
import std.stdio;
import std.format;
writeln("First Histogram test");
auto histogram = new Histogram().name("test").help("Help").buckets([0.01, 0.1, 1, 2]);
assert(histogram._name == "test", "Name differs");
assert(histogram._help == "Help", "help differs");
histogram.observe(1.5f);
{
auto value = histogram.get();
//writeln(format("%s", value));
assert(value._sum == 1.5, "Sum is good");
assert(value._count == 1, "Count is good");
assert(value._bucketCounters[0] == 0, "Bucket 0 is good");
assert(value._bucketCounters[1] == 0, "Bucket 1 is good");
assert(value._bucketCounters[2] == 0, "Bucket 2 is good");
assert(value._bucketCounters[3] == 1, "Bucket 3 is good");
}
histogram.observe(1.5);
{
auto value = histogram.get();
assert(value._sum == 3, "Sum is good");
assert(value._count == 2, "Count is good");
assert(value._bucketCounters[0] == 0, "Bucket 0 is good");
assert(value._bucketCounters[1] == 0, "Bucket 1 is good");
assert(value._bucketCounters[2] == 0, "Bucket 2 is good");
assert(value._bucketCounters[3] == 2, "Bucket 3 is good");
}
histogram.observe(0.9);
{
auto value = histogram.get();
assert(value._sum == 3.9, "Sum is good");
assert(value._count == 3, "Count is good");
assert(value._bucketCounters[0] == 0, "Bucket 0 is good");
assert(value._bucketCounters[1] == 0, "Bucket 1 is good");
assert(value._bucketCounters[2] == 1, "Bucket 2 is good");
assert(value._bucketCounters[3] == 3, "Bucket 3 is good");
}
histogram.observe(0.02);
{
auto value = histogram.get();
assert(value._sum == 3.92, "Sum is good");
assert(value._count == 4, "Count is good");
assert(value._bucketCounters[0] == 0, "Bucket 0 is good");
assert(value._bucketCounters[1] == 1, "Bucket 1 is good");
assert(value._bucketCounters[2] == 2, "Bucket 2 is good");
assert(value._bucketCounters[3] == 4, "Bucket 3 is good");
}
//writeln(histogram.getTextExposition());
assert(histogram.getTextExposition() == "# HELP test Help
# TYPE test histogram
test_bucket{le=\"0.01\"} 0
test_bucket{le=\"0.1\"} 1
test_bucket{le=\"1\"} 2
test_bucket{le=\"2\"} 4
test_bucket{le=\"+Inf\"} 4
test_sum 3.92
test_count 4", "Histogram expsition is not bery nice");
writeln("Second Histogram test");
auto histogram2 = new Histogram().name("jamla").help("description").labelNames(["code"])
.buckets([10, 20, 30]);
assert(histogram2._name == "jamla", "Name differs");
assert(histogram2._help == "description", "help differs");
histogram2.labels(["ah"]).observe(15);
histogram2.labels(["ah"]).observe(0.2f);
{
auto value = histogram2.labels(["ah"]).get();
//writeln(format("%s", value));
assert(value._sum == 15.2, "Sum is good");
assert(value._count == 2, "Count is good");
assert(value._bucketCounters[0] == 1, "Bucket 0 is good");
assert(value._bucketCounters[1] == 2, "Bucket 1 is good");
assert(value._bucketCounters[2] == 2, "Bucket 2 is good");
}
histogram2.labels(["some_other_value"]).observe(1.8f);
{
auto value = histogram2.labels(["some_other_value"]).get();
//writeln(format("%s", value));
assert(value._sum == 1.8, "Sum is good");
assert(value._count == 1, "Count is good");
assert(value._bucketCounters[0] == 1, "Bucket 0 is good");
assert(value._bucketCounters[1] == 1, "Bucket 1 is good");
assert(value._bucketCounters[2] == 1, "Bucket 2 is good");
}
//writeln(histogram2.getTextExposition());
assert(histogram2.getTextExposition() == "# HELP jamla description
# TYPE jamla histogram
jamla_bucket{code=\"ah\",le=\"10\"} 1
jamla_bucket{code=\"ah\",le=\"20\"} 2
jamla_bucket{code=\"ah\",le=\"30\"} 2
jamla_bucket{code=\"ah\",le=\"+Inf\"} 2
jamla_sum{code=\"ah\"} 15.2
jamla_count{code=\"ah\"} 2
jamla_bucket{code=\"some_other_value\",le=\"10\"} 1
jamla_bucket{code=\"some_other_value\",le=\"20\"} 1
jamla_bucket{code=\"some_other_value\",le=\"30\"} 1
jamla_bucket{code=\"some_other_value\",le=\"+Inf\"} 1
jamla_sum{code=\"some_other_value\"} 1.8
jamla_count{code=\"some_other_value\"} 1", "Histogram expsition is not bery nice");
}
| D |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.