code
stringlengths 3
10M
| language
stringclasses 31
values |
|---|---|
/**
Defines a Region and common operation with these. A Region is a set of
tagged intervals where differently tagged intervals are distinct.
Copyright: © 2018 Arne Ludwig <arne.ludwig@posteo.de>
License: Subject to the terms of the MIT license, as written in the
included LICENSE file.
Authors: Arne Ludwig <arne.ludwig@posteo.de>
*/
module djunctor.util.region;
import std.algorithm : all, cmp, filter, map, max, min, sort, sum;
import std.array : appender, array, join;
import std.exception : assertThrown;
import std.format : format;
import std.range : assumeSorted, ElementType, isInputRange, only, retro;
import std.traits : isNumeric, Unqual;
/// Returns the type of the property `tag` of `T`.
template TagType(T)
{
private T instance;
alias TagType = typeof(instance.tag);
}
/// Checks if T has a property `tag` implicitly convertible to `Tag` – if given.
template isTaggable(T)
{
enum isTaggable = is(TagType!T);
}
unittest
{
struct Taggable
{
int tag;
}
static assert(isTaggable!Taggable);
static assert(!isTaggable!int);
}
unittest
{
struct Taggable
{
int tag;
}
static assert(isTaggable!Taggable);
static assert(!isTaggable!int);
}
/// Thrown if two operands require the same tag but different were provided.
static class MismatchingTagsException(Tag) : Exception
{
const(Tag[2]) tags;
this(in Tag tagA, in Tag tagB)
{
this.tags = [tagA, tagB];
super(format!"mismatching interval tags: %s"(this.tags));
}
}
/*
Throws an exception if tags do not match.
Throws: MismatchingTagsException if tags do not match.
*/
void enforceMatchingTags(Taggable)(in Taggable taggableA, in Taggable taggableB) pure
if (isTaggable!Taggable)
{
alias Tag = TagType!Taggable;
if (taggableA.tag != taggableB.tag)
{
throw new MismatchingTagsException!Tag(taggableA.tag, taggableB.tag);
}
}
/// Thrown if regions is unexpectedly empty.
static class EmptyRegionException : Exception
{
this()
{
super("empty region");
}
}
/*
Throws an exception if region is empty.
Throws: EmptyRegionException if region is empty.
*/
void enforceNonEmpty(R)(in R region) if (is(R : Region!Args, Args...))
{
if (region.empty)
{
throw new EmptyRegionException();
}
}
/**
A Region is a set of tagged intervals where differently tagged intervals are distinct.
*/
struct Region(Number, Tag, string tagAlias = null, Tag emptyTag = Tag.init)
{
static assert(isNumeric!Number, "interval limits must be numeric");
static if (__traits(compiles, Number.infinity))
{
static immutable numberSup = Number.infinity;
}
else
{
static immutable numberSup = Number.max;
}
/**
This represents a single tagged point.
*/
static struct TaggedPoint
{
Tag tag = emptyTag;
Number value;
static if (!(tagAlias is null) && tagAlias != "tag")
{
mixin("alias " ~ tagAlias ~ " = tag;");
}
}
/**
This is a right-open interval `[begin, end)` tagged with `tag`.
If `tagAlias` is given then the tag may be access as a property of
that name.
*/
static struct TaggedInterval
{
Tag tag = emptyTag;
Number begin;
Number end;
static if (!(tagAlias is null) && tagAlias != "tag")
{
mixin("alias " ~ tagAlias ~ " = tag;");
}
invariant
{
assert(begin <= end, "begin must be less than or equal to end");
}
/// Returns the size of this interval.
@property Number size() pure const nothrow
{
return this.end - this.begin;
}
///
unittest
{
assert(Region!(int, int).TaggedInterval().size == 0);
assert(TaggedInterval(1, 10, 20).size == 10);
assert(TaggedInterval(2, 20, 40).size == 20);
assert(TaggedInterval(3, 30, 60).size == 30);
}
/// Returns true iff the interval is empty. An interval is empty iff
/// `begin == end`.
@property bool empty() pure const nothrow
{
return begin >= end;
}
///
unittest
{
assert(TaggedInterval().empty);
assert(!TaggedInterval(1, 10, 20).empty);
assert(!TaggedInterval(2, 20, 40).empty);
assert(TaggedInterval(3, 60, 60).empty);
}
/**
Returns the convex hull of the intervals.
Throws: MismatchingTagsException if `tag`s differ.
*/
static TaggedInterval convexHull(in TaggedInterval[] intervals...) pure
{
if (intervals.length == 0)
{
return TaggedInterval();
}
TaggedInterval convexHullInterval = intervals[0];
foreach (interval; intervals[1 .. $])
{
enforceMatchingTags(convexHullInterval, interval);
if (convexHullInterval.empty)
{
convexHullInterval = interval;
}
else if (interval.empty)
{
continue;
}
else
{
convexHullInterval.begin = min(convexHullInterval.begin, interval.begin);
convexHullInterval.end = max(convexHullInterval.end, interval.end);
}
}
// dfmt off
return convexHullInterval.empty
? TaggedInterval()
: convexHullInterval;
// dfmt on
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
assert(TI.convexHull(TI(0, 10, 20), TI(0, 0, 5)) == TI(0, 0, 20));
assert(TI.convexHull(TI(0, 10, 20), TI(0, 5, 15)) == TI(0, 5, 20));
assert(TI.convexHull(TI(0, 10, 20), TI(0, 12, 18)) == TI(0, 10, 20));
assert(TI.convexHull(TI(0, 10, 20), TI(0, 10, 20)) == TI(0, 10, 20));
assert(TI.convexHull(TI(0, 10, 20), TI(0, 15, 25)) == TI(0, 10, 25));
assert(TI.convexHull(TI(0, 10, 20), TI(0, 25, 30)) == TI(0, 10, 30));
assertThrown!(MismatchingTagsException!int)(TI.convexHull(TI(0, 10, 20), TI(1, 25, 30)));
}
/// Returns the intersection of both intervals; empty if `tag`s differ.
TaggedInterval opBinary(string op)(in TaggedInterval other) const pure nothrow
if (op == "&")
{
if (this.tag != other.tag)
{
return TaggedInterval();
}
auto newBegin = max(this.begin, other.begin);
auto newEnd = min(this.end, other.end);
if (newBegin > newEnd)
{
return TaggedInterval();
}
// dfmt off
return TaggedInterval(
tag,
newBegin,
newEnd,
);
// dfmt on
}
/// ditto
TaggedInterval opOpAssign(string op)(in TaggedInterval other) if (op == "&")
{
{
auto tmp = this & other;
this.tag = tmp.tag;
this.begin = tmp.begin;
this.end = tmp.end;
return this;
}
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
assert((TI(0, 10, 20) & TI(0, 0, 5)).empty);
assert((TI(0, 10, 20) & TI(0, 5, 15)) == TI(0, 10, 15));
assert((TI(0, 10, 20) & TI(0, 12, 18)) == TI(0, 12, 18));
assert((TI(0, 10, 20) & TI(0, 10, 20)) == TI(0, 10, 20));
assert((TI(0, 10, 20) & TI(0, 15, 25)) == TI(0, 15, 20));
assert((TI(0, 10, 20) & TI(0, 25, 30)).empty);
assert((TI(0, 10, 20) & TI(1, 25, 30)).empty);
}
/// Returns the difference of both intervals.
Region opBinary(string op)(in TaggedInterval other) const if (op == "-")
{
auto intersection = this & other;
if (intersection.empty)
{
TaggedInterval thisCopy = this;
return Region(this.empty ? [] : [thisCopy]);
}
// dfmt off
return Region(only(
TaggedInterval(
tag,
this.begin,
intersection.begin,
),
TaggedInterval(
tag,
intersection.end,
this.end,
),
).filter!"!a.empty".array);
// dfmt on
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
assert(TI(0, 10, 20) - TI(0, 0, 5) == R([TI(0, 10, 20)]));
assert(TI(0, 10, 20) - TI(0, 5, 15) == R([TI(0, 15, 20)]));
assert(TI(0, 10, 20) - TI(0, 12, 18) == R([TI(0, 10, 12), TI(0, 18, 20)]));
assert(TI(0, 10, 20) - TI(0, 10, 20) == R([]));
assert(TI(0, 10, 20) - TI(0, 15, 25) == R([TI(0, 10, 15)]));
assert(TI(0, 10, 20) - TI(0, 25, 30) == R([TI(0, 10, 20)]));
assert(TI(0, 10, 20) - TI(1, 25, 30) == R([TI(0, 10, 20)]));
}
int opCmp(in TaggedInterval other) const pure nothrow
{
// dfmt off
return cmp(
only(this.tag, this.begin, this.end),
only(other.tag, other.begin, other.end),
);
// dfmt on
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
assert(TI(0, 10, 20) > TI(0, 0, 5));
assert(TI(0, 10, 20) > TI(0, 5, 15));
assert(TI(0, 10, 20) < TI(0, 12, 18));
assert(TI(0, 10, 20) < TI(0, 15, 25));
assert(TI(0, 10, 20) == TI(0, 10, 20));
assert(TI(0, 10, 20) < TI(0, 25, 30));
assert(TI(0, 10, 20) < TI(1, 25, 30));
}
/// Returns true iff the tagged intervals intersect.
bool intersects(in TaggedInterval other) const pure nothrow
{
return !(this & other).empty;
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
assert(!TI(0, 10, 20).intersects(TI(0, 0, 5)));
assert(TI(0, 10, 20).intersects(TI(0, 5, 15)));
assert(TI(0, 10, 20).intersects(TI(0, 12, 18)));
assert(TI(0, 10, 20).intersects(TI(0, 15, 25)));
assert(TI(0, 10, 20).intersects(TI(0, 10, 20)));
assert(!TI(0, 10, 20).intersects(TI(0, 25, 30)));
assert(!TI(0, 10, 20).intersects(TI(1, 25, 30)));
}
/// Returns true iff the tagged intervals do not intersect and `this < other`.
bool isStrictlyBefore(in TaggedInterval other) const pure nothrow
{
return !this.intersects(other) && this < other;
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
assert(!TI(0, 10, 20).isStrictlyBefore(TI(0, 0, 5)));
assert(!TI(0, 10, 20).isStrictlyBefore(TI(0, 5, 15)));
assert(!TI(0, 10, 20).isStrictlyBefore(TI(0, 12, 18)));
assert(!TI(0, 10, 20).isStrictlyBefore(TI(0, 15, 25)));
assert(!TI(0, 10, 20).isStrictlyBefore(TI(0, 10, 20)));
assert(TI(0, 10, 20).isStrictlyBefore(TI(0, 25, 30)));
assert(TI(0, 10, 20).isStrictlyBefore(TI(1, 25, 30)));
}
/// Returns true iff the tagged intervals do not intersect and `this > other`.
bool isStrictlyAfter(in TaggedInterval other) const pure nothrow
{
return !this.intersects(other) && this > other;
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
assert(TI(0, 10, 20).isStrictlyAfter(TI(0, 0, 5)));
assert(!TI(0, 10, 20).isStrictlyAfter(TI(0, 5, 15)));
assert(!TI(0, 10, 20).isStrictlyAfter(TI(0, 12, 18)));
assert(!TI(0, 10, 20).isStrictlyAfter(TI(0, 15, 25)));
assert(!TI(0, 10, 20).isStrictlyAfter(TI(0, 10, 20)));
assert(!TI(0, 10, 20).isStrictlyAfter(TI(0, 25, 30)));
assert(!TI(0, 10, 20).isStrictlyAfter(TI(1, 25, 30)));
}
}
///
unittest
{
static immutable emptyTag = 42;
alias R = Region!(int, int, "bucketId", emptyTag);
alias TI = R.TaggedInterval;
TI emptyInterval;
// Default constructor produces empty interval.
assert((emptyInterval).empty);
assert(emptyInterval.tag == emptyTag);
auto ti1 = TI(1, 0, 10);
// The tag can be aliased:
assert(ti1.tag == ti1.bucketId);
auto ti2 = TI(1, 5, 15);
// Tagged intervals with the same tag behave like regular intervals:
assert((ti1 & ti2) == TI(1, 5, 10));
auto ti3 = TI(2, 0, 10);
// Tagged intervals with different tags are distinct:
assert((ti1 & ti3).empty);
}
TaggedInterval[] _intervals;
this(TaggedInterval[] intervals)
{
this._intervals = intervals;
this.normalize();
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
auto region = R([TI(0, 15, 20), TI(0, 5, 10), TI(0, 0, 10)]);
// Intervals get implicitly normalized.
assert(region.intervals == [TI(0, 0, 10), TI(0, 15, 20)]);
}
this(TaggedInterval interval)
{
this._intervals = [interval];
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
R region = TI(0, 15, 20);
assert(region.intervals == [TI(0, 15, 20)]);
}
this(Tag tag, Number begin, Number end)
{
this._intervals = [TaggedInterval(tag, begin, end)];
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
auto region = R(0, 15, 20);
assert(region.intervals == [TI(0, 15, 20)]);
}
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
auto tis = [TI(0, 15, 20)];
auto region = R(tis);
auto regionDup = region;
assert(region == regionDup);
// Changing the original does not affect duplicate
region |= R(TI(0, 25, 30));
assert(region != regionDup);
}
/// Return a list of the tagged intervals in this region.
@property const(TaggedInterval)[] intervals() const pure nothrow
{
return _intervals;
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
R emptyRegion;
auto region1 = R(0, 5, 10);
auto region2 = R([TI(0, 5, 10), TI(0, 15, 20)]);
assert(emptyRegion.intervals == []);
assert(region1.intervals == [TI(0, 5, 10)]);
assert(region2.intervals == [TI(0, 5, 10), TI(0, 15, 20)]);
}
/// Returns the size of this region.
Number size() pure const nothrow
{
return _intervals.map!"a.size".sum;
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
R emptyRegion;
auto region1 = R(0, 0, 10);
auto region2 = R([TI(0, 0, 10), TI(0, 20, 30)]);
auto region3 = R([TI(0, 0, 20), TI(0, 10, 30)]);
assert(emptyRegion.size == 0);
assert(region1.size == 10);
assert(region2.size == 20);
assert(region3.size == 30);
}
/// Returns true iff the region is empty.
bool empty() pure const nothrow
{
return _intervals.length == 0;
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
R emptyRegion1;
auto emptyRegion2 = R([TI(0, 0, 0), TI(0, 10, 10)]);
auto emptyRegion3 = R([TI(0, 0, 0), TI(1, 0, 0)]);
auto region1 = R(0, 0, 10);
assert(emptyRegion1.empty);
assert(emptyRegion2.empty);
assert(emptyRegion3.empty);
assert(!region1.empty);
}
protected void normalize()
{
if (_intervals.length == 0)
{
return;
}
_intervals.sort();
TaggedInterval accInterval = _intervals[0];
size_t insertIdx = 0;
foreach (i, intervalB; _intervals[1 .. $])
{
if (intervalB.empty)
{
continue;
}
else if (accInterval.intersects(intervalB))
{
// If two intervals intersect their union is the same as the convex hull of both.
accInterval = TaggedInterval.convexHull(accInterval, intervalB);
}
else
{
if (!accInterval.empty)
{
_intervals[insertIdx++] = accInterval;
}
accInterval = intervalB;
}
}
if (!accInterval.empty)
{
_intervals[insertIdx++] = accInterval;
}
_intervals.length = insertIdx;
}
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
// dfmt off
auto region = R([
TI(3, 8349, 8600),
TI(3, 8349, 8349),
TI(3, 8349, 8850),
TI(3, 8349, 9100),
TI(3, 8349, 8349),
TI(3, 8349, 9350),
TI(3, 8349, 9600),
TI(3, 8349, 8349),
TI(3, 8349, 9900),
TI(3, 8349, 10150),
TI(3, 8349, 8349),
TI(3, 8349, 10400),
TI(3, 8349, 10650),
TI(3, 8349, 10800),
TI(3, 8499, 10800),
TI(3, 8749, 10800),
TI(3, 8749, 8749),
TI(3, 8999, 10800),
TI(3, 9249, 10800),
TI(3, 9549, 10800),
TI(3, 9799, 10800),
TI(3, 10049, 10800),
TI(3, 10299, 10800),
TI(3, 10549, 10800),
]);
auto normalizedRegion = R([
TI(3, 8349, 10800),
]);
// dfmt on
assert(region == normalizedRegion);
}
/// Computes the union of all tagged intervals.
Region opBinary(string op)(in Region other) const if (op == "|")
{
return Region(this._intervals.dup ~ other._intervals.dup);
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
assert((R(0, 10, 20) | R(0, 0, 5)) == R([TI(0, 10, 20), TI(0, 0, 5)]));
assert((R(0, 10, 20) | R(0, 5, 15)) == R(0, 5, 20));
assert((R(0, 10, 20) | R(0, 12, 18)) == R(0, 10, 20));
assert((R(0, 10, 20) | R(0, 10, 20)) == R(0, 10, 20));
assert((R(0, 10, 20) | R(0, 15, 25)) == R(0, 10, 25));
assert((R(0, 10, 20) | R(0, 25, 30)) == R([TI(0, 10, 20), TI(0, 25, 30)]));
assert((R(0, 10, 20) | R(1, 25, 30)) == R([TI(0, 10, 20), TI(1, 25, 30)]));
}
/// Computes the intersection of the two regions.
Region opBinary(string op)(in Region other) const if (op == "&")
{
if (this.empty || other.empty)
{
return Region();
}
auto intersectionAcc = appender!(TaggedInterval[]);
intersectionAcc.reserve(this._intervals.length + other._intervals.length);
size_t lhsIdx = 0;
size_t lhsLength = this._intervals.length;
TaggedInterval lhsInterval;
size_t rhsIdx = 0;
size_t rhsLength = other._intervals.length;
TaggedInterval rhsInterval;
while (lhsIdx < lhsLength && rhsIdx < rhsLength)
{
lhsInterval = this._intervals[lhsIdx];
rhsInterval = other._intervals[rhsIdx];
if (lhsInterval.isStrictlyBefore(rhsInterval))
{
++lhsIdx;
}
else if (rhsInterval.isStrictlyBefore(lhsInterval))
{
++rhsIdx;
}
else
{
assert(lhsInterval.intersects(rhsInterval));
intersectionAcc ~= lhsInterval & rhsInterval;
if (lhsIdx + 1 < lhsLength && rhsIdx + 1 < rhsLength)
{
if (this._intervals[lhsIdx + 1].begin < other._intervals[rhsIdx + 1].begin)
{
++lhsIdx;
}
else
{
++rhsIdx;
}
}
else if (lhsIdx + 1 < lhsLength)
{
++lhsIdx;
}
else
{
++rhsIdx;
}
}
}
return Region(intersectionAcc.data);
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
assert((R(0, 10, 20) & R(0, 0, 5)) == R([]));
assert((R(0, 10, 20) & R(0, 5, 15)) == R(0, 10, 15));
assert((R(0, 10, 20) & R(0, 12, 18)) == R(0, 12, 18));
assert((R(0, 10, 20) & R(0, 10, 20)) == R(0, 10, 20));
assert((R(0, 10, 20) & R(0, 15, 25)) == R(0, 15, 20));
assert((R(0, 10, 20) & R(0, 25, 30)) == R([]));
assert((R(0, 10, 20) & R(1, 25, 30)) == R([]));
// dfmt off
// R1: [-------) [-------) [-------)
// R2: [-------) [-------) [-------)
// R1 & R2: [-) [-) [-) [-) [-)
assert((R([
TI(0, 0, 30),
TI(0, 40, 70),
TI(0, 80, 110),
]) & R([
TI(0, 20, 50),
TI(0, 60, 90),
TI(0, 100, 130),
])) == R([
TI(0, 20, 30),
TI(0, 40, 50),
TI(0, 60, 70),
TI(0, 80, 90),
TI(0, 100, 110),
]));
// dfmt on
}
Region opBinary(string op)(in TaggedInterval interval) const if (op == "-")
{
if (interval.empty)
{
return Region(_intervals.dup);
}
auto differenceAcc = appender!(TaggedInterval[]);
differenceAcc.reserve(_intervals.length + 1);
// dfmt off
auto trisection = _intervals
.assumeSorted!"a.isStrictlyBefore(b)"
.trisect(interval);
// dfmt on
auto copyHeadEnd = trisection[0].length;
auto copyTailBegin = trisection[0].length + trisection[1].length;
differenceAcc ~= _intervals[0 .. copyHeadEnd];
foreach (lhsInterval; trisection[1])
{
assert(lhsInterval.intersects(interval));
auto tmpDifference = lhsInterval - interval;
differenceAcc ~= tmpDifference._intervals;
}
differenceAcc ~= _intervals[copyTailBegin .. $];
return Region(differenceAcc.data);
}
Region opBinary(string op)(in Region other) const if (op == "-")
{
if (other.empty)
{
return Region(this._intervals.dup);
}
auto otherDifferenceCandidates = getDifferenceCandidates(other).assumeSorted!"a.isStrictlyBefore(b)";
auto differenceAcc = appender!(TaggedInterval[]);
differenceAcc.reserve(this._intervals.length + otherDifferenceCandidates.length);
foreach (lhsInterval; this._intervals)
{
auto intersectingRhs = otherDifferenceCandidates.equalRange(lhsInterval);
auto tmpDifference = Region(lhsInterval);
foreach (rhsInterval; intersectingRhs)
{
if (tmpDifference.empty
|| tmpDifference._intervals[$ - 1].isStrictlyBefore(rhsInterval))
{
// Remaining rhsItervals will not intersect anymore.
break;
}
tmpDifference -= rhsInterval;
}
if (!tmpDifference.empty)
{
differenceAcc ~= tmpDifference._intervals;
}
}
return Region(differenceAcc.data);
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
assert((R(0, 10, 20) - R(0, 0, 5)) == R(0, 10, 20));
assert((R(0, 10, 20) - R(0, 5, 15)) == R(0, 15, 20));
assert((R(0, 10, 20) - R(0, 12, 18)) == R([TI(0, 10, 12), TI(0, 18, 20)]));
assert((R(0, 10, 20) - R(0, 10, 20)).empty);
assert((R(0, 10, 20) - R(0, 15, 25)) == R(0, 10, 15));
assert((R(0, 10, 20) - R(0, 25, 30)) == R(0, 10, 20));
assert((R(0, 10, 20) - R(1, 25, 30)) == R(0, 10, 20));
}
private auto getDifferenceCandidates(in Region other) const pure nothrow
{
auto otherIntervals = other._intervals.assumeSorted!"a.isStrictlyBefore(b)";
auto sliceBegin = otherIntervals.lowerBound(this._intervals[0]).length;
auto sliceEnd = other._intervals.length - otherIntervals.upperBound(this._intervals[$ - 1]).length;
if (sliceBegin < sliceEnd)
{
return other._intervals[sliceBegin .. sliceEnd];
}
else
{
return cast(typeof(other._intervals)) [];
}
}
Region opOpAssign(string op, T)(in T other)
if (is(T : Region) || is(T : TaggedInterval))
{
static if (op == "|" || op == "&" || op == "-")
{
mixin("auto tmp = this " ~ op ~ " other;");
this._intervals = tmp._intervals;
return this;
}
else
{
static assert(0, "unsupported operator: " ~ op);
}
}
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
R accRegion;
// dfmt off
auto inputRegion1 = R([
TI(3, 8349, 8600),
TI(3, 8349, 8850),
TI(3, 8349, 9100),
TI(3, 8349, 9350),
TI(3, 8349, 9600),
TI(3, 8349, 9900),
TI(3, 8349, 10150),
TI(3, 8349, 10400),
TI(3, 8349, 10650),
TI(3, 8349, 10800),
TI(3, 8499, 10800),
TI(3, 8749, 10800),
TI(3, 8999, 10800),
TI(3, 9249, 10800),
TI(3, 9549, 10800),
TI(3, 9799, 10800),
TI(3, 10049, 10800),
TI(3, 10299, 10800),
TI(3, 10549, 10800),
]);
auto inputRegion2 = R([
TI(3, 2297, 11371),
]);
auto expectedResult = R([
TI(3, 2297, 11371),
]);
// dfmt on
accRegion |= inputRegion1;
assert(accRegion == inputRegion1);
accRegion |= inputRegion2;
assert(accRegion == expectedResult);
assert((inputRegion1 | inputRegion2) == expectedResult);
}
/// Returns true iff point is in this region.
bool opBinaryRight(string op)(in TaggedPoint point) const pure nothrow
if (op == "in")
{
if (this.empty)
{
return false;
}
auto needle = TaggedInterval(point.tag, point.value, numberSup);
auto sortedIntervals = intervals.assumeSorted;
auto candidateIntervals = sortedIntervals.lowerBound(needle).retro;
if (candidateIntervals.empty)
{
return false;
}
auto candidateInterval = candidateIntervals.front;
return candidateInterval.begin <= point.value && point.value < candidateInterval.end;
}
/// ditto
alias includes = opBinaryRight!"in";
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
alias TP = R.TaggedPoint;
R emptyRegion;
auto region = R([TI(0, 0, 10), TI(1, 0, 10)]);
assert(TP(0, 0) !in emptyRegion);
assert(TP(0, 5) !in emptyRegion);
assert(TP(0, 10) !in emptyRegion);
assert(TP(0, 20) !in emptyRegion);
assert(TP(0, 0) in region);
assert(TP(0, 5) in region);
assert(TP(0, 10) !in region);
assert(TP(0, 20) !in region);
assert(TP(1, 0) in region);
assert(TP(1, 5) in region);
assert(TP(1, 10) !in region);
assert(TP(1, 20) !in region);
}
}
unittest
{
Region!(int, int) r;
}
/**
Returns true iff `thing` is empty
See_Also: Region.empty, Region.TaggedInterval.empty
*/
bool empty(T)(in T thing) pure nothrow
if (is(T : Region!Args, Args...) || is(T : Region!Args.TaggedInterval, Args...))
{
return thing.empty;
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
R emptyRegion;
TI emptyTI;
auto region = R(0, 0, 10);
auto ti = TI(0, 0, 10);
assert(empty(emptyRegion));
assert(empty(emptyTI));
assert(!empty(region));
assert(!empty(ti));
}
/**
Returns the union of all elements.
See_Also: Region.opBinary!"|", Region.TaggedInterval.opBinary!"|"
*/
auto union_(Range)(Range regions)
if (isInputRange!Range && is(ElementType!Range : Region!Args, Args...))
{
alias Region = Unqual!(ElementType!Range);
// dfmt off
return Region(regions
.map!"a._intervals.dup"
.join);
// dfmt on
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
R emptyRegion;
TI emptyTI;
auto region = R(0, 0, 10);
auto ti = TI(0, 0, 10);
assert(empty(emptyRegion));
assert(empty(emptyTI));
assert(!empty(region));
assert(!empty(ti));
}
/**
Returns the minimum/supremum point of the intervals. Both values are
undefined for empty regions.
Throws: MismatchingTagsException if `tag`s differ.
Throws: EmptyRegionException if region is empty.
*/
auto min(R)(R region) if (is(R : Region!Args, Args...))
{
alias TI = R.TaggedInterval;
enforceNonEmpty(region);
auto convexHull = TI.convexHull(region.intervals[0], region.intervals[$ - 1]);
return convexHull.begin;
}
/// ditto
auto sup(R)(R region) if (is(R : Region!Args, Args...))
{
alias TI = R.TaggedInterval;
enforceNonEmpty(region);
auto convexHull = TI.convexHull(region.intervals[0], region.intervals[$ - 1]);
return convexHull.end;
}
///
unittest
{
alias R = Region!(int, int);
alias TI = R.TaggedInterval;
R emptyRegion;
auto region1 = R([TI(0, 0, 10), TI(0, 20, 30)]);
auto region2 = R([TI(0, 0, 10), TI(1, 0, 10)]);
assert(min(region1) == 0);
assert(sup(region1) == 30);
assertThrown!EmptyRegionException(min(emptyRegion));
assertThrown!EmptyRegionException(sup(emptyRegion));
assertThrown!(MismatchingTagsException!int)(min(region2));
assertThrown!(MismatchingTagsException!int)(sup(region2));
}
|
D
|
/*******************************************************************************
* Copyright (c) 2000, 2008 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 org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.TreeListener;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.GCData;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.internal.ImageList;
import org.eclipse.swt.internal.win32.OS;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TypedListener;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.swt.widgets.Table;
import java.lang.all;
/**
* Instances of this class provide a selectable user interface object
* that displays a hierarchy of items and issues notification when an
* item in the hierarchy is selected.
* <p>
* The item children that may be added to instances of this class
* must be of type <code>TreeItem</code>.
* </p><p>
* Style <code>VIRTUAL</code> is used to create a <code>Tree</code> whose
* <code>TreeItem</code>s are to be populated by the client on an on-demand basis
* instead of up-front. This can provide significant performance improvements for
* trees that are very large or for which <code>TreeItem</code> population is
* expensive (for example, retrieving values from an external source).
* </p><p>
* Here is an example of using a <code>Tree</code> with style <code>VIRTUAL</code>:
* <code><pre>
* final Tree tree = new Tree(parent, SWT.VIRTUAL | SWT.BORDER);
* tree.setItemCount(20);
* tree.addListener(SWT.SetData, new Listener() {
* public void handleEvent(Event event) {
* TreeItem item = (TreeItem)event.item;
* TreeItem parentItem = item.getParentItem();
* String text = null;
* if (parentItem is null) {
* text = "node " + tree.indexOf(item);
* } else {
* text = parentItem.getText() + " - " + parentItem.indexOf(item);
* }
* item.setText(text);
* System.out.println(text);
* item.setItemCount(10);
* }
* });
* </pre></code>
* </p><p>
* Note that although this class is a subclass of <code>Composite</code>,
* it does not normally make sense to add <code>Control</code> children to
* it, or set a layout on it, unless implementing something like a cell
* editor.
* </p><p>
* <dl>
* <dt><b>Styles:</b></dt>
* <dd>SINGLE, MULTI, CHECK, FULL_SELECTION, VIRTUAL, NO_SCROLL</dd>
* <dt><b>Events:</b></dt>
* <dd>Selection, DefaultSelection, Collapse, Expand, SetData, MeasureItem, EraseItem, PaintItem</dd>
* </dl>
* </p><p>
* Note: Only one of the styles SINGLE and MULTI may be specified.
* </p><p>
* IMPORTANT: This class is <em>not</em> intended to be subclassed.
* </p>
*
* @see <a href="http://www.eclipse.org/swt/snippets/#tree">Tree, TreeItem, TreeColumn snippets</a>
* @see <a href="http://www.eclipse.org/swt/examples.php">SWT Example: ControlExample</a>
* @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a>
*/
public class Tree : Composite {
alias computeSize = Composite.computeSize;
alias setBackgroundImage = Composite.setBackgroundImage;
alias setBounds = Composite.setBounds;
alias setCursor = Composite.setCursor;
alias sort = Composite.sort;
TreeItem[] items;
TreeColumn[] columns;
int columnCount;
ImageList imageList, headerImageList;
TreeItem currentItem;
TreeColumn sortColumn;
RECT* focusRect;
HWND hwndParent, hwndHeader;
HANDLE hAnchor, hInsert, hSelect;
int lastID;
HANDLE hFirstIndexOf, hLastIndexOf;
int lastIndexOf, itemCount, sortDirection;
bool dragStarted, gestureCompleted, insertAfter, shrink, ignoreShrink;
bool ignoreSelect, ignoreExpand, ignoreDeselect, ignoreResize;
bool lockSelection, oldSelected, newSelected, ignoreColumnMove;
bool linesVisible, customDraw, printClient, painted, ignoreItemHeight;
bool ignoreCustomDraw, ignoreDrawForeground, ignoreDrawBackground, ignoreDrawFocus;
bool ignoreDrawSelection, ignoreDrawHot, ignoreFullSelection, explorerTheme;
int scrollWidth, selectionForeground;
HANDLE headerToolTipHandle, itemToolTipHandle;
static const int INSET = 3;
static const int GRID_WIDTH = 1;
static const int SORT_WIDTH = 10;
static const int HEADER_MARGIN = 12;
static const int HEADER_EXTRA = 3;
static const int INCREMENT = 5;
static const int EXPLORER_EXTRA = 2;
static const int DRAG_IMAGE_SIZE = 301;
static const bool EXPLORER_THEME = true;
mixin(gshared!(`private static /+const+/ WNDPROC TreeProc;`));
mixin(gshared!(`static const TCHAR[] TreeClass = OS.WC_TREEVIEW;`));
mixin(gshared!(`private static /+const+/ WNDPROC HeaderProc;`));
mixin(gshared!(`static const TCHAR[] HeaderClass = OS.WC_HEADER;`));
mixin(gshared!(`private static bool static_this_completed = false;`));
private static void static_this() {
if (static_this_completed) {
return;
}
synchronized {
if (static_this_completed) {
return;
}
WNDCLASS lpWndClass;
OS.GetClassInfo(null, TreeClass.ptr, &lpWndClass);
TreeProc = lpWndClass.lpfnWndProc;
OS.GetClassInfo(null, HeaderClass.ptr, &lpWndClass);
HeaderProc = lpWndClass.lpfnWndProc;
static_this_completed = true;
}
}
mixin(gshared!(`private static Tree sThis;`));
/**
* Constructs a new instance of this class given its parent
* and a style value describing its behavior and appearance.
* <p>
* The style value is either one of the style constants defined in
* class <code>SWT</code> which is applicable to instances of this
* class, or must be built by <em>bitwise OR</em>'ing together
* (that is, using the <code>int</code> "|" operator) two or more
* of those <code>SWT</code> style constants. The class description
* lists the style constants that are applicable to the class.
* Style bits are also inherited from superclasses.
* </p>
*
* @param parent a composite control which will be the parent of the new instance (cannot be null)
* @param style the style of control to construct
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent</li>
* <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li>
* </ul>
*
* @see SWT#SINGLE
* @see SWT#MULTI
* @see SWT#CHECK
* @see SWT#FULL_SELECTION
* @see SWT#VIRTUAL
* @see SWT#NO_SCROLL
* @see Widget#checkSubclass
* @see Widget#getStyle
*/
public this(Composite parent, int style) {
static_this();
super(parent, checkStyle(style));
}
static int checkStyle(int style) {
/*
* Feature in Windows. Even when WS_HSCROLL or
* WS_VSCROLL is not specified, Windows creates
* trees and tables with scroll bars. The fix
* is to set H_SCROLL and V_SCROLL.
*
* NOTE: This code appears on all platforms so that
* applications have consistent scroll bar behavior.
*/
if ((style & SWT.NO_SCROLL) is 0) {
style |= SWT.H_SCROLL | SWT.V_SCROLL;
}
/*
* Note: Windows only supports TVS_NOSCROLL and TVS_NOHSCROLL.
*/
if ((style & SWT.H_SCROLL) !is 0 && (style & SWT.V_SCROLL) is 0) {
style |= SWT.V_SCROLL;
}
return checkBits(style, SWT.SINGLE, SWT.MULTI, 0, 0, 0, 0);
}
override void _addListener(int eventType, Listener listener) {
super._addListener(eventType, listener);
switch (eventType) {
case SWT.DragDetect: {
if ((state & DRAG_DETECT) !is 0) {
int bits = OS.GetWindowLong(handle, OS.GWL_STYLE);
bits &= ~OS.TVS_DISABLEDRAGDROP;
OS.SetWindowLong(handle, OS.GWL_STYLE, bits);
}
break;
}
case SWT.MeasureItem:
case SWT.EraseItem:
case SWT.PaintItem: {
customDraw = true;
style |= SWT.DOUBLE_BUFFERED;
if (isCustomToolTip())
createItemToolTips();
OS.SendMessage(handle, OS.TVM_SETSCROLLTIME, 0, 0);
int bits = OS.GetWindowLong(handle, OS.GWL_STYLE);
if (eventType is SWT.MeasureItem) {
/*
* This code is intentionally commented.
*/
// if (explorerTheme) {
// int bits1 = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETEXTENDEDSTYLE, 0, 0);
// bits1 &= ~OS.TVS_EX_AUTOHSCROLL;
// OS.SendMessage (handle, OS.TVM_SETEXTENDEDSTYLE, 0, bits1);
// }
bits |= OS.TVS_NOHSCROLL;
}
/*
* Feature in Windows. When the tree has the style
* TVS_FULLROWSELECT, the background color for the
* entire row is filled when an item is painted,
* drawing on top of any custom drawing. The fix
* is to clear TVS_FULLROWSELECT.
*/
if ((style & SWT.FULL_SELECTION) !is 0) {
if (eventType !is SWT.MeasureItem) {
if (!explorerTheme)
bits &= ~OS.TVS_FULLROWSELECT;
}
}
if (bits !is OS.GetWindowLong(handle, OS.GWL_STYLE)) {
OS.SetWindowLong(handle, OS.GWL_STYLE, bits);
OS.InvalidateRect(handle, null, true);
/*
* Bug in Windows. When TVS_NOHSCROLL is set after items
* have been inserted into the tree, Windows shows the
* scroll bar. The fix is to check for this case and
* explicitly hide the scroll bar.
*/
auto count = OS.SendMessage(handle, OS.TVM_GETCOUNT, 0, 0);
if (count !is 0 && (bits & OS.TVS_NOHSCROLL) !is 0) {
static if (!OS.IsWinCE)
OS.ShowScrollBar(handle, OS.SB_HORZ, false);
}
}
break;
}
default:
}
}
TreeItem _getItem(HANDLE hItem) {
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM;
tvItem.hItem = cast(HTREEITEM) hItem;
if (OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem) !is 0) {
return _getItem(tvItem.hItem, tvItem.lParam);
}
return null;
}
TreeItem _getItem(HANDLE hItem, LPARAM id) {
if ((style & SWT.VIRTUAL) is 0)
return items[id];
return id !is -1 ? items[id] : new TreeItem(this, SWT.NONE,
cast(HANDLE)-1, cast(HANDLE)-1, hItem);
}
void _setBackgroundPixel(int newPixel) {
auto oldPixel = OS.SendMessage(handle, OS.TVM_GETBKCOLOR, 0, 0);
if (oldPixel !is newPixel) {
/*
* Bug in Windows. When TVM_SETBKCOLOR is used more
* than once to set the background color of a tree,
* the background color of the lines and the plus/minus
* does not change to the new color. The fix is to set
* the background color to the default before setting
* the new color.
*/
if (oldPixel !is -1) {
OS.SendMessage(handle, OS.TVM_SETBKCOLOR, 0, -1);
}
/* Set the background color */
OS.SendMessage(handle, OS.TVM_SETBKCOLOR, 0, newPixel);
/*
* Feature in Windows. When TVM_SETBKCOLOR is used to
* set the background color of a tree, the plus/minus
* animation draws badly. The fix is to clear the effect.
*/
if (explorerTheme) {
auto bits2 = OS.SendMessage(handle, OS.TVM_GETEXTENDEDSTYLE, 0, 0);
if (newPixel is -1 && findImageControl() is null) {
bits2 |= OS.TVS_EX_FADEINOUTEXPANDOS;
}
else {
bits2 &= ~OS.TVS_EX_FADEINOUTEXPANDOS;
}
OS.SendMessage(handle, OS.TVM_SETEXTENDEDSTYLE, 0, bits2);
}
/* Set the checkbox image list */
if ((style & SWT.CHECK) !is 0)
setCheckboxImageList();
}
}
/**
* Adds the listener to the collection of listeners who will
* be notified when the user changes the receiver's selection, by sending
* it one of the messages defined in the <code>SelectionListener</code>
* interface.
* <p>
* When <code>widgetSelected</code> is called, the item field of the event object is valid.
* If the receiver has the <code>SWT.CHECK</code> style and the check selection changes,
* the event object detail field contains the value <code>SWT.CHECK</code>.
* <code>widgetDefaultSelected</code> is typically called when an item is double-clicked.
* The item field of the event object is valid for default selection, but the detail field is not used.
* </p>
*
* @param listener the listener which should be notified when the user changes the receiver's selection
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see SelectionListener
* @see #removeSelectionListener
* @see SelectionEvent
*/
public void addSelectionListener(SelectionListener listener) {
checkWidget();
if (listener is null)
error(SWT.ERROR_NULL_ARGUMENT);
TypedListener typedListener = new TypedListener(listener);
addListener(SWT.Selection, typedListener);
addListener(SWT.DefaultSelection, typedListener);
}
/**
* Adds the listener to the collection of listeners who will
* be notified when an item in the receiver is expanded or collapsed
* by sending it one of the messages defined in the <code>TreeListener</code>
* interface.
*
* @param listener the listener which should be notified
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see TreeListener
* @see #removeTreeListener
*/
public void addTreeListener(TreeListener listener) {
checkWidget();
if (listener is null)
error(SWT.ERROR_NULL_ARGUMENT);
TypedListener typedListener = new TypedListener(listener);
addListener(SWT.Expand, typedListener);
addListener(SWT.Collapse, typedListener);
}
override HWND borderHandle() {
return hwndParent !is null ? hwndParent : handle;
}
LRESULT CDDS_ITEMPOSTPAINT(NMTVCUSTOMDRAW* nmcd, WPARAM wParam, LPARAM lParam) {
if (ignoreCustomDraw)
return null;
if (nmcd.nmcd.rc.left is nmcd.nmcd.rc.right)
return new LRESULT(OS.CDRF_DODEFAULT);
auto hDC = nmcd.nmcd.hdc;
OS.RestoreDC(hDC, -1);
TreeItem item = getItem(nmcd);
/*
* Feature in Windows. When a new tree item is inserted
* using TVM_INSERTITEM and the tree is using custom draw,
* a NM_CUSTOMDRAW is sent before TVM_INSERTITEM returns
* and before the item is added to the items array. The
* fix is to check for null.
*
* NOTE: This only happens on XP with the version 6.00 of
* COMCTL32.DLL,
*/
if (item is null)
return null;
/*
* Feature in Windows. Under certain circumstances, Windows
* sends CDDS_ITEMPOSTPAINT for an empty rectangle. This is
* not a problem providing that graphics do not occur outside
* the rectangle. The fix is to test for the rectangle and
* draw nothing.
*
* NOTE: This seems to happen when both I_IMAGECALLBACK
* and LPSTR_TEXTCALLBACK are used at the same time with
* TVM_SETITEM.
*/
if (nmcd.nmcd.rc.left >= nmcd.nmcd.rc.right || nmcd.nmcd.rc.top >= nmcd.nmcd.rc.bottom)
return null;
if (!OS.IsWindowVisible(handle))
return null;
if ((style & SWT.FULL_SELECTION) !is 0 || findImageControl() !is null
|| ignoreDrawSelection || explorerTheme) {
OS.SetBkMode(hDC, OS.TRANSPARENT);
}
bool selected = isItemSelected(nmcd);
bool hot = explorerTheme && (nmcd.nmcd.uItemState & OS.CDIS_HOT) !is 0;
if (OS.IsWindowEnabled(handle)) {
if (explorerTheme) {
int bits = OS.GetWindowLong(handle, OS.GWL_STYLE);
if ((bits & OS.TVS_TRACKSELECT) !is 0) {
if ((style & SWT.FULL_SELECTION) !is 0 && (selected || hot)) {
OS.SetTextColor(hDC, OS.GetSysColor(OS.COLOR_WINDOWTEXT));
}
else {
OS.SetTextColor(hDC, getForegroundPixel());
}
}
}
}
int[] order = null;
RECT clientRect;
OS.GetClientRect(scrolledHandle(), &clientRect);
if (hwndHeader !is null) {
OS.MapWindowPoints(hwndParent, handle, cast(POINT*)&clientRect, 2);
if (columnCount !is 0) {
order = new int[columnCount];
OS.SendMessage(hwndHeader, OS.HDM_GETORDERARRAY, columnCount, order.ptr);
}
}
int sortIndex = -1, clrSortBk = -1;
if (OS.COMCTL32_MAJOR >= 6 && OS.IsAppThemed()) {
if (sortColumn !is null && sortDirection !is SWT.NONE) {
if (findImageControl() is null) {
sortIndex = indexOf(sortColumn);
clrSortBk = getSortColumnPixel();
}
}
}
int x = 0;
Point size = null;
for (int i = 0; i < Math.max(1, columnCount); i++) {
int index = order is null ? i : order[i], width = nmcd.nmcd.rc.right - nmcd
.nmcd.rc.left;
if (columnCount > 0 && hwndHeader !is null) {
HDITEM hdItem;
hdItem.mask = OS.HDI_WIDTH;
OS.SendMessage(hwndHeader, OS.HDM_GETITEM, index, &hdItem);
width = hdItem.cxy;
}
if (i is 0) {
if ((style & SWT.FULL_SELECTION) !is 0) {
bool clear = !explorerTheme && !ignoreDrawSelection && findImageControl() is null;
if (clear || (selected && !ignoreDrawSelection) || (hot && !ignoreDrawHot)) {
bool draw = true;
RECT pClipRect;
OS.SetRect(&pClipRect, width, nmcd.nmcd.rc.top,
nmcd.nmcd.rc.right, nmcd.nmcd.rc.bottom);
if (explorerTheme) {
if (hooks(SWT.EraseItem)) {
RECT* itemRect = item.getBounds(index, true,
true, false, false, true, hDC);
itemRect.left -= EXPLORER_EXTRA;
itemRect.right += EXPLORER_EXTRA + 1;
pClipRect.left = itemRect.left;
pClipRect.right = itemRect.right;
if (columnCount > 0 && hwndHeader !is null) {
HDITEM hdItem;
hdItem.mask = OS.HDI_WIDTH;
OS.SendMessage(hwndHeader, OS.HDM_GETITEM, index, &hdItem);
pClipRect.right = Math.min(pClipRect.right,
nmcd.nmcd.rc.left + hdItem.cxy);
}
}
RECT pRect;
OS.SetRect(&pRect, nmcd.nmcd.rc.left,
nmcd.nmcd.rc.top, nmcd.nmcd.rc.right, nmcd.nmcd.rc.bottom);
if (columnCount > 0 && hwndHeader !is null) {
int totalWidth = 0;
HDITEM hdItem;
hdItem.mask = OS.HDI_WIDTH;
for (int j = 0; j < columnCount; j++) {
OS.SendMessage(hwndHeader, OS.HDM_GETITEM, j, &hdItem);
totalWidth += hdItem.cxy;
}
if (totalWidth > clientRect.right - clientRect.left) {
pRect.left = 0;
pRect.right = totalWidth;
}
else {
pRect.left = clientRect.left;
pRect.right = clientRect.right;
}
}
draw = false;
auto hTheme = OS.OpenThemeData(handle, cast(TCHAR*) Display.TREEVIEW);
int iStateId = selected ? OS.TREIS_SELECTED : OS.TREIS_HOT;
if (OS.GetFocus() !is handle && selected && !hot)
iStateId = OS.TREIS_SELECTEDNOTFOCUS;
OS.DrawThemeBackground(hTheme, hDC,
OS.TVP_TREEITEM, iStateId, &pRect, &pClipRect);
OS.CloseThemeData(hTheme);
}
if (draw)
fillBackground(hDC, OS.GetBkColor(hDC), &pClipRect);
}
}
}
if (x + width > clientRect.left) {
RECT* rect = new RECT(), backgroundRect = null;
bool drawItem = true, drawText = true, drawImage = true, drawBackground_ = false;
if (i is 0) {
drawItem = drawImage = drawText = false;
if (findImageControl() !is null) {
if (explorerTheme) {
if (OS.IsWindowEnabled(handle) && !hooks(SWT.EraseItem)) {
Image image = null;
if (index is 0) {
image = item.image;
}
else {
Image[] images = item.images;
if (images !is null)
image = images[index];
}
if (image !is null) {
Rectangle bounds = image.getBounds();
if (size is null)
size = getImageSize();
if (!ignoreDrawForeground) {
GCData data = new GCData();
data.device = display;
GC gc = GC.win32_new(hDC, data);
RECT* iconRect = item.getBounds(index,
false, true, false, false, true, hDC);
gc.setClipping(iconRect.left, iconRect.top,
iconRect.right - iconRect.left,
iconRect.bottom - iconRect.top);
gc.drawImage(image, 0, 0, bounds.width, bounds.height,
iconRect.left, iconRect.top, size.x, size.y);
OS.SelectClipRgn(hDC, null);
gc.dispose();
}
}
}
}
else {
drawItem = drawText = drawBackground_ = true;
rect = item.getBounds(index, true, false, false, false, true, hDC);
if (linesVisible) {
rect.right++;
rect.bottom++;
}
}
}
if (selected && !ignoreDrawSelection && !ignoreDrawBackground) {
if (!explorerTheme)
fillBackground(hDC, OS.GetBkColor(hDC), rect);
drawBackground_ = false;
}
backgroundRect = rect;
if (hooks(SWT.EraseItem)) {
drawItem = drawText = drawImage = true;
rect = item.getBounds(index, true, true, false, false, true, hDC);
if ((style & SWT.FULL_SELECTION) !is 0) {
backgroundRect = rect;
}
else {
backgroundRect = item.getBounds(index, true, false,
false, false, true, hDC);
}
}
}
else {
selectionForeground = -1;
ignoreDrawForeground = ignoreDrawBackground = ignoreDrawSelection = ignoreDrawFocus = ignoreDrawHot = false;
OS.SetRect(rect, x, nmcd.nmcd.rc.top, x + width, nmcd.nmcd.rc.bottom);
backgroundRect = rect;
}
int clrText = -1, clrTextBk = -1;
auto hFont = item.fontHandle(index);
if (selectionForeground !is -1)
clrText = selectionForeground;
if (OS.IsWindowEnabled(handle)) {
bool drawForeground = false;
if (selected) {
if (i !is 0 && (style & SWT.FULL_SELECTION) is 0) {
OS.SetTextColor(hDC, getForegroundPixel());
OS.SetBkColor(hDC, getBackgroundPixel());
drawForeground = drawBackground_ = true;
}
}
else {
drawForeground = drawBackground_ = true;
}
if (drawForeground) {
clrText = item.cellForeground !is null ? item.cellForeground[index] : -1;
if (clrText is -1)
clrText = item.foreground;
}
if (drawBackground_) {
clrTextBk = item.cellBackground !is null ? item.cellBackground[index] : -1;
if (clrTextBk is -1)
clrTextBk = item.background;
if (clrTextBk is -1 && index is sortIndex)
clrTextBk = clrSortBk;
}
}
else {
if (clrTextBk is -1 && index is sortIndex) {
drawBackground_ = true;
clrTextBk = clrSortBk;
}
}
if (explorerTheme) {
if (selected || (nmcd.nmcd.uItemState & OS.CDIS_HOT) !is 0) {
if ((style & SWT.FULL_SELECTION) !is 0) {
drawBackground_ = false;
}
else {
if (i is 0) {
drawBackground_ = false;
if (!hooks(SWT.EraseItem))
drawText = false;
}
}
}
}
if (drawItem) {
if (i !is 0) {
if (hooks(SWT.MeasureItem)) {
sendMeasureItemEvent(item, index, hDC);
if (isDisposed() || item.isDisposed())
break;
}
if (hooks(SWT.EraseItem)) {
RECT* cellRect = item.getBounds(index, true, true,
true, true, true, hDC);
int nSavedDC = OS.SaveDC(hDC);
GCData data = new GCData();
data.device = display;
data.foreground = OS.GetTextColor(hDC);
data.background = OS.GetBkColor(hDC);
if (!selected || (style & SWT.FULL_SELECTION) is 0) {
if (clrText !is -1)
data.foreground = clrText;
if (clrTextBk !is -1)
data.background = clrTextBk;
}
data.font = item.getFont(index);
data.uiState = cast(int) /*64bit*/ OS.SendMessage(handle,
OS.WM_QUERYUISTATE, 0, 0);
GC gc = GC.win32_new(hDC, data);
Event event = new Event();
event.item = item;
event.index = index;
event.gc = gc;
event.detail |= SWT.FOREGROUND;
if (clrTextBk !is -1)
event.detail |= SWT.BACKGROUND;
if ((style & SWT.FULL_SELECTION) !is 0) {
if (hot)
event.detail |= SWT.HOT;
if (selected)
event.detail |= SWT.SELECTED;
if (!explorerTheme) {
//if ((nmcd.uItemState & OS.CDIS_FOCUS) !is 0) {
if (OS.SendMessage(handle, OS.TVM_GETNEXTITEM,
OS.TVGN_CARET, 0) is nmcd.nmcd.dwItemSpec) {
if (handle is OS.GetFocus()) {
auto uiState = OS.SendMessage(handle,
OS.WM_QUERYUISTATE, 0, 0);
if ((uiState & OS.UISF_HIDEFOCUS) is 0)
event.detail |= SWT.FOCUSED;
}
}
}
}
event.x = cellRect.left;
event.y = cellRect.top;
event.width = cellRect.right - cellRect.left;
event.height = cellRect.bottom - cellRect.top;
gc.setClipping(event.x, event.y, event.width, event.height);
sendEvent(SWT.EraseItem, event);
event.gc = null;
int newTextClr = data.foreground;
gc.dispose();
OS.RestoreDC(hDC, nSavedDC);
if (isDisposed() || item.isDisposed())
break;
if (event.doit) {
ignoreDrawForeground = (event.detail & SWT.FOREGROUND) is 0;
ignoreDrawBackground = (event.detail & SWT.BACKGROUND) is 0;
if ((style & SWT.FULL_SELECTION) !is 0) {
ignoreDrawSelection = (event.detail & SWT.SELECTED) is 0;
ignoreDrawFocus = (event.detail & SWT.FOCUSED) is 0;
ignoreDrawHot = (event.detail & SWT.HOT) is 0;
}
}
else {
ignoreDrawForeground = ignoreDrawBackground = ignoreDrawSelection = ignoreDrawFocus = ignoreDrawHot = true;
}
if (selected && ignoreDrawSelection)
ignoreDrawHot = true;
if ((style & SWT.FULL_SELECTION) !is 0) {
if (ignoreDrawSelection)
ignoreFullSelection = true;
if (!ignoreDrawSelection || !ignoreDrawHot) {
if (!selected && !hot) {
selectionForeground = OS.GetSysColor(
OS.COLOR_HIGHLIGHTTEXT);
}
else {
if (!explorerTheme) {
drawBackground_ = true;
ignoreDrawBackground = false;
if ((handle is OS.GetFocus() || display.getHighContrast())
&& OS.IsWindowEnabled(handle)) {
clrTextBk = OS.GetSysColor(OS.COLOR_HIGHLIGHT);
}
else {
clrTextBk = OS.GetSysColor(OS.COLOR_3DFACE);
}
if (!ignoreFullSelection && index is columnCount - 1) {
RECT* selectionRect = new RECT();
OS.SetRect(selectionRect, backgroundRect.left, backgroundRect.top,
nmcd.nmcd.rc.right, backgroundRect.bottom);
backgroundRect = selectionRect;
}
}
else {
RECT pRect;
OS.SetRect(&pRect, nmcd.nmcd.rc.left,
nmcd.nmcd.rc.top, nmcd.nmcd.rc.right,
nmcd.nmcd.rc.bottom);
if (columnCount > 0 && hwndHeader !is null) {
int totalWidth = 0;
HDITEM hdItem;
hdItem.mask = OS.HDI_WIDTH;
for (int j = 0; j < columnCount; j++) {
OS.SendMessage(hwndHeader,
OS.HDM_GETITEM, j, &hdItem);
totalWidth += hdItem.cxy;
}
if (totalWidth > clientRect.right - clientRect.left) {
pRect.left = 0;
pRect.right = totalWidth;
}
else {
pRect.left = clientRect.left;
pRect.right = clientRect.right;
}
if (index is columnCount - 1) {
RECT* selectionRect = new RECT();
OS.SetRect(selectionRect, backgroundRect.left, backgroundRect.top,
pRect.right, backgroundRect.bottom);
backgroundRect = selectionRect;
}
}
auto hTheme = OS.OpenThemeData(handle,
cast(TCHAR*) Display.TREEVIEW);
int iStateId = selected ? OS.TREIS_SELECTED
: OS.TREIS_HOT;
if (OS.GetFocus() !is handle && selected && !hot)
iStateId = OS.TREIS_SELECTEDNOTFOCUS;
OS.DrawThemeBackground(hTheme, hDC, OS.TVP_TREEITEM,
iStateId, &pRect, backgroundRect);
OS.CloseThemeData(hTheme);
}
}
}
else {
if (selected) {
selectionForeground = newTextClr;
if (!explorerTheme) {
if (clrTextBk is -1 && OS.IsWindowEnabled(handle)) {
Control control = findBackgroundControl();
if (control is null)
control = this;
clrTextBk = control.getBackgroundPixel();
}
}
}
}
}
}
if (selectionForeground !is -1)
clrText = selectionForeground;
}
if (!ignoreDrawBackground) {
if (clrTextBk !is -1) {
if (drawBackground_)
fillBackground(hDC, clrTextBk, backgroundRect);
}
else {
Control control = findImageControl();
if (control !is null) {
if (i is 0) {
int right = Math.min(rect.right, width);
OS.SetRect(rect, rect.left, rect.top, right, rect.bottom);
if (drawBackground_)
fillImageBackground(hDC, control, rect);
}
else {
if (drawBackground_)
fillImageBackground(hDC, control, rect);
}
}
}
}
rect.left += INSET - 1;
if (drawImage) {
Image image = null;
if (index is 0) {
image = item.image;
}
else {
Image[] images = item.images;
if (images !is null)
image = images[index];
}
int inset = i !is 0 ? INSET : 0;
int offset = i !is 0 ? INSET : INSET + 2;
if (image !is null) {
Rectangle bounds = image.getBounds();
if (size is null)
size = getImageSize();
if (!ignoreDrawForeground) {
//int y1 = rect.top + (index is 0 ? (getItemHeight () - size.y) / 2 : 0);
int y1 = rect.top;
int x1 = Math.max(rect.left, rect.left - inset + 1);
GCData data = new GCData();
data.device = display;
GC gc = GC.win32_new(hDC, data);
gc.setClipping(x1, rect.top, rect.right - x1,
rect.bottom - rect.top);
gc.drawImage(image, 0, 0, bounds.width,
bounds.height, x1, y1, size.x, size.y);
OS.SelectClipRgn(hDC, null);
gc.dispose();
}
OS.SetRect(rect, rect.left + size.x + offset,
rect.top, rect.right - inset, rect.bottom);
}
else {
if (i is 0) {
if (OS.SendMessage(handle, OS.TVM_GETIMAGELIST,
OS.TVSIL_NORMAL, 0) !is 0) {
if (size is null)
size = getImageSize();
rect.left = Math.min(rect.left + size.x + offset, rect.right);
}
}
else {
OS.SetRect(rect, rect.left + offset, rect.top,
rect.right - inset, rect.bottom);
}
}
}
if (drawText) {
/*
* Bug in Windows. When DrawText() is used with DT_VCENTER
* and DT_ENDELLIPSIS, the ellipsis can draw outside of the
* rectangle when the rectangle is empty. The fix is avoid
* all text drawing for empty rectangles.
*/
if (rect.left < rect.right) {
String string = null;
if (index is 0) {
string = item.text;
}
else {
String[] strings = item.strings;
if (strings !is null)
string = strings[index];
}
if (string !is null) {
if (hFont !is cast(HFONT)-1)
hFont = cast(HFONT) OS.SelectObject(hDC, hFont);
if (clrText !is -1)
clrText = OS.SetTextColor(hDC, clrText);
if (clrTextBk !is -1)
clrTextBk = OS.SetBkColor(hDC, clrTextBk);
int flags = OS.DT_NOPREFIX | OS.DT_SINGLELINE | OS.DT_VCENTER;
if (i !is 0)
flags |= OS.DT_ENDELLIPSIS;
TreeColumn column = columns !is null ? columns[index] : null;
if (column !is null) {
if ((column.style & SWT.CENTER) !is 0)
flags |= OS.DT_CENTER;
if ((column.style & SWT.RIGHT) !is 0)
flags |= OS.DT_RIGHT;
}
StringT buffer = StrToTCHARs(getCodePage(), string, false);
if (!ignoreDrawForeground)
OS.DrawText(hDC, buffer.ptr,
cast(int) /*64bit*/ buffer.length, rect, flags);
OS.DrawText(hDC, buffer.ptr, cast(int) /*64bit*/ buffer.length,
rect, flags | OS.DT_CALCRECT);
if (hFont !is cast(HFONT)-1)
hFont = cast(HFONT) OS.SelectObject(hDC, hFont);
if (clrText !is -1)
clrText = OS.SetTextColor(hDC, clrText);
if (clrTextBk !is -1)
clrTextBk = OS.SetBkColor(hDC, clrTextBk);
}
}
}
}
if (selectionForeground !is -1)
clrText = selectionForeground;
if (hooks(SWT.PaintItem)) {
RECT* itemRect = item.getBounds(index, true, true, false, false, false, hDC);
int nSavedDC = OS.SaveDC(hDC);
GCData data = new GCData();
data.device = display;
data.font = item.getFont(index);
data.foreground = OS.GetTextColor(hDC);
data.background = OS.GetBkColor(hDC);
if (selected && (style & SWT.FULL_SELECTION) !is 0) {
if (selectionForeground !is -1)
data.foreground = selectionForeground;
}
else {
if (clrText !is -1)
data.foreground = clrText;
if (clrTextBk !is -1)
data.background = clrTextBk;
}
data.uiState = cast(int) /*64bit*/ OS.SendMessage(handle,
OS.WM_QUERYUISTATE, 0, 0);
GC gc = GC.win32_new(hDC, data);
Event event = new Event();
event.item = item;
event.index = index;
event.gc = gc;
event.detail |= SWT.FOREGROUND;
if (clrTextBk !is -1)
event.detail |= SWT.BACKGROUND;
if (hot)
event.detail |= SWT.HOT;
if (selected && (i is 0 /*nmcd.iSubItem is 0*/
|| (style & SWT.FULL_SELECTION) !is 0)) {
event.detail |= SWT.SELECTED;
}
if (!explorerTheme) {
//if ((nmcd.uItemState & OS.CDIS_FOCUS) !is 0) {
if (OS.SendMessage(handle, OS.TVM_GETNEXTITEM,
OS.TVGN_CARET, 0) is nmcd.nmcd.dwItemSpec) {
if (i is 0 /*nmcd.iSubItem is 0*/ || (style & SWT.FULL_SELECTION) !is 0) {
if (handle is OS.GetFocus()) {
auto uiState = OS.SendMessage(handle, OS.WM_QUERYUISTATE, 0, 0);
if ((uiState & OS.UISF_HIDEFOCUS) is 0)
event.detail |= SWT.FOCUSED;
}
}
}
}
event.x = itemRect.left;
event.y = itemRect.top;
event.width = itemRect.right - itemRect.left;
event.height = itemRect.bottom - itemRect.top;
RECT* cellRect = item.getBounds(index, true, true, true, true, true, hDC);
int cellWidth = cellRect.right - cellRect.left;
int cellHeight = cellRect.bottom - cellRect.top;
gc.setClipping(cellRect.left, cellRect.top, cellWidth, cellHeight);
sendEvent(SWT.PaintItem, event);
if (data.focusDrawn)
focusRect = null;
event.gc = null;
gc.dispose();
OS.RestoreDC(hDC, nSavedDC);
if (isDisposed() || item.isDisposed())
break;
}
}
x += width;
if (x > clientRect.right)
break;
}
if (linesVisible) {
if ((style & SWT.FULL_SELECTION) !is 0) {
if (columnCount !is 0) {
HDITEM hdItem;
hdItem.mask = OS.HDI_WIDTH;
OS.SendMessage(hwndHeader, OS.HDM_GETITEM, 0, &hdItem);
RECT rect;
OS.SetRect(&rect, nmcd.nmcd.rc.left + hdItem.cxy,
nmcd.nmcd.rc.top, nmcd.nmcd.rc.right, nmcd.nmcd.rc.bottom);
OS.DrawEdge(hDC, &rect, OS.BDR_SUNKENINNER, OS.BF_BOTTOM);
}
}
RECT rect;
OS.SetRect(&rect, nmcd.nmcd.rc.left, nmcd.nmcd.rc.top,
nmcd.nmcd.rc.right, nmcd.nmcd.rc.bottom);
OS.DrawEdge(hDC, &rect, OS.BDR_SUNKENINNER, OS.BF_BOTTOM);
}
if (!ignoreDrawFocus && focusRect !is null) {
OS.DrawFocusRect(hDC, focusRect);
focusRect = null;
}
else {
if (!explorerTheme) {
if (handle is OS.GetFocus()) {
auto uiState = OS.SendMessage(handle, OS.WM_QUERYUISTATE, 0, 0);
if ((uiState & OS.UISF_HIDEFOCUS) is 0) {
auto hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
if (hItem is item.handle) {
if (!ignoreDrawFocus && findImageControl() !is null) {
if ((style & SWT.FULL_SELECTION) !is 0) {
RECT focusRect;
OS.SetRect(&focusRect, 0, nmcd.nmcd.rc.top,
clientRect.right + 1, nmcd.nmcd.rc.bottom);
OS.DrawFocusRect(hDC, &focusRect);
}
else {
int index = cast(int) /*64bit*/ OS.SendMessage(hwndHeader,
OS.HDM_ORDERTOINDEX, 0, 0);
RECT* focusRect = item.getBounds(index,
true, false, false, false, false, hDC);
RECT* clipRect = item.getBounds(index,
true, false, false, false, true, hDC);
OS.IntersectClipRect(hDC, clipRect.left,
clipRect.top, clipRect.right, clipRect.bottom);
OS.DrawFocusRect(hDC, focusRect);
OS.SelectClipRgn(hDC, null);
}
}
}
}
}
}
}
return new LRESULT(OS.CDRF_DODEFAULT);
}
LRESULT CDDS_ITEMPREPAINT(NMTVCUSTOMDRAW* nmcd, WPARAM wParam, LPARAM lParam) {
/*
* Even when custom draw is being ignored, the font needs
* to be selected into the HDC so that the item bounds are
* measured correctly.
*/
TreeItem item = getItem(nmcd);
/*
* Feature in Windows. When a new tree item is inserted
* using TVM_INSERTITEM and the tree is using custom draw,
* a NM_CUSTOMDRAW is sent before TVM_INSERTITEM returns
* and before the item is added to the items array. The
* fix is to check for null.
*
* NOTE: This only happens on XP with the version 6.00 of
* COMCTL32.DLL,
*/
if (item is null)
return null;
auto hDC = nmcd.nmcd.hdc;
int index = hwndHeader !is null ? cast(int) /*64bit*/ OS.SendMessage(hwndHeader,
OS.HDM_ORDERTOINDEX, 0, 0) : 0;
auto hFont = item.fontHandle(index);
if (hFont !is cast(HFONT)-1)
OS.SelectObject(hDC, hFont);
if (ignoreCustomDraw || nmcd.nmcd.rc.left is nmcd.nmcd.rc.right) {
return new LRESULT(hFont is cast(HFONT)-1 ? OS.CDRF_DODEFAULT : OS.CDRF_NEWFONT);
}
RECT* clipRect = null;
if (columnCount !is 0) {
bool clip = !printClient;
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0)) {
clip = true;
}
if (clip) {
clipRect = new RECT();
HDITEM hdItem;
hdItem.mask = OS.HDI_WIDTH;
OS.SendMessage(hwndHeader, OS.HDM_GETITEM, index, &hdItem);
OS.SetRect(clipRect, nmcd.nmcd.rc.left, nmcd.nmcd.rc.top,
nmcd.nmcd.rc.left + hdItem.cxy, nmcd.nmcd.rc.bottom);
}
}
int clrText = -1, clrTextBk = -1;
if (OS.IsWindowEnabled(handle)) {
clrText = item.cellForeground !is null ? item.cellForeground[index] : -1;
if (clrText is -1)
clrText = item.foreground;
clrTextBk = item.cellBackground !is null ? item.cellBackground[index] : -1;
if (clrTextBk is -1)
clrTextBk = item.background;
}
int clrSortBk = -1;
if (OS.COMCTL32_MAJOR >= 6 && OS.IsAppThemed()) {
if (sortColumn !is null && sortDirection !is SWT.NONE) {
if (findImageControl() is null) {
if (indexOf(sortColumn) is index) {
clrSortBk = getSortColumnPixel();
if (clrTextBk is -1)
clrTextBk = clrSortBk;
}
}
}
}
bool selected = isItemSelected(nmcd);
bool hot = explorerTheme && (nmcd.nmcd.uItemState & OS.CDIS_HOT) !is 0;
bool focused = explorerTheme && (nmcd.nmcd.uItemState & OS.CDIS_FOCUS) !is 0;
if (OS.IsWindowVisible(handle)
&& nmcd.nmcd.rc.left < nmcd.nmcd.rc.right && nmcd.nmcd.rc.top < nmcd.nmcd.rc.bottom) {
if (hFont !is cast(HFONT)-1)
OS.SelectObject(hDC, hFont);
if (linesVisible) {
RECT rect;
OS.SetRect(&rect, nmcd.nmcd.rc.left, nmcd.nmcd.rc.top,
nmcd.nmcd.rc.right, nmcd.nmcd.rc.bottom);
OS.DrawEdge(hDC, &rect, OS.BDR_SUNKENINNER, OS.BF_BOTTOM);
}
//TODO - BUG - measure and erase sent when first column is clipped
Event measureEvent = null;
if (hooks(SWT.MeasureItem)) {
measureEvent = sendMeasureItemEvent(item, index, hDC);
if (isDisposed() || item.isDisposed())
return null;
}
selectionForeground = -1;
ignoreDrawForeground = ignoreDrawBackground = ignoreDrawSelection = ignoreDrawFocus = ignoreDrawHot = ignoreFullSelection = false;
if (hooks(SWT.EraseItem)) {
RECT rect;
OS.SetRect(&rect, nmcd.nmcd.rc.left, nmcd.nmcd.rc.top,
nmcd.nmcd.rc.right, nmcd.nmcd.rc.bottom);
RECT* cellRect = item.getBounds(index, true, true, true, true, true, hDC);
if (clrSortBk !is -1) {
drawBackground(hDC, cellRect, clrSortBk);
}
else {
if (OS.IsWindowEnabled(handle) || findImageControl() !is null) {
drawBackground(hDC, &rect);
}
else {
fillBackground(hDC, OS.GetBkColor(hDC), &rect);
}
}
int nSavedDC = OS.SaveDC(hDC);
GCData data = new GCData();
data.device = display;
if (selected && explorerTheme) {
data.foreground = OS.GetSysColor(OS.COLOR_WINDOWTEXT);
}
else {
data.foreground = OS.GetTextColor(hDC);
}
data.background = OS.GetBkColor(hDC);
if (!selected) {
if (clrText !is -1)
data.foreground = clrText;
if (clrTextBk !is -1)
data.background = clrTextBk;
}
data.uiState = cast(int) /*64bit*/ OS.SendMessage(handle, OS.WM_QUERYUISTATE, 0, 0);
data.font = item.getFont(index);
GC gc = GC.win32_new(hDC, data);
Event event = new Event();
event.index = index;
event.item = item;
event.gc = gc;
event.detail |= SWT.FOREGROUND;
if (clrTextBk !is -1)
event.detail |= SWT.BACKGROUND;
if (hot)
event.detail |= SWT.HOT;
if (selected)
event.detail |= SWT.SELECTED;
if (!explorerTheme) {
//if ((nmcd.uItemState & OS.CDIS_FOCUS) !is 0) {
if (OS.SendMessage(handle, OS.TVM_GETNEXTITEM,
OS.TVGN_CARET, 0) is nmcd.nmcd.dwItemSpec) {
if (handle is OS.GetFocus()) {
auto uiState = OS.SendMessage(handle, OS.WM_QUERYUISTATE, 0, 0);
if ((uiState & OS.UISF_HIDEFOCUS) is 0) {
focused = true;
event.detail |= SWT.FOCUSED;
}
}
}
}
event.x = cellRect.left;
event.y = cellRect.top;
event.width = cellRect.right - cellRect.left;
event.height = cellRect.bottom - cellRect.top;
gc.setClipping(event.x, event.y, event.width, event.height);
sendEvent(SWT.EraseItem, event);
event.gc = null;
int newTextClr = data.foreground;
gc.dispose();
OS.RestoreDC(hDC, nSavedDC);
if (isDisposed() || item.isDisposed())
return null;
if (event.doit) {
ignoreDrawForeground = (event.detail & SWT.FOREGROUND) is 0;
ignoreDrawBackground = (event.detail & SWT.BACKGROUND) is 0;
ignoreDrawSelection = (event.detail & SWT.SELECTED) is 0;
ignoreDrawFocus = (event.detail & SWT.FOCUSED) is 0;
ignoreDrawHot = (event.detail & SWT.HOT) is 0;
}
else {
ignoreDrawForeground = ignoreDrawBackground = ignoreDrawSelection = ignoreDrawFocus = ignoreDrawHot = true;
}
if (selected && ignoreDrawSelection)
ignoreDrawHot = true;
if (!ignoreDrawBackground && clrTextBk !is -1) {
bool draw = !selected && !hot;
if (!explorerTheme && selected)
draw = !ignoreDrawSelection;
if (draw) {
if (columnCount is 0) {
if ((style & SWT.FULL_SELECTION) !is 0) {
fillBackground(hDC, clrTextBk, &rect);
}
else {
RECT* textRect = item.getBounds(index, true,
false, false, false, true, hDC);
if (measureEvent !is null) {
textRect.right = Math.min(cellRect.right,
measureEvent.x + measureEvent.width);
}
fillBackground(hDC, clrTextBk, textRect);
}
}
else {
fillBackground(hDC, clrTextBk, cellRect);
}
}
}
if (ignoreDrawSelection)
ignoreFullSelection = true;
if (!ignoreDrawSelection || !ignoreDrawHot) {
if (!selected && !hot) {
selectionForeground = clrText = OS.GetSysColor(OS.COLOR_HIGHLIGHTTEXT);
}
if (explorerTheme) {
if ((style & SWT.FULL_SELECTION) is 0) {
RECT* pRect = item.getBounds(index, true, true,
false, false, false, hDC);
RECT* pClipRect = item.getBounds(index, true, true,
true, false, true, hDC);
if (measureEvent !is null) {
pRect.right = Math.min(pClipRect.right,
measureEvent.x + measureEvent.width);
}
else {
pRect.right += EXPLORER_EXTRA;
pClipRect.right += EXPLORER_EXTRA;
}
pRect.left -= EXPLORER_EXTRA;
pClipRect.left -= EXPLORER_EXTRA;
auto hTheme = OS.OpenThemeData(handle, Display.TREEVIEW.ptr);
int iStateId = selected ? OS.TREIS_SELECTED : OS.TREIS_HOT;
if (OS.GetFocus() !is handle && selected && !hot)
iStateId = OS.TREIS_SELECTEDNOTFOCUS;
OS.DrawThemeBackground(hTheme, hDC,
OS.TVP_TREEITEM, iStateId, pRect, pClipRect);
OS.CloseThemeData(hTheme);
}
}
else {
/*
* Feature in Windows. When the tree has the style
* TVS_FULLROWSELECT, the background color for the
* entire row is filled when an item is painted,
* drawing on top of any custom drawing. The fix
* is to emulate TVS_FULLROWSELECT.
*/
if ((style & SWT.FULL_SELECTION) !is 0) {
if ((style & SWT.FULL_SELECTION) !is 0 && columnCount is 0) {
fillBackground(hDC, OS.GetBkColor(hDC), &rect);
}
else {
fillBackground(hDC, OS.GetBkColor(hDC), cellRect);
}
}
else {
RECT* textRect = item.getBounds(index, true, false,
false, false, true, hDC);
if (measureEvent !is null) {
textRect.right = Math.min(cellRect.right,
measureEvent.x + measureEvent.width);
}
fillBackground(hDC, OS.GetBkColor(hDC), textRect);
}
}
}
else {
if (selected || hot) {
selectionForeground = clrText = newTextClr;
ignoreDrawSelection = ignoreDrawHot = true;
}
if (explorerTheme) {
nmcd.nmcd.uItemState |= OS.CDIS_DISABLED;
/*
* Feature in Windows. On Vista only, when the text
* color is unchanged and an item is asked to draw
* disabled, it uses the disabled color. The fix is
* to modify the color so that is it no longer equal.
*/
int newColor = clrText is -1 ? getForegroundPixel() : clrText;
if (nmcd.clrText is newColor) {
nmcd.clrText |= 0x20000000;
if (nmcd.clrText is newColor)
nmcd.clrText &= ~0x20000000;
}
else {
nmcd.clrText = newColor;
}
OS.MoveMemory(lParam, nmcd, NMTVCUSTOMDRAW.sizeof);
}
}
if (focused && !ignoreDrawFocus && (style & SWT.FULL_SELECTION) is 0) {
RECT* textRect = item.getBounds(index, true, explorerTheme,
false, false, true, hDC);
if (measureEvent !is null) {
textRect.right = Math.min(cellRect.right,
measureEvent.x + measureEvent.width);
}
nmcd.nmcd.uItemState &= ~OS.CDIS_FOCUS;
OS.MoveMemory(lParam, nmcd, NMTVCUSTOMDRAW.sizeof);
focusRect = textRect;
}
if (explorerTheme) {
if (selected || (hot && ignoreDrawHot))
nmcd.nmcd.uItemState &= ~OS.CDIS_HOT;
OS.MoveMemory(lParam, nmcd, NMTVCUSTOMDRAW.sizeof);
}
RECT* itemRect = item.getBounds(index, true, true, false, false, false, hDC);
OS.SaveDC(hDC);
OS.SelectClipRgn(hDC, null);
if (explorerTheme) {
itemRect.left -= EXPLORER_EXTRA;
itemRect.right += EXPLORER_EXTRA;
}
//TODO - bug in Windows selection or SWT itemRect
/*if (selected)*/
itemRect.right++;
if (linesVisible)
itemRect.bottom++;
if (clipRect !is null) {
OS.IntersectClipRect(hDC, clipRect.left, clipRect.top,
clipRect.right, clipRect.bottom);
}
OS.ExcludeClipRect(hDC, itemRect.left, itemRect.top,
itemRect.right, itemRect.bottom);
return new LRESULT(OS.CDRF_DODEFAULT | OS.CDRF_NOTIFYPOSTPAINT);
}
/*
* Feature in Windows. When the tree has the style
* TVS_FULLROWSELECT, the background color for the
* entire row is filled when an item is painted,
* drawing on top of any custom drawing. The fix
* is to emulate TVS_FULLROWSELECT.
*/
if ((style & SWT.FULL_SELECTION) !is 0) {
int bits = OS.GetWindowLong(handle, OS.GWL_STYLE);
if ((bits & OS.TVS_FULLROWSELECT) is 0) {
RECT rect;
OS.SetRect(&rect, nmcd.nmcd.rc.left, nmcd.nmcd.rc.top,
nmcd.nmcd.rc.right, nmcd.nmcd.rc.bottom);
if (selected) {
fillBackground(hDC, OS.GetBkColor(hDC), &rect);
}
else {
if (OS.IsWindowEnabled(handle))
drawBackground(hDC, &rect);
}
nmcd.nmcd.uItemState &= ~OS.CDIS_FOCUS;
OS.MoveMemory(lParam, nmcd, NMTVCUSTOMDRAW.sizeof);
}
}
}
LRESULT result = null;
if (clrText is -1 && clrTextBk is -1 && hFont is cast(HFONT)-1) {
result = new LRESULT(OS.CDRF_DODEFAULT | OS.CDRF_NOTIFYPOSTPAINT);
}
else {
result = new LRESULT(OS.CDRF_NEWFONT | OS.CDRF_NOTIFYPOSTPAINT);
if (hFont !is cast(HFONT)-1)
OS.SelectObject(hDC, hFont);
if (OS.IsWindowEnabled(handle) && OS.IsWindowVisible(handle)) {
/*
* Feature in Windows. Windows does not fill the entire cell
* with the background color when TVS_FULLROWSELECT is not set.
* The fix is to fill the cell with the background color.
*/
if (clrTextBk !is -1) {
int bits = OS.GetWindowLong(handle, OS.GWL_STYLE);
if ((bits & OS.TVS_FULLROWSELECT) is 0) {
if (columnCount !is 0 && hwndHeader !is null) {
RECT rect;
HDITEM hdItem;
hdItem.mask = OS.HDI_WIDTH;
OS.SendMessage(hwndHeader, OS.HDM_GETITEM, index, &hdItem);
OS.SetRect(&rect, nmcd.nmcd.rc.left,
nmcd.nmcd.rc.top, nmcd.nmcd.rc.left + hdItem.cxy,
nmcd.nmcd.rc.bottom);
if (OS.COMCTL32_MAJOR < 6 || !OS.IsAppThemed()) {
RECT itemRect;
if (OS.TreeView_GetItemRect(handle,
cast(HTREEITEM) item.handle, &itemRect, true)) {
rect.left = Math.min(itemRect.left, rect.right);
}
}
if ((style & SWT.FULL_SELECTION) !is 0) {
if (!selected)
fillBackground(hDC, clrTextBk, &rect);
}
else {
if (explorerTheme) {
if (!selected && !hot)
fillBackground(hDC, clrTextBk, &rect);
}
else {
fillBackground(hDC, clrTextBk, &rect);
}
}
}
else {
if ((style & SWT.FULL_SELECTION) !is 0) {
RECT rect;
OS.SetRect(&rect, nmcd.nmcd.rc.left,
nmcd.nmcd.rc.top, nmcd.nmcd.rc.right, nmcd.nmcd.rc.bottom);
if (!selected)
fillBackground(hDC, clrTextBk, &rect);
}
}
}
}
if (!selected) {
nmcd.clrText = clrText is -1 ? getForegroundPixel() : clrText;
nmcd.clrTextBk = clrTextBk is -1 ? getBackgroundPixel() : clrTextBk;
OS.MoveMemory(lParam, nmcd, NMTVCUSTOMDRAW.sizeof);
}
}
}
if (OS.IsWindowEnabled(handle)) {
/*
* On Vista only, when an item is asked to draw disabled,
* the background of the text is not filled with the
* background color of the tree. This is true for both
* regular and full selection trees. In order to draw a
* background image, mark the item as disabled using
* CDIS_DISABLED (when not selected) and set the text
* to the regular text color to avoid drawing disabled.
*/
if (explorerTheme) {
if (findImageControl() !is null) {
if (!selected && (nmcd.nmcd.uItemState & (OS.CDIS_HOT | OS.CDIS_SELECTED)) is 0) {
nmcd.nmcd.uItemState |= OS.CDIS_DISABLED;
/*
* Feature in Windows. On Vista only, when the text
* color is unchanged and an item is asked to draw
* disabled, it uses the disabled color. The fix is
* to modify the color so it is no longer equal.
*/
int newColor = clrText is -1 ? getForegroundPixel() : clrText;
if (nmcd.clrText is newColor) {
nmcd.clrText |= 0x20000000;
if (nmcd.clrText is newColor)
nmcd.clrText &= ~0x20000000;
}
else {
nmcd.clrText = newColor;
}
OS.MoveMemory(lParam, nmcd, NMTVCUSTOMDRAW.sizeof);
if (clrTextBk !is -1) {
if ((style & SWT.FULL_SELECTION) !is 0) {
RECT rect;
if (columnCount !is 0) {
HDITEM hdItem;
hdItem.mask = OS.HDI_WIDTH;
OS.SendMessage(hwndHeader, OS.HDM_GETITEM, index, &hdItem);
OS.SetRect(&rect, nmcd.nmcd.rc.left,
nmcd.nmcd.rc.top, nmcd.nmcd.rc.left + hdItem.cxy,
nmcd.nmcd.rc.bottom);
}
else {
OS.SetRect(&rect, nmcd.nmcd.rc.left,
nmcd.nmcd.rc.top, nmcd.nmcd.rc.right,
nmcd.nmcd.rc.bottom);
}
fillBackground(hDC, clrTextBk, &rect);
}
else {
RECT* textRect = item.getBounds(index, true,
false, true, false, true, hDC);
fillBackground(hDC, clrTextBk, textRect);
}
}
}
}
}
}
else {
/*
* Feature in Windows. When the tree is disabled, it draws
* with a gray background over the sort column. The fix is
* to fill the background with the sort column color.
*/
if (clrSortBk !is -1) {
RECT rect;
HDITEM hdItem;
hdItem.mask = OS.HDI_WIDTH;
OS.SendMessage(hwndHeader, OS.HDM_GETITEM, index, &hdItem);
OS.SetRect(&rect, nmcd.nmcd.rc.left, nmcd.nmcd.rc.top,
nmcd.nmcd.rc.left + hdItem.cxy, nmcd.nmcd.rc.bottom);
fillBackground(hDC, clrSortBk, &rect);
}
}
OS.SaveDC(hDC);
if (clipRect !is null) {
auto hRgn = OS.CreateRectRgn(clipRect.left, clipRect.top,
clipRect.right, clipRect.bottom);
POINT lpPoint;
OS.GetWindowOrgEx(hDC, &lpPoint);
OS.OffsetRgn(hRgn, -lpPoint.x, -lpPoint.y);
OS.SelectClipRgn(hDC, hRgn);
OS.DeleteObject(hRgn);
}
return result;
}
LRESULT CDDS_POSTPAINT(NMTVCUSTOMDRAW* nmcd, WPARAM wParam, LPARAM lParam) {
if (ignoreCustomDraw)
return null;
if (OS.IsWindowVisible(handle)) {
if (OS.COMCTL32_MAJOR >= 6 && OS.IsAppThemed()) {
if (sortColumn !is null && sortDirection !is SWT.NONE) {
if (findImageControl() is null) {
int index = indexOf(sortColumn);
if (index !is -1) {
int top = nmcd.nmcd.rc.top;
/*
* Bug in Windows. For some reason, during a collapse,
* when TVM_GETNEXTITEM is sent with TVGN_LASTVISIBLE
* and the collapse causes the item being collapsed
* to become the last visible item in the tree, the
* message takes a long time to process. In order for
* the slowness to happen, the children of the item
* must have children. Times of up to 11 seconds have
* been observed with 23 children, each having one
* child. The fix is to use the bottom partially
* visible item rather than the last possible item
* that could be visible.
*
* NOTE: This problem only happens on Vista during
* WM_NOTIFY with NM_CUSTOMDRAW and CDDS_POSTPAINT.
*/
HANDLE hItem;
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0)) {
hItem = getBottomItem();
}
else {
hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_LASTVISIBLE, 0);
}
if (hItem !is null) {
RECT rect;
if (OS.TreeView_GetItemRect(handle,
cast(HTREEITEM) hItem, &rect, false)) {
top = rect.bottom;
}
}
RECT rect;
OS.SetRect(&rect, nmcd.nmcd.rc.left, top,
nmcd.nmcd.rc.right, nmcd.nmcd.rc.bottom);
RECT headerRect;
OS.SendMessage(hwndHeader, OS.HDM_GETITEMRECT, index, &headerRect);
rect.left = headerRect.left;
rect.right = headerRect.right;
fillBackground(nmcd.nmcd.hdc, getSortColumnPixel(), &rect);
}
}
}
}
if (linesVisible) {
auto hDC = nmcd.nmcd.hdc;
if (hwndHeader !is null) {
int x = 0;
RECT rect;
HDITEM hdItem;
hdItem.mask = OS.HDI_WIDTH;
for (int i = 0; i < columnCount; i++) {
auto index = OS.SendMessage(hwndHeader, OS.HDM_ORDERTOINDEX, i, 0);
OS.SendMessage(hwndHeader, OS.HDM_GETITEM, index, &hdItem);
OS.SetRect(&rect, x, nmcd.nmcd.rc.top, x + hdItem.cxy, nmcd.nmcd.rc.bottom);
OS.DrawEdge(hDC, &rect, OS.BDR_SUNKENINNER, OS.BF_RIGHT);
x += hdItem.cxy;
}
}
int height = 0;
RECT rect;
/*
* Bug in Windows. For some reason, during a collapse,
* when TVM_GETNEXTITEM is sent with TVGN_LASTVISIBLE
* and the collapse causes the item being collapsed
* to become the last visible item in the tree, the
* message takes a long time to process. In order for
* the slowness to happen, the children of the item
* must have children. Times of up to 11 seconds have
* been observed with 23 children, each having one
* child. The fix is to use the bottom partially
* visible item rather than the last possible item
* that could be visible.
*
* NOTE: This problem only happens on Vista during
* WM_NOTIFY with NM_CUSTOMDRAW and CDDS_POSTPAINT.
*/
HANDLE hItem;
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0)) {
hItem = getBottomItem();
}
else {
hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_LASTVISIBLE, 0);
}
if (hItem !is null) {
if (OS.TreeView_GetItemRect(handle, cast(HTREEITEM) hItem, &rect, false)) {
height = rect.bottom - rect.top;
}
}
if (height is 0) {
height = cast(int) /*64bit*/ OS.SendMessage(handle, OS.TVM_GETITEMHEIGHT, 0, 0);
OS.GetClientRect(handle, &rect);
OS.SetRect(&rect, rect.left, rect.top, rect.right, rect.top + height);
OS.DrawEdge(hDC, &rect, OS.BDR_SUNKENINNER, OS.BF_BOTTOM);
}
while (rect.bottom < nmcd.nmcd.rc.bottom) {
int top = rect.top + height;
OS.SetRect(&rect, rect.left, top, rect.right, top + height);
OS.DrawEdge(hDC, &rect, OS.BDR_SUNKENINNER, OS.BF_BOTTOM);
}
}
}
return new LRESULT(OS.CDRF_DODEFAULT);
}
LRESULT CDDS_PREPAINT(NMTVCUSTOMDRAW* nmcd, WPARAM wParam, LPARAM lParam) {
if (explorerTheme) {
if ((OS.IsWindowEnabled(handle) && hooks(SWT.EraseItem)) || findImageControl() !is null) {
RECT rect;
OS.SetRect(&rect, nmcd.nmcd.rc.left, nmcd.nmcd.rc.top,
nmcd.nmcd.rc.right, nmcd.nmcd.rc.bottom);
drawBackground(nmcd.nmcd.hdc, &rect);
}
}
return new LRESULT(OS.CDRF_NOTIFYITEMDRAW | OS.CDRF_NOTIFYPOSTPAINT);
}
override.LRESULT callWindowProc(HWND hwnd, int msg, WPARAM wParam, LPARAM lParam) {
if (handle is null)
return 0;
if (hwndParent !is null && hwnd is hwndParent) {
return OS.DefWindowProc(hwnd, msg, wParam, lParam);
}
if (hwndHeader !is null && hwnd is hwndHeader) {
return OS.CallWindowProc(HeaderProc, hwnd, msg, wParam, lParam);
}
switch (msg) {
case OS.WM_SETFOCUS: {
/*
* Feature in Windows. When a tree control processes WM_SETFOCUS,
* if no item is selected, the first item in the tree is selected.
* This is unexpected and might clear the previous selection.
* The fix is to detect that there is no selection and set it to
* the first visible item in the tree. If the item was not selected,
* only the focus is assigned.
*/
if ((style & SWT.SINGLE) !is 0)
break;
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
if (hItem is null) {
hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0);
if (hItem !is null) {
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE;
tvItem.hItem = cast(HTREEITEM) hItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
hSelect = hItem;
ignoreDeselect = ignoreSelect = lockSelection = true;
OS.SendMessage(handle, OS.TVM_SELECTITEM, OS.TVGN_CARET, hItem);
ignoreDeselect = ignoreSelect = lockSelection = false;
hSelect = null;
if ((tvItem.state & OS.TVIS_SELECTED) is 0) {
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
}
}
break;
}
default:
}
HANDLE hItem;
bool redraw = false;
switch (msg) {
/* Keyboard messages */
case OS.WM_KEYDOWN:
if (wParam is OS.VK_CONTROL || wParam is OS.VK_SHIFT)
break;
//FALL THROUGH
goto case;
case OS.WM_CHAR:
case OS.WM_IME_CHAR:
case OS.WM_KEYUP:
case OS.WM_SYSCHAR:
case OS.WM_SYSKEYDOWN:
case OS.WM_SYSKEYUP:
//FALL THROUGH
/* Scroll messages */
case OS.WM_HSCROLL:
case OS.WM_VSCROLL:
//FALL THROUGH
/* Resize messages */
case OS.WM_SIZE:
redraw = findImageControl() !is null && drawCount is 0 && OS.IsWindowVisible(handle);
if (redraw)
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 0, 0);
//FALL THROUGH
goto case;
/* Mouse messages */
case OS.WM_LBUTTONDBLCLK:
case OS.WM_LBUTTONDOWN:
case OS.WM_LBUTTONUP:
case OS.WM_MBUTTONDBLCLK:
case OS.WM_MBUTTONDOWN:
case OS.WM_MBUTTONUP:
case OS.WM_MOUSEHOVER:
case OS.WM_MOUSELEAVE:
case OS.WM_MOUSEMOVE:
case OS.WM_MOUSEWHEEL:
case OS.WM_RBUTTONDBLCLK:
case OS.WM_RBUTTONDOWN:
case OS.WM_RBUTTONUP:
case OS.WM_XBUTTONDBLCLK:
case OS.WM_XBUTTONDOWN:
case OS.WM_XBUTTONUP:
//FALL THROUGH
/* Other messages */
case OS.WM_SETFONT:
case OS.WM_TIMER: {
if (findImageControl() !is null) {
hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0);
}
break;
}
default:
}
auto code = OS.CallWindowProc(TreeProc, hwnd, msg, wParam, lParam);
switch (msg) {
/* Keyboard messages */
case OS.WM_KEYDOWN:
if (wParam is OS.VK_CONTROL || wParam is OS.VK_SHIFT)
break;
//FALL THROUGH
goto case;
case OS.WM_CHAR:
case OS.WM_IME_CHAR:
case OS.WM_KEYUP:
case OS.WM_SYSCHAR:
case OS.WM_SYSKEYDOWN:
case OS.WM_SYSKEYUP:
//FALL THROUGH
/* Scroll messages */
case OS.WM_HSCROLL:
case OS.WM_VSCROLL:
//FALL THROUGH
/* Resize messages */
case OS.WM_SIZE:
if (redraw) {
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 1, 0);
OS.InvalidateRect(handle, null, true);
if (hwndHeader !is null)
OS.InvalidateRect(hwndHeader, null, true);
}
//FALL THROUGH
goto case;
/* Mouse messages */
case OS.WM_LBUTTONDBLCLK:
case OS.WM_LBUTTONDOWN:
case OS.WM_LBUTTONUP:
case OS.WM_MBUTTONDBLCLK:
case OS.WM_MBUTTONDOWN:
case OS.WM_MBUTTONUP:
case OS.WM_MOUSEHOVER:
case OS.WM_MOUSELEAVE:
case OS.WM_MOUSEMOVE:
case OS.WM_MOUSEWHEEL:
case OS.WM_RBUTTONDBLCLK:
case OS.WM_RBUTTONDOWN:
case OS.WM_RBUTTONUP:
case OS.WM_XBUTTONDBLCLK:
case OS.WM_XBUTTONDOWN:
case OS.WM_XBUTTONUP:
//FALL THROUGH
/* Other messages */
case OS.WM_SETFONT:
case OS.WM_TIMER: {
if (findImageControl() !is null) {
if (hItem !is cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0)) {
OS.InvalidateRect(handle, null, true);
}
}
updateScrollBar();
break;
}
case OS.WM_PAINT:
painted = true;
break;
default:
}
return code;
}
override void checkBuffered() {
super.checkBuffered();
if ((style & SWT.VIRTUAL) !is 0) {
style |= SWT.DOUBLE_BUFFERED;
OS.SendMessage(handle, OS.TVM_SETSCROLLTIME, 0, 0);
}
if (EXPLORER_THEME) {
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0) && OS.IsAppThemed()) {
auto exStyle = OS.SendMessage(handle, OS.TVM_GETEXTENDEDSTYLE, 0, 0);
if ((exStyle & OS.TVS_EX_DOUBLEBUFFER) !is 0)
style |= SWT.DOUBLE_BUFFERED;
}
}
}
bool checkData(TreeItem item, bool redraw) {
if ((style & SWT.VIRTUAL) is 0)
return true;
if (!item.cached) {
TreeItem parentItem = item.getParentItem();
return checkData(item, parentItem is null ? indexOf(item)
: parentItem.indexOf(item), redraw);
}
return true;
}
bool checkData(TreeItem item, int index, bool redraw) {
if ((style & SWT.VIRTUAL) is 0)
return true;
if (!item.cached) {
item.cached = true;
Event event = new Event();
event.item = item;
event.index = index;
TreeItem oldItem = currentItem;
currentItem = item;
sendEvent(SWT.SetData, event);
//widget could be disposed at this point
currentItem = oldItem;
if (isDisposed() || item.isDisposed())
return false;
if (redraw)
item.redraw();
}
return true;
}
override bool checkHandle(HWND hwnd) {
return hwnd is handle || (hwndParent !is null && hwnd is hwndParent)
|| (hwndHeader !is null && hwnd is hwndHeader);
}
bool checkScroll(HANDLE hItem) {
/*
* Feature in Windows. If redraw is turned off using WM_SETREDRAW
* and a tree item that is not a child of the first root is selected or
* scrolled using TVM_SELECTITEM or TVM_ENSUREVISIBLE, then scrolling
* does not occur. The fix is to detect this case, and make sure
* that redraw is temporarily enabled. To avoid flashing, DefWindowProc()
* is called to disable redrawing.
*
* NOTE: The code that actually works around the problem is in the
* callers of this method.
*/
if (drawCount is 0)
return false;
auto hRoot = OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
auto hParent = OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_PARENT, hItem);
while (hParent !is hRoot && hParent !is 0) {
hParent = OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_PARENT, hParent);
}
return hParent is 0;
}
override protected void checkSubclass() {
if (!isValidSubclass())
error(SWT.ERROR_INVALID_SUBCLASS);
}
/**
* Clears the item at the given zero-relative index in the receiver.
* The text, icon and other attributes of the item are set to the default
* value. If the tree was created with the <code>SWT.VIRTUAL</code> style,
* these attributes are requested again as needed.
*
* @param index the index of the item to clear
* @param all <code>true</code> if all child items of the indexed item should be
* cleared recursively, and <code>false</code> otherwise
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_INVALID_RANGE - if the index is not between 0 and the number of elements in the list minus 1 (inclusive)</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see SWT#VIRTUAL
* @see SWT#SetData
*
* @since 3.2
*/
public void clear(int index, bool all) {
checkWidget();
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
if (hItem is null)
error(SWT.ERROR_INVALID_RANGE);
hItem = findItem(hItem, index);
if (hItem is null)
error(SWT.ERROR_INVALID_RANGE);
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM;
clear(hItem, &tvItem);
if (all) {
hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hItem);
clearAll(hItem, &tvItem, all);
}
}
void clear(HANDLE hItem, TVITEM* tvItem) {
tvItem.hItem = cast(HTREEITEM) hItem;
TreeItem item = null;
if (OS.SendMessage(handle, OS.TVM_GETITEM, 0, tvItem) !is 0) {
item = tvItem.lParam !is -1 ? items[tvItem.lParam] : null;
}
if (item !is null) {
if ((style & SWT.VIRTUAL) !is 0 && !item.cached)
return;
item.clear();
item.redraw();
}
}
/**
* Clears all the items in the receiver. The text, icon and other
* attributes of the items are set to their default values. If the
* tree was created with the <code>SWT.VIRTUAL</code> style, these
* attributes are requested again as needed.
*
* @param all <code>true</code> if all child items should be cleared
* recursively, and <code>false</code> otherwise
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see SWT#VIRTUAL
* @see SWT#SetData
*
* @since 3.2
*/
public void clearAll(bool all) {
checkWidget();
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
if (hItem is null)
return;
if (all) {
bool redraw = false;
for (int i = 0; i < items.length; i++) {
TreeItem item = items[i];
if (item !is null && item !is currentItem) {
item.clear();
redraw = true;
}
}
if (redraw)
OS.InvalidateRect(handle, null, true);
}
else {
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM;
clearAll(hItem, &tvItem, all);
}
}
void clearAll(HANDLE hItem, TVITEM* tvItem, bool all) {
while (hItem !is null) {
clear(hItem, tvItem);
if (all) {
auto hFirstItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hItem);
clearAll(hFirstItem, tvItem, all);
}
hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem);
}
}
private static extern (Windows) int CompareFunc(LPARAM lParam1, LPARAM lParam2,
LPARAM lParamSort) {
return sThis.CompareProc(lParam1, lParam2, lParamSort);
}
int CompareProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) {
TreeItem item1 = items[lParam1], item2 = items[lParam2];
String text1 = item1.getText(cast(int) /*64bit*/ lParamSort),
text2 = item2.getText(cast(int) /*64bit*/ lParamSort);
return sortDirection is SWT.UP ? (text1 < text2) : (text2 < text1);
}
override public Point computeSize(int wHint, int hHint, bool changed) {
checkWidget();
int width = 0, height = 0;
if (hwndHeader !is null) {
HDITEM hdItem;
hdItem.mask = OS.HDI_WIDTH;
for (int i = 0; i < columnCount; i++) {
OS.SendMessage(hwndHeader, OS.HDM_GETITEM, i, &hdItem);
width += hdItem.cxy;
}
RECT rect;
OS.GetWindowRect(hwndHeader, &rect);
height += rect.bottom - rect.top;
}
RECT rect;
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
while (hItem !is null) {
if ((style & SWT.VIRTUAL) is 0 && !painted) {
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_TEXT;
tvItem.hItem = cast(HTREEITEM) hItem;
tvItem.pszText = OS.LPSTR_TEXTCALLBACK;
ignoreCustomDraw = true;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
ignoreCustomDraw = false;
}
if (OS.TreeView_GetItemRect(handle, cast(HTREEITEM) hItem, &rect, true)) {
width = Math.max(width, rect.right);
height += rect.bottom - rect.top;
}
hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM,
OS.TVGN_NEXTVISIBLE, hItem);
}
if (width is 0)
width = DEFAULT_WIDTH;
if (height is 0)
height = DEFAULT_HEIGHT;
if (wHint !is SWT.DEFAULT)
width = wHint;
if (hHint !is SWT.DEFAULT)
height = hHint;
int border = getBorderWidth();
width += border * 2;
height += border * 2;
if ((style & SWT.V_SCROLL) !is 0) {
width += OS.GetSystemMetrics(OS.SM_CXVSCROLL);
}
if ((style & SWT.H_SCROLL) !is 0) {
height += OS.GetSystemMetrics(OS.SM_CYHSCROLL);
}
return new Point(width, height);
}
override void createHandle() {
super.createHandle();
state &= ~(CANVAS | THEME_BACKGROUND);
/* Use the Explorer theme */
if (EXPLORER_THEME) {
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0) && OS.IsAppThemed()) {
explorerTheme = true;
OS.SetWindowTheme(handle, cast(TCHAR*) Display.EXPLORER, null);
int bits = OS.TVS_EX_DOUBLEBUFFER | OS.TVS_EX_FADEINOUTEXPANDOS
| OS.TVS_EX_RICHTOOLTIP;
/*
* This code is intentionally commented.
*/
// if ((style & SWT.FULL_SELECTION) is 0) bits |= OS.TVS_EX_AUTOHSCROLL;
OS.SendMessage(handle, OS.TVM_SETEXTENDEDSTYLE, 0, bits);
/*
* Bug in Windows. When the tree is using the explorer
* theme, it does not use COLOR_WINDOW_TEXT for the
* default foreground color. The fix is to explicitly
* set the foreground.
*/
setForegroundPixel(-1);
}
}
/*
* Feature in Windows. In version 5.8 of COMCTL32.DLL,
* if the font is changed for an item, the bounds for the
* item are not updated, causing the text to be clipped.
* The fix is to detect the version of COMCTL32.DLL, and
* if it is one of the versions with the problem, then
* use version 5.00 of the control (a version that does
* not have the problem). This is the recommended work
* around from the MSDN.
*/
static if (!OS.IsWinCE) {
if (OS.COMCTL32_MAJOR < 6) {
OS.SendMessage(handle, OS.CCM_SETVERSION, 5, 0);
}
}
/* Set the checkbox image list */
if ((style & SWT.CHECK) !is 0)
setCheckboxImageList();
/*
* Feature in Windows. When the control is created,
* it does not use the default system font. A new HFONT
* is created and destroyed when the control is destroyed.
* This means that a program that queries the font from
* this control, uses the font in another control and then
* destroys this control will have the font unexpectedly
* destroyed in the other control. The fix is to assign
* the font ourselves each time the control is created.
* The control will not destroy a font that it did not
* create.
*/
HFONT hFont = OS.GetStockObject(OS.SYSTEM_FONT);
OS.SendMessage(handle, OS.WM_SETFONT, hFont, 0);
}
void createHeaderToolTips() {
static if (OS.IsWinCE)
return;
if (headerToolTipHandle !is null)
return;
int bits = 0;
if (OS.WIN32_VERSION >= OS.VERSION(4, 10)) {
if ((style & SWT.RIGHT_TO_LEFT) !is 0)
bits |= OS.WS_EX_LAYOUTRTL;
}
headerToolTipHandle = OS.CreateWindowEx(bits, OS.TOOLTIPS_CLASS.dup.ptr,
null, OS.TTS_NOPREFIX, OS.CW_USEDEFAULT, 0, OS.CW_USEDEFAULT,
0, handle, null, OS.GetModuleHandle(null), null);
if (headerToolTipHandle is null)
error(SWT.ERROR_NO_HANDLES);
/*
* Feature in Windows. Despite the fact that the
* tool tip text contains \r\n, the tooltip will
* not honour the new line unless TTM_SETMAXTIPWIDTH
* is set. The fix is to set TTM_SETMAXTIPWIDTH to
* a large value.
*/
OS.SendMessage(headerToolTipHandle, OS.TTM_SETMAXTIPWIDTH, 0, 0x7FFF);
}
void createItem(TreeColumn column, int index) {
if (hwndHeader is null)
createParent();
if (!(0 <= index && index <= columnCount))
error(SWT.ERROR_INVALID_RANGE);
if (columnCount is columns.length) {
TreeColumn[] newColumns = new TreeColumn[columns.length + 4];
System.arraycopy(columns, 0, newColumns, 0, columns.length);
columns = newColumns;
}
for (int i = 0; i < items.length; i++) {
TreeItem item = items[i];
if (item !is null) {
String[] strings = item.strings;
if (strings !is null) {
String[] temp = new String[columnCount + 1];
System.arraycopy(strings, 0, temp, 0, index);
System.arraycopy(strings, index, temp, index + 1, columnCount - index);
item.strings = temp;
}
Image[] images = item.images;
if (images !is null) {
Image[] temp = new Image[columnCount + 1];
System.arraycopy(images, 0, temp, 0, index);
System.arraycopy(images, index, temp, index + 1, columnCount - index);
item.images = temp;
}
if (index is 0) {
if (columnCount !is 0) {
if (strings is null) {
item.strings = new String[columnCount + 1];
item.strings[1] = item.text;
}
item.text = "";
if (images is null) {
item.images = new Image[columnCount + 1];
item.images[1] = item.image;
}
item.image = null;
}
}
if (item.cellBackground !is null) {
int[] cellBackground = item.cellBackground;
int[] temp = new int[columnCount + 1];
System.arraycopy(cellBackground, 0, temp, 0, index);
System.arraycopy(cellBackground, index, temp, index + 1, columnCount - index);
temp[index] = -1;
item.cellBackground = temp;
}
if (item.cellForeground !is null) {
int[] cellForeground = item.cellForeground;
int[] temp = new int[columnCount + 1];
System.arraycopy(cellForeground, 0, temp, 0, index);
System.arraycopy(cellForeground, index, temp, index + 1, columnCount - index);
temp[index] = -1;
item.cellForeground = temp;
}
if (item.cellFont !is null) {
Font[] cellFont = item.cellFont;
Font[] temp = new Font[columnCount + 1];
System.arraycopy(cellFont, 0, temp, 0, index);
System.arraycopy(cellFont, index, temp, index + 1, columnCount - index);
item.cellFont = temp;
}
}
}
System.arraycopy(columns, index, columns, index + 1, columnCount++ - index);
columns[index] = column;
/*
* Bug in Windows. For some reason, when HDM_INSERTITEM
* is used to insert an item into a header without text,
* if is not possible to set the text at a later time.
* The fix is to insert the item with an empty string.
*/
auto hHeap = OS.GetProcessHeap();
auto pszText = cast(TCHAR*) OS.HeapAlloc(hHeap, OS.HEAP_ZERO_MEMORY, TCHAR.sizeof);
HDITEM hdItem;
hdItem.mask = OS.HDI_TEXT | OS.HDI_FORMAT;
hdItem.pszText = pszText;
if ((column.style & SWT.LEFT) is SWT.LEFT)
hdItem.fmt = OS.HDF_LEFT;
if ((column.style & SWT.CENTER) is SWT.CENTER)
hdItem.fmt = OS.HDF_CENTER;
if ((column.style & SWT.RIGHT) is SWT.RIGHT)
hdItem.fmt = OS.HDF_RIGHT;
OS.SendMessage(hwndHeader, OS.HDM_INSERTITEM, index, &hdItem);
if (pszText !is null)
OS.HeapFree(hHeap, 0, pszText);
/* When the first column is created, hide the horizontal scroll bar */
if (columnCount is 1) {
scrollWidth = 0;
if ((style & SWT.H_SCROLL) !is 0) {
int bits = OS.GetWindowLong(handle, OS.GWL_STYLE);
bits |= OS.TVS_NOHSCROLL;
OS.SetWindowLong(handle, OS.GWL_STYLE, bits);
}
/*
* Bug in Windows. When TVS_NOHSCROLL is set after items
* have been inserted into the tree, Windows shows the
* scroll bar. The fix is to check for this case and
* explicitly hide the scroll bar explicitly.
*/
auto count = OS.SendMessage(handle, OS.TVM_GETCOUNT, 0, 0);
if (count !is 0) {
static if (!OS.IsWinCE)
OS.ShowScrollBar(handle, OS.SB_HORZ, false);
}
createItemToolTips();
if (itemToolTipHandle !is null) {
OS.SendMessage(itemToolTipHandle, OS.TTM_SETDELAYTIME, OS.TTDT_AUTOMATIC, -1);
}
}
setScrollWidth();
updateImageList();
updateScrollBar();
/* Redraw to hide the items when the first column is created */
if (columnCount is 1 && OS.SendMessage(handle, OS.TVM_GETCOUNT, 0, 0) !is 0) {
OS.InvalidateRect(handle, null, true);
}
/* Add the tool tip item for the header */
if (headerToolTipHandle !is null) {
RECT rect;
if (OS.SendMessage(hwndHeader, OS.HDM_GETITEMRECT, index, &rect) !is 0) {
TOOLINFO lpti;
lpti.cbSize = OS.TOOLINFO_sizeof;
lpti.uFlags = OS.TTF_SUBCLASS;
lpti.hwnd = hwndHeader;
lpti.uId = column.id = display.nextToolTipId++;
lpti.rect.left = rect.left;
lpti.rect.top = rect.top;
lpti.rect.right = rect.right;
lpti.rect.bottom = rect.bottom;
lpti.lpszText = OS.LPSTR_TEXTCALLBACK;
OS.SendMessage(headerToolTipHandle, OS.TTM_ADDTOOL, 0, &lpti);
}
}
}
void createItem(TreeItem item, HANDLE hParent, HANDLE hInsertAfter, HANDLE hItem) {
int id = -1;
if (item !is null) {
id = lastID < items.length ? lastID : 0;
while (id < items.length && items[id]!is null)
id++;
if (id is items.length) {
/*
* Grow the array faster when redraw is off or the
* table is not visible. When the table is painted,
* the items array is resized to be smaller to reduce
* memory usage.
*/
size_t length = 0;
if (drawCount is 0 && OS.IsWindowVisible(handle)) {
length = items.length + 4;
}
else {
shrink = true;
length = Math.max(4, items.length * 3 / 2);
}
TreeItem[] newItems = new TreeItem[length];
System.arraycopy(items, 0, newItems, 0, items.length);
items = newItems;
}
lastID = id + 1;
}
HANDLE hNewItem;
HANDLE hFirstItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hParent);
bool fixParent = hFirstItem is null;
if (hItem is null) {
TVINSERTSTRUCT tvInsert;
tvInsert.hParent = cast(HTREEITEM) hParent;
tvInsert.hInsertAfter = cast(HTREEITEM) hInsertAfter;
tvInsert.item.lParam = id;
tvInsert.item.pszText = OS.LPSTR_TEXTCALLBACK;
tvInsert.item.iImage = tvInsert.item.iSelectedImage = cast(HBITMAP) OS.I_IMAGECALLBACK;
tvInsert.item.mask = OS.TVIF_TEXT | OS.TVIF_IMAGE
| OS.TVIF_SELECTEDIMAGE | OS.TVIF_HANDLE | OS.TVIF_PARAM;
if ((style & SWT.CHECK) !is 0) {
tvInsert.item.mask = tvInsert.item.mask | OS.TVIF_STATE;
tvInsert.item.state = 1 << 12;
tvInsert.item.stateMask = OS.TVIS_STATEIMAGEMASK;
}
ignoreCustomDraw = true;
hNewItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_INSERTITEM, 0, &tvInsert);
ignoreCustomDraw = false;
if (hNewItem is null)
error(SWT.ERROR_ITEM_NOT_ADDED);
/*
* This code is intentionally commented.
*/
// if (hParent !is 0) {
// int bits = OS.GetWindowLong (handle, OS.GWL_STYLE);
// bits |= OS.TVS_LINESATROOT;
// OS.SetWindowLong (handle, OS.GWL_STYLE, bits);
// }
}
else {
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM;
tvItem.hItem = cast(HTREEITEM)(hNewItem = hItem);
tvItem.lParam = id;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
if (item !is null) {
item.handle = hNewItem;
items[id] = item;
}
if (hFirstItem is null) {
if (cast(ptrdiff_t) hInsertAfter is OS.TVI_FIRST
|| cast(ptrdiff_t) hInsertAfter is OS.TVI_LAST) {
hFirstIndexOf = hLastIndexOf = hFirstItem = hNewItem;
itemCount = lastIndexOf = 0;
}
}
if (hFirstItem is hFirstIndexOf && itemCount !is -1)
itemCount++;
if (hItem is null) {
/*
* Bug in Windows. When a child item is added to a parent item
* that has no children outside of WM_NOTIFY with control code
* TVN_ITEMEXPANDED, the tree widget does not redraw the + / -
* indicator. The fix is to detect the case when the first
* child is added to a visible parent item and redraw the parent.
*/
if (fixParent) {
if (drawCount is 0 && OS.IsWindowVisible(handle)) {
RECT rect;
if (OS.TreeView_GetItemRect(handle, cast(HTREEITEM) hParent, &rect, false)) {
OS.InvalidateRect(handle, &rect, true);
}
}
}
/*
* Bug in Windows. When a new item is added while Windows
* is requesting data a tree item using TVN_GETDISPINFO,
* outstanding damage for items that are below the new item
* is not scrolled. The fix is to explicitly damage the
* new area.
*/
if ((style & SWT.VIRTUAL) !is 0) {
if (currentItem !is null) {
RECT rect;
if (OS.TreeView_GetItemRect(handle, cast(HTREEITEM) hNewItem, &rect, false)) {
RECT damageRect;
bool damaged = cast(bool) OS.GetUpdateRect(handle, &damageRect, true);
if (damaged && damageRect.top < rect.bottom) {
static if (OS.IsWinCE) {
OS.OffsetRect(&damageRect, 0, rect.bottom - rect.top);
OS.InvalidateRect(handle, &damageRect, true);
}
else {
HRGN rgn = OS.CreateRectRgn(0, 0, 0, 0);
int result = OS.GetUpdateRgn(handle, rgn, true);
if (result !is OS.NULLREGION) {
OS.OffsetRgn(rgn, 0, rect.bottom - rect.top);
OS.InvalidateRgn(handle, rgn, true);
}
OS.DeleteObject(rgn);
}
}
}
}
}
updateScrollBar();
}
}
void createItemToolTips() {
static if (OS.IsWinCE)
return;
if (itemToolTipHandle !is null)
return;
int bits1 = OS.GetWindowLong(handle, OS.GWL_STYLE);
bits1 |= OS.TVS_NOTOOLTIPS;
OS.SetWindowLong(handle, OS.GWL_STYLE, bits1);
int bits2 = 0;
if (OS.WIN32_VERSION >= OS.VERSION(4, 10)) {
if ((style & SWT.RIGHT_TO_LEFT) !is 0)
bits2 |= OS.WS_EX_LAYOUTRTL;
}
/*
* Feature in Windows. For some reason, when the user
* clicks on a tool tip, it temporarily takes focus, even
* when WS_EX_NOACTIVATE is specified. The fix is to
* use WS_EX_TRANSPARENT, even though WS_EX_TRANSPARENT
* is documented to affect painting, not hit testing.
*
* NOTE: Windows 2000 doesn't have the problem and
* setting WS_EX_TRANSPARENT causes pixel corruption.
*/
if (OS.COMCTL32_MAJOR >= 6)
bits2 |= OS.WS_EX_TRANSPARENT;
itemToolTipHandle = OS.CreateWindowEx(bits2, OS.TOOLTIPS_CLASS.dup.ptr, null,
OS.TTS_NOPREFIX | OS.TTS_NOANIMATE | OS.TTS_NOFADE, OS.CW_USEDEFAULT,
0, OS.CW_USEDEFAULT, 0, handle, null, OS.GetModuleHandle(null), null);
if (itemToolTipHandle is null)
error(SWT.ERROR_NO_HANDLES);
OS.SendMessage(itemToolTipHandle, OS.TTM_SETDELAYTIME, OS.TTDT_INITIAL, 0);
TOOLINFO lpti;
lpti.cbSize = OS.TOOLINFO_sizeof;
lpti.hwnd = handle;
lpti.uId = cast(ptrdiff_t) handle;
lpti.uFlags = OS.TTF_SUBCLASS | OS.TTF_TRANSPARENT;
lpti.lpszText = OS.LPSTR_TEXTCALLBACK;
OS.SendMessage(itemToolTipHandle, OS.TTM_ADDTOOL, 0, &lpti);
}
void createParent() {
forceResize();
RECT rect;
OS.GetWindowRect(handle, &rect);
OS.MapWindowPoints(null, parent.handle, cast(POINT*)&rect, 2);
int oldStyle = OS.GetWindowLong(handle, OS.GWL_STYLE);
int newStyle = super.widgetStyle() & ~OS.WS_VISIBLE;
if ((oldStyle & OS.WS_DISABLED) !is 0)
newStyle |= OS.WS_DISABLED;
// if ((oldStyle & OS.WS_VISIBLE) !is 0) newStyle |= OS.WS_VISIBLE;
hwndParent = OS.CreateWindowEx(super.widgetExtStyle(), StrToTCHARz(0,
super.windowClass()), null, newStyle, rect.left, rect.top,
rect.right - rect.left, rect.bottom - rect.top, parent.handle,
null, OS.GetModuleHandle(null), null);
if (hwndParent is null)
error(SWT.ERROR_NO_HANDLES);
OS.SetWindowLongPtr(hwndParent, OS.GWLP_ID, cast(LONG_PTR) hwndParent);
int bits = 0;
if (OS.WIN32_VERSION >= OS.VERSION(4, 10)) {
bits |= OS.WS_EX_NOINHERITLAYOUT;
if ((style & SWT.RIGHT_TO_LEFT) !is 0)
bits |= OS.WS_EX_LAYOUTRTL;
}
hwndHeader = OS.CreateWindowEx(bits, HeaderClass.ptr, null,
OS.HDS_BUTTONS | OS.HDS_FULLDRAG | OS.HDS_DRAGDROP | OS.HDS_HIDDEN | OS.WS_CHILD | OS.WS_CLIPSIBLINGS,
0, 0, 0, 0, hwndParent, null, OS.GetModuleHandle(null), null);
if (hwndHeader is null)
error(SWT.ERROR_NO_HANDLES);
OS.SetWindowLongPtr(hwndHeader, OS.GWLP_ID, cast(LONG_PTR) hwndHeader);
if (OS.IsDBLocale) {
auto hIMC = OS.ImmGetContext(handle);
OS.ImmAssociateContext(hwndParent, hIMC);
OS.ImmAssociateContext(hwndHeader, hIMC);
OS.ImmReleaseContext(handle, hIMC);
}
//This code is intentionally commented
// if (!OS.IsPPC) {
// if ((style & SWT.BORDER) !is 0) {
// int oldExStyle = OS.GetWindowLong (handle, OS.GWL_EXSTYLE);
// oldExStyle &= ~OS.WS_EX_CLIENTEDGE;
// OS.SetWindowLong (handle, OS.GWL_EXSTYLE, oldExStyle);
// }
// }
HFONT hFont = cast(HFONT) OS.SendMessage(handle, OS.WM_GETFONT, 0, 0);
if (hFont !is null)
OS.SendMessage(hwndHeader, OS.WM_SETFONT, hFont, 0);
HANDLE hwndInsertAfter = OS.GetWindow(handle, OS.GW_HWNDPREV);
int flags = OS.SWP_NOSIZE | OS.SWP_NOMOVE | OS.SWP_NOACTIVATE;
SetWindowPos(hwndParent, hwndInsertAfter, 0, 0, 0, 0, flags);
SCROLLINFO info;
info.cbSize = SCROLLINFO.sizeof;
info.fMask = OS.SIF_RANGE | OS.SIF_PAGE;
OS.GetScrollInfo(hwndParent, OS.SB_HORZ, &info);
info.nPage = info.nMax + 1;
OS.SetScrollInfo(hwndParent, OS.SB_HORZ, &info, true);
OS.GetScrollInfo(hwndParent, OS.SB_VERT, &info);
info.nPage = info.nMax + 1;
OS.SetScrollInfo(hwndParent, OS.SB_VERT, &info, true);
customDraw = true;
deregister();
if ((oldStyle & OS.WS_VISIBLE) !is 0) {
OS.ShowWindow(hwndParent, OS.SW_SHOW);
}
HWND hwndFocus = OS.GetFocus();
if (hwndFocus is handle)
OS.SetFocus(hwndParent);
OS.SetParent(handle, hwndParent);
if (hwndFocus is handle)
OS.SetFocus(handle);
register();
subclass();
}
override void createWidget() {
super.createWidget();
items = new TreeItem[4];
columns = new TreeColumn[4];
itemCount = -1;
}
override int defaultBackground() {
return OS.GetSysColor(OS.COLOR_WINDOW);
}
override void deregister() {
super.deregister();
if (hwndParent !is null)
display.removeControl(hwndParent);
if (hwndHeader !is null)
display.removeControl(hwndHeader);
}
void deselect(HANDLE hItem, TVITEM* tvItem, HANDLE hIgnoreItem) {
while (hItem !is null) {
if (hItem !is hIgnoreItem) {
tvItem.hItem = cast(HTREEITEM) hItem;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, tvItem);
}
auto hFirstItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hItem);
deselect(hFirstItem, tvItem, hIgnoreItem);
hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem);
}
}
/**
* Deselects an item in the receiver. If the item was already
* deselected, it remains deselected.
*
* @param item the item to be deselected
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the item is null</li>
* <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.4
*/
public void deselect(TreeItem item) {
checkWidget();
if (item is null)
error(SWT.ERROR_NULL_ARGUMENT);
if (item.isDisposed())
error(SWT.ERROR_INVALID_ARGUMENT);
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE;
tvItem.stateMask = OS.TVIS_SELECTED;
tvItem.hItem = cast(HTREEITEM) item.handle;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
/**
* Deselects all selected items in the receiver.
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public void deselectAll() {
checkWidget();
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE;
tvItem.stateMask = OS.TVIS_SELECTED;
if ((style & SWT.SINGLE) !is 0) {
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
if (hItem !is null) {
tvItem.hItem = cast(HTREEITEM) hItem;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
}
else {
auto oldProc = OS.GetWindowLongPtr(handle, OS.GWLP_WNDPROC);
OS.SetWindowLongPtr(handle, OS.GWLP_WNDPROC, cast(LONG_PTR) TreeProc);
if ((style & SWT.VIRTUAL) !is 0) {
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
deselect(hItem, &tvItem, null);
}
else {
for (int i = 0; i < items.length; i++) {
TreeItem item = items[i];
if (item !is null) {
tvItem.hItem = cast(HTREEITEM) item.handle;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
}
}
OS.SetWindowLongPtr(handle, OS.GWLP_WNDPROC, oldProc);
}
}
void destroyItem(TreeColumn column) {
if (hwndHeader is null)
error(SWT.ERROR_ITEM_NOT_REMOVED);
int index = 0;
while (index < columnCount) {
if (columns[index] is column)
break;
index++;
}
int[] oldOrder = new int[columnCount];
OS.SendMessage(hwndHeader, OS.HDM_GETORDERARRAY, columnCount, oldOrder.ptr);
int orderIndex = 0;
while (orderIndex < columnCount) {
if (oldOrder[orderIndex] is index)
break;
orderIndex++;
}
RECT headerRect;
OS.SendMessage(hwndHeader, OS.HDM_GETITEMRECT, index, &headerRect);
if (OS.SendMessage(hwndHeader, OS.HDM_DELETEITEM, index, 0) is 0) {
error(SWT.ERROR_ITEM_NOT_REMOVED);
}
System.arraycopy(columns, index + 1, columns, index, --columnCount - index);
columns[columnCount] = null;
for (int i = 0; i < items.length; i++) {
TreeItem item = items[i];
if (item !is null) {
if (columnCount is 0) {
item.strings = null;
item.images = null;
item.cellBackground = null;
item.cellForeground = null;
item.cellFont = null;
}
else {
if (item.strings !is null) {
String[] strings = item.strings;
if (index is 0) {
item.text = strings[1]!is null ? strings[1] : "";
}
String[] temp = new String[columnCount];
System.arraycopy(strings, 0, temp, 0, index);
System.arraycopy(strings, index + 1, temp, index, columnCount - index);
item.strings = temp;
}
else {
if (index is 0)
item.text = "";
}
if (item.images !is null) {
Image[] images = item.images;
if (index is 0)
item.image = images[1];
Image[] temp = new Image[columnCount];
System.arraycopy(images, 0, temp, 0, index);
System.arraycopy(images, index + 1, temp, index, columnCount - index);
item.images = temp;
}
else {
if (index is 0)
item.image = null;
}
if (item.cellBackground !is null) {
int[] cellBackground = item.cellBackground;
int[] temp = new int[columnCount];
System.arraycopy(cellBackground, 0, temp, 0, index);
System.arraycopy(cellBackground, index + 1, temp,
index, columnCount - index);
item.cellBackground = temp;
}
if (item.cellForeground !is null) {
int[] cellForeground = item.cellForeground;
int[] temp = new int[columnCount];
System.arraycopy(cellForeground, 0, temp, 0, index);
System.arraycopy(cellForeground, index + 1, temp,
index, columnCount - index);
item.cellForeground = temp;
}
if (item.cellFont !is null) {
Font[] cellFont = item.cellFont;
Font[] temp = new Font[columnCount];
System.arraycopy(cellFont, 0, temp, 0, index);
System.arraycopy(cellFont, index + 1, temp, index, columnCount - index);
item.cellFont = temp;
}
}
}
}
/*
* When the last column is deleted, show the horizontal
* scroll bar. Otherwise, left align the first column
* and redraw the columns to the right.
*/
if (columnCount is 0) {
scrollWidth = 0;
if (!hooks(SWT.MeasureItem)) {
int bits = OS.GetWindowLong(handle, OS.GWL_STYLE);
if ((style & SWT.H_SCROLL) !is 0)
bits &= ~OS.TVS_NOHSCROLL;
OS.SetWindowLong(handle, OS.GWL_STYLE, bits);
OS.InvalidateRect(handle, null, true);
}
if (itemToolTipHandle !is null) {
OS.SendMessage(itemToolTipHandle, OS.TTM_SETDELAYTIME, OS.TTDT_INITIAL, 0);
}
}
else {
if (index is 0) {
columns[0].style &= ~(SWT.LEFT | SWT.RIGHT | SWT.CENTER);
columns[0].style |= SWT.LEFT;
HDITEM hdItem;
hdItem.mask = OS.HDI_FORMAT | OS.HDI_IMAGE;
OS.SendMessage(hwndHeader, OS.HDM_GETITEM, index, &hdItem);
hdItem.fmt &= ~OS.HDF_JUSTIFYMASK;
hdItem.fmt |= OS.HDF_LEFT;
OS.SendMessage(hwndHeader, OS.HDM_SETITEM, index, &hdItem);
}
RECT rect;
OS.GetClientRect(handle, &rect);
rect.left = headerRect.left;
OS.InvalidateRect(handle, &rect, true);
}
setScrollWidth();
updateImageList();
updateScrollBar();
if (columnCount !is 0) {
int[] newOrder = new int[columnCount];
OS.SendMessage(hwndHeader, OS.HDM_GETORDERARRAY, columnCount, newOrder.ptr);
TreeColumn[] newColumns = new TreeColumn[columnCount - orderIndex];
for (int i = orderIndex; i < newOrder.length; i++) {
newColumns[i - orderIndex] = columns[newOrder[i]];
newColumns[i - orderIndex].updateToolTip(newOrder[i]);
}
for (int i = 0; i < newColumns.length; i++) {
if (!newColumns[i].isDisposed()) {
newColumns[i].sendEvent(SWT.Move);
}
}
}
/* Remove the tool tip item for the header */
if (headerToolTipHandle !is null) {
TOOLINFO lpti;
lpti.cbSize = OS.TOOLINFO_sizeof;
lpti.uId = column.id;
lpti.hwnd = hwndHeader;
OS.SendMessage(headerToolTipHandle, OS.TTM_DELTOOL, 0, &lpti);
}
}
void destroyItem(TreeItem item, HANDLE hItem) {
hFirstIndexOf = hLastIndexOf = null;
itemCount = -1;
/*
* Feature in Windows. When an item is removed that is not
* visible in the tree because it belongs to a collapsed branch,
* Windows redraws the tree causing a flash for each item that
* is removed. The fix is to detect whether the item is visible,
* force the widget to be fully painted, turn off redraw, remove
* the item and validate the damage caused by the removing of
* the item.
*
* NOTE: This fix is not necessary when double buffering and
* can cause problems for virtual trees due to the call to
* UpdateWindow() that flushes outstanding WM_PAINT events,
* allowing application code to add or remove items during
* this remove operation.
*/
HANDLE hParent;
bool fixRedraw = false;
if ((style & SWT.DOUBLE_BUFFERED) is 0) {
if (drawCount is 0 && OS.IsWindowVisible(handle)) {
RECT rect;
fixRedraw = !OS.TreeView_GetItemRect(handle, cast(HTREEITEM) hItem, &rect, false);
}
}
if (fixRedraw) {
hParent = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM,
OS.TVGN_PARENT, hItem);
OS.UpdateWindow(handle);
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 0, 0);
/*
* This code is intentionally commented.
*/
// OS.SendMessage (handle, OS.WM_SETREDRAW, 0, 0);
}
if ((style & SWT.MULTI) !is 0) {
ignoreDeselect = ignoreSelect = lockSelection = true;
}
/*
* Feature in Windows. When an item is deleted and a tool tip
* is showing, Window requests the new text for the new item
* that is under the cursor right away. This means that when
* multiple items are deleted, the tool tip flashes, showing
* each new item in the tool tip as it is scrolled into view.
* The fix is to hide tool tips when any item is deleted.
*
* NOTE: This only happens on Vista.
*/
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0)) {
auto hwndToolTip = cast(HWND) OS.SendMessage(handle, OS.TVM_GETTOOLTIPS, 0, 0);
if (hwndToolTip !is null)
OS.SendMessage(hwndToolTip, OS.TTM_POP, 0, 0);
}
shrink = ignoreShrink = true;
OS.SendMessage(handle, OS.TVM_DELETEITEM, 0, hItem);
ignoreShrink = false;
if ((style & SWT.MULTI) !is 0) {
ignoreDeselect = ignoreSelect = lockSelection = false;
}
if (fixRedraw) {
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 1, 0);
OS.ValidateRect(handle, null);
/*
* If the item that was deleted was the last child of a tree item that
* is visible, redraw the parent item to force the + / - to be updated.
*/
if (OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hParent) is 0) {
RECT rect;
if (OS.TreeView_GetItemRect(handle, cast(HTREEITEM) hParent, &rect, false)) {
OS.InvalidateRect(handle, &rect, true);
}
}
}
auto count = OS.SendMessage(handle, OS.TVM_GETCOUNT, 0, 0);
if (count is 0) {
if (imageList !is null) {
OS.SendMessage(handle, OS.TVM_SETIMAGELIST, 0, 0);
display.releaseImageList(imageList);
}
imageList = null;
if (hwndParent is null && !linesVisible) {
if (!hooks(SWT.MeasureItem) && !hooks(SWT.EraseItem) && !hooks(SWT.PaintItem)) {
customDraw = false;
}
}
items = new TreeItem[4];
scrollWidth = 0;
setScrollWidth();
}
updateScrollBar();
}
override void destroyScrollBar(int type) {
super.destroyScrollBar(type);
int bits = OS.GetWindowLong(handle, OS.GWL_STYLE);
if ((style & (SWT.H_SCROLL | SWT.V_SCROLL)) is 0) {
bits &= ~(OS.WS_HSCROLL | OS.WS_VSCROLL);
bits |= OS.TVS_NOSCROLL;
}
else {
if ((style & SWT.H_SCROLL) is 0) {
bits &= ~OS.WS_HSCROLL;
bits |= OS.TVS_NOHSCROLL;
}
}
OS.SetWindowLong(handle, OS.GWL_STYLE, bits);
}
override void enableDrag(bool enabled) {
int bits = OS.GetWindowLong(handle, OS.GWL_STYLE);
if (enabled && hooks(SWT.DragDetect)) {
bits &= ~OS.TVS_DISABLEDRAGDROP;
}
else {
bits |= OS.TVS_DISABLEDRAGDROP;
}
OS.SetWindowLong(handle, OS.GWL_STYLE, bits);
}
override void enableWidget(bool enabled) {
super.enableWidget(enabled);
/*
* Feature in Windows. When a tree is given a background color
* using TVM_SETBKCOLOR and the tree is disabled, Windows draws
* the tree using the background color rather than the disabled
* colors. This is different from the table which draws grayed.
* The fix is to set the default background color while the tree
* is disabled and restore it when enabled.
*/
Control control = findBackgroundControl();
/*
* Bug in Windows. On Vista only, Windows does not draw using
* the background color when the tree is disabled. The fix is
* to set the default color, even when the color has not been
* changed, causing Windows to draw correctly.
*/
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0)) {
if (control is null)
control = this;
}
if (control !is null) {
if (control.backgroundImage is null) {
_setBackgroundPixel(enabled ? control.getBackgroundPixel() : -1);
}
}
if (hwndParent !is null)
OS.EnableWindow(hwndParent, enabled);
/*
* Feature in Windows. When the tree has the style
* TVS_FULLROWSELECT, the background color for the
* entire row is filled when an item is painted,
* drawing on top of the sort column color. The fix
* is to clear TVS_FULLROWSELECT when a their is
* as sort column.
*/
updateFullSelection();
}
bool findCell(int x, int y, ref TreeItem item, ref int index,
ref RECT* cellRect, ref RECT* itemRect) {
bool found = false;
TVHITTESTINFO lpht;
lpht.pt.x = x;
lpht.pt.y = y;
OS.SendMessage(handle, OS.TVM_HITTEST, 0, &lpht);
if (lpht.hItem !is null) {
item = _getItem(lpht.hItem);
POINT pt;
pt.x = x;
pt.y = y;
auto hDC = OS.GetDC(handle);
HFONT oldFont;
auto newFont = cast(HFONT) OS.SendMessage(handle, OS.WM_GETFONT, 0, 0);
if (newFont !is null)
oldFont = OS.SelectObject(hDC, newFont);
RECT rect;
if (hwndParent !is null) {
OS.GetClientRect(hwndParent, &rect);
OS.MapWindowPoints(hwndParent, handle, cast(POINT*)&rect, 2);
}
else {
OS.GetClientRect(handle, &rect);
}
int count = Math.max(1, columnCount);
int[] order = new int[count];
if (hwndHeader !is null)
OS.SendMessage(hwndHeader, OS.HDM_GETORDERARRAY, count, order.ptr);
index = 0;
bool quit = false;
while (index < count && !quit) {
auto hFont = item.fontHandle(order[index]);
if (hFont !is cast(HFONT)-1)
hFont = OS.SelectObject(hDC, hFont);
cellRect = item.getBounds(order[index], true, false, true, false, true, hDC);
if (cellRect.left > rect.right) {
quit = true;
}
else {
cellRect.right = Math.min(cellRect.right, rect.right);
if (OS.PtInRect(cellRect, pt)) {
if (isCustomToolTip()) {
Event event = sendMeasureItemEvent(item, order[index], hDC);
if (isDisposed() || item.isDisposed())
break;
itemRect = new RECT();
itemRect.left = event.x;
itemRect.right = event.x + event.width;
itemRect.top = event.y;
itemRect.bottom = event.y + event.height;
}
else {
itemRect = item.getBounds(order[index], true,
false, false, false, false, hDC);
}
if (itemRect.right > cellRect.right)
found = true;
quit = true;
}
}
if (hFont !is cast(HFONT)-1)
OS.SelectObject(hDC, hFont);
if (!found)
index++;
}
if (newFont !is null)
OS.SelectObject(hDC, oldFont);
OS.ReleaseDC(handle, hDC);
}
return found;
}
int findIndex(HANDLE hFirstItem, HANDLE hItem) {
if (hFirstItem is null)
return -1;
if (hFirstItem is hFirstIndexOf) {
if (hFirstIndexOf is hItem) {
hLastIndexOf = hFirstIndexOf;
return lastIndexOf = 0;
}
if (hLastIndexOf is hItem)
return lastIndexOf;
auto hPrevItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_PREVIOUS, hLastIndexOf);
if (hPrevItem is hItem) {
hLastIndexOf = hPrevItem;
return --lastIndexOf;
}
HANDLE hNextItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hLastIndexOf);
if (hNextItem is hItem) {
hLastIndexOf = hNextItem;
return ++lastIndexOf;
}
int previousIndex = lastIndexOf - 1;
while (hPrevItem !is null && hPrevItem !is hItem) {
hPrevItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_PREVIOUS, hPrevItem);
--previousIndex;
}
if (hPrevItem is hItem) {
hLastIndexOf = hPrevItem;
return lastIndexOf = previousIndex;
}
int nextIndex = lastIndexOf + 1;
while (hNextItem !is null && hNextItem !is hItem) {
hNextItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hNextItem);
nextIndex++;
}
if (hNextItem is hItem) {
hLastIndexOf = hNextItem;
return lastIndexOf = nextIndex;
}
return -1;
}
int index = 0;
auto hNextItem = hFirstItem;
while (hNextItem !is null && hNextItem !is hItem) {
hNextItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM,
OS.TVGN_NEXT, hNextItem);
index++;
}
if (hNextItem is hItem) {
itemCount = -1;
hFirstIndexOf = hFirstItem;
hLastIndexOf = hNextItem;
return lastIndexOf = index;
}
return -1;
}
override Widget findItem(HANDLE hItem) {
return _getItem(hItem);
}
HANDLE findItem(HANDLE hFirstItem, int index) {
if (hFirstItem is null)
return null;
if (hFirstItem is hFirstIndexOf) {
if (index is 0) {
lastIndexOf = 0;
return hLastIndexOf = hFirstIndexOf;
}
if (lastIndexOf is index)
return hLastIndexOf;
if (lastIndexOf - 1 is index) {
--lastIndexOf;
return hLastIndexOf = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_PREVIOUS, hLastIndexOf);
}
if (lastIndexOf + 1 is index) {
lastIndexOf++;
return hLastIndexOf = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hLastIndexOf);
}
if (index < lastIndexOf) {
int previousIndex = lastIndexOf - 1;
auto hPrevItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_PREVIOUS, hLastIndexOf);
while (hPrevItem !is null && index < previousIndex) {
hPrevItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_PREVIOUS, hPrevItem);
--previousIndex;
}
if (index is previousIndex) {
lastIndexOf = previousIndex;
return hLastIndexOf = hPrevItem;
}
}
else {
int nextIndex = lastIndexOf + 1;
auto hNextItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hLastIndexOf);
while (hNextItem !is null && nextIndex < index) {
hNextItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hNextItem);
nextIndex++;
}
if (index is nextIndex) {
lastIndexOf = nextIndex;
return hLastIndexOf = hNextItem;
}
}
return null;
}
int nextIndex = 0;
auto hNextItem = hFirstItem;
while (hNextItem !is null && nextIndex < index) {
hNextItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM,
OS.TVGN_NEXT, hNextItem);
nextIndex++;
}
if (index is nextIndex) {
itemCount = -1;
lastIndexOf = nextIndex;
hFirstIndexOf = hFirstItem;
return hLastIndexOf = hNextItem;
}
return null;
}
TreeItem getFocusItem() {
// checkWidget ();
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
return hItem !is null ? _getItem(hItem) : null;
}
/**
* Returns the width in pixels of a grid line.
*
* @return the width of a grid line in pixels
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.1
*/
public int getGridLineWidth() {
checkWidget();
return GRID_WIDTH;
}
/**
* Returns the height of the receiver's header
*
* @return the height of the header or zero if the header is not visible
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.1
*/
public int getHeaderHeight() {
checkWidget();
if (hwndHeader is null)
return 0;
RECT rect;
OS.GetWindowRect(hwndHeader, &rect);
return rect.bottom - rect.top;
}
/**
* Returns <code>true</code> if the receiver's header is visible,
* and <code>false</code> otherwise.
* <p>
* If one of the receiver's ancestors is not visible or some
* other condition makes the receiver not visible, this method
* may still indicate that it is considered visible even though
* it may not actually be showing.
* </p>
*
* @return the receiver's header's visibility state
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.1
*/
public bool getHeaderVisible() {
checkWidget();
if (hwndHeader is null)
return false;
int bits = OS.GetWindowLong(hwndHeader, OS.GWL_STYLE);
return (bits & OS.WS_VISIBLE) !is 0;
}
Point getImageSize() {
if (imageList !is null)
return imageList.getImageSize();
return new Point(0, getItemHeight());
}
HANDLE getBottomItem() {
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM,
OS.TVGN_FIRSTVISIBLE, 0);
if (hItem is null)
return null;
auto index = 0, count = OS.SendMessage(handle, OS.TVM_GETVISIBLECOUNT, 0, 0);
while (index < count) {
HANDLE hNextItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_NEXTVISIBLE, hItem);
if (hNextItem is null)
return hItem;
hItem = hNextItem;
index++;
}
return hItem;
}
/**
* Returns the column at the given, zero-relative index in the
* receiver. Throws an exception if the index is out of range.
* Columns are returned in the order that they were created.
* If no <code>TreeColumn</code>s were created by the programmer,
* this method will throw <code>ERROR_INVALID_RANGE</code> despite
* the fact that a single column of data may be visible in the tree.
* This occurs when the programmer uses the tree like a list, adding
* items but never creating a column.
*
* @param index the index of the column to return
* @return the column at the given index
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_INVALID_RANGE - if the index is not between 0 and the number of elements in the list minus 1 (inclusive)</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see Tree#getColumnOrder()
* @see Tree#setColumnOrder(int[])
* @see TreeColumn#getMoveable()
* @see TreeColumn#setMoveable(bool)
* @see SWT#Move
*
* @since 3.1
*/
public TreeColumn getColumn(int index) {
checkWidget();
if (!(0 <= index && index < columnCount))
error(SWT.ERROR_INVALID_RANGE);
return columns[index];
}
/**
* Returns the number of columns contained in the receiver.
* If no <code>TreeColumn</code>s were created by the programmer,
* this value is zero, despite the fact that visually, one column
* of items may be visible. This occurs when the programmer uses
* the tree like a list, adding items but never creating a column.
*
* @return the number of columns
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.1
*/
public int getColumnCount() {
checkWidget();
return columnCount;
}
/**
* Returns an array of zero-relative integers that map
* the creation order of the receiver's items to the
* order in which they are currently being displayed.
* <p>
* Specifically, the indices of the returned array represent
* the current visual order of the items, and the contents
* of the array represent the creation order of the items.
* </p><p>
* Note: This is not the actual structure used by the receiver
* to maintain its list of items, so modifying the array will
* not affect the receiver.
* </p>
*
* @return the current visual order of the receiver's items
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see Tree#setColumnOrder(int[])
* @see TreeColumn#getMoveable()
* @see TreeColumn#setMoveable(bool)
* @see SWT#Move
*
* @since 3.2
*/
public int[] getColumnOrder() {
checkWidget();
if (columnCount is 0)
return null;
int[] order = new int[columnCount];
OS.SendMessage(hwndHeader, OS.HDM_GETORDERARRAY, columnCount, order.ptr);
return order;
}
/**
* Returns an array of <code>TreeColumn</code>s which are the
* columns in the receiver. Columns are returned in the order
* that they were created. If no <code>TreeColumn</code>s were
* created by the programmer, the array is empty, despite the fact
* that visually, one column of items may be visible. This occurs
* when the programmer uses the tree like a list, adding items but
* never creating a column.
* <p>
* Note: This is not the actual structure used by the receiver
* to maintain its list of items, so modifying the array will
* not affect the receiver.
* </p>
*
* @return the items in the receiver
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see Tree#getColumnOrder()
* @see Tree#setColumnOrder(int[])
* @see TreeColumn#getMoveable()
* @see TreeColumn#setMoveable(bool)
* @see SWT#Move
*
* @since 3.1
*/
public TreeColumn[] getColumns() {
checkWidget();
TreeColumn[] result = new TreeColumn[columnCount];
System.arraycopy(columns, 0, result, 0, columnCount);
return result;
}
/**
* Returns the item at the given, zero-relative index in the
* receiver. Throws an exception if the index is out of range.
*
* @param index the index of the item to return
* @return the item at the given index
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_INVALID_RANGE - if the index is not between 0 and the number of elements in the list minus 1 (inclusive)</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.1
*/
public TreeItem getItem(int index) {
checkWidget();
if (index < 0)
error(SWT.ERROR_INVALID_RANGE);
auto hFirstItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
if (hFirstItem is null)
error(SWT.ERROR_INVALID_RANGE);
HANDLE hItem = findItem(hFirstItem, index);
if (hItem is null)
error(SWT.ERROR_INVALID_RANGE);
return _getItem(hItem);
}
TreeItem getItem(NMTVCUSTOMDRAW* nmcd) {
/*
* Bug in Windows. If the lParam field of TVITEM
* is changed during custom draw using TVM_SETITEM,
* the lItemlParam field of the NMTVCUSTOMDRAW struct
* is not updated until the next custom draw. The
* fix is to query the field from the item instead
* of using the struct.
*/
auto id = nmcd.nmcd.lItemlParam;
if ((style & SWT.VIRTUAL) !is 0) {
if (id is -1) {
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM;
tvItem.hItem = cast(HTREEITEM) nmcd.nmcd.dwItemSpec;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
id = tvItem.lParam;
}
}
return _getItem(cast(HANDLE) nmcd.nmcd.dwItemSpec, id);
}
/**
* Returns the item at the given point in the receiver
* or null if no such item exists. The point is in the
* coordinate system of the receiver.
* <p>
* The item that is returned represents an item that could be selected by the user.
* For example, if selection only occurs in items in the first column, then null is
* returned if the point is outside of the item.
* Note that the SWT.FULL_SELECTION style hint, which specifies the selection policy,
* determines the extent of the selection.
* </p>
*
* @param point the point used to locate the item
* @return the item at the given point, or null if the point is not in a selectable item
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the point is null</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public TreeItem getItem(Point point) {
checkWidget();
if (point is null)
error(SWT.ERROR_NULL_ARGUMENT);
TVHITTESTINFO lpht;
lpht.pt.x = point.x;
lpht.pt.y = point.y;
OS.SendMessage(handle, OS.TVM_HITTEST, 0, &lpht);
if (lpht.hItem !is null) {
int flags = OS.TVHT_ONITEM;
if ((style & SWT.FULL_SELECTION) !is 0) {
flags |= OS.TVHT_ONITEMRIGHT | OS.TVHT_ONITEMINDENT;
}
else {
if (hooks(SWT.MeasureItem)) {
lpht.flags &= ~(OS.TVHT_ONITEMICON | OS.TVHT_ONITEMLABEL);
if (hitTestSelection(lpht.hItem, lpht.pt.x, lpht.pt.y)) {
lpht.flags |= OS.TVHT_ONITEMICON | OS.TVHT_ONITEMLABEL;
}
}
}
if ((lpht.flags & flags) !is 0)
return _getItem(lpht.hItem);
}
return null;
}
/**
* Returns the number of items contained in the receiver
* that are direct item children of the receiver. The
* number that is returned is the number of roots in the
* tree.
*
* @return the number of items
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public int getItemCount() {
checkWidget();
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
if (hItem is null)
return 0;
return getItemCount(hItem);
}
int getItemCount(HANDLE hItem) {
int count = 0;
auto hFirstItem = hItem;
if (hItem is hFirstIndexOf) {
if (itemCount !is -1)
return itemCount;
hFirstItem = hLastIndexOf;
count = lastIndexOf;
}
while (hFirstItem !is null) {
hFirstItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hFirstItem);
count++;
}
if (hItem is hFirstIndexOf)
itemCount = count;
return count;
}
/**
* Returns the height of the area which would be used to
* display <em>one</em> of the items in the tree.
*
* @return the height of one item
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public int getItemHeight() {
checkWidget();
return cast(int) /*64bit*/ OS.SendMessage(handle, OS.TVM_GETITEMHEIGHT, 0, 0);
}
/**
* Returns a (possibly empty) array of items contained in the
* receiver that are direct item children of the receiver. These
* are the roots of the tree.
* <p>
* Note: This is not the actual structure used by the receiver
* to maintain its list of items, so modifying the array will
* not affect the receiver.
* </p>
*
* @return the items
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public TreeItem[] getItems() {
checkWidget();
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
if (hItem is null)
return null;
return getItems(hItem);
}
TreeItem[] getItems(HANDLE hTreeItem) {
int count = 0;
auto hItem = hTreeItem;
while (hItem !is null) {
hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem);
count++;
}
int index = 0;
TreeItem[] result = new TreeItem[count];
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM;
tvItem.hItem = cast(HTREEITEM) hTreeItem;
/*
* Feature in Windows. In some cases an expand or collapse message
* can occur from within TVM_DELETEITEM. When this happens, the item
* being destroyed has been removed from the list of items but has not
* been deleted from the tree. The fix is to check for null items and
* remove them from the list.
*/
while (tvItem.hItem !is null) {
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
TreeItem item = _getItem(tvItem.hItem, tvItem.lParam);
if (item !is null)
result[index++] = item;
tvItem.hItem = cast(HTREEITEM) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, tvItem.hItem);
}
if (index !is count) {
TreeItem[] newResult = new TreeItem[index];
System.arraycopy(result, 0, newResult, 0, index);
result = newResult;
}
return result;
}
/**
* Returns <code>true</code> if the receiver's lines are visible,
* and <code>false</code> otherwise.
* <p>
* If one of the receiver's ancestors is not visible or some
* other condition makes the receiver not visible, this method
* may still indicate that it is considered visible even though
* it may not actually be showing.
* </p>
*
* @return the visibility state of the lines
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.1
*/
public bool getLinesVisible() {
checkWidget();
return linesVisible;
}
HANDLE getNextSelection(HANDLE hItem, TVITEM* tvItem) {
while (hItem !is null) {
.LRESULT state = 0;
static if (OS.IsWinCE) {
tvItem.hItem = hItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, tvItem);
state = tvItem.state;
}
else {
state = OS.SendMessage(handle, OS.TVM_GETITEMSTATE, hItem, OS.TVIS_SELECTED);
}
if ((state & OS.TVIS_SELECTED) !is 0)
return hItem;
auto hFirstItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hItem);
auto hSelected = getNextSelection(hFirstItem, tvItem);
if (hSelected !is null)
return hSelected;
hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem);
}
return null;
}
/**
* Returns the receiver's parent item, which must be a
* <code>TreeItem</code> or null when the receiver is a
* root.
*
* @return the receiver's parent item
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public TreeItem getParentItem() {
checkWidget();
return null;
}
int getSelection(HANDLE hItem, TVITEM* tvItem, TreeItem[] selection,
int index, int count, bool bigSelection, bool all) {
while (hItem !is null) {
if (OS.IsWinCE || bigSelection) {
tvItem.hItem = cast(HTREEITEM) hItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, tvItem);
if ((tvItem.state & OS.TVIS_SELECTED) !is 0) {
if (selection !is null && index < selection.length) {
selection[index] = _getItem(hItem, tvItem.lParam);
}
index++;
}
}
else {
auto state = OS.SendMessage(handle, OS.TVM_GETITEMSTATE, hItem, OS.TVIS_SELECTED);
if ((state & OS.TVIS_SELECTED) !is 0) {
if (tvItem !is null && selection !is null && index < selection.length) {
tvItem.hItem = cast(HTREEITEM) hItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, tvItem);
selection[index] = _getItem(hItem, tvItem.lParam);
}
index++;
}
}
if (index is count)
break;
if (all) {
auto hFirstItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hItem);
if ((index = getSelection(hFirstItem, tvItem, selection, index,
count, bigSelection, all)) is count) {
break;
}
hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM,
OS.TVGN_NEXT, hItem);
}
else {
hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM,
OS.TVGN_NEXTVISIBLE, hItem);
}
}
return index;
}
/**
* Returns an array of <code>TreeItem</code>s that are currently
* selected in the receiver. The order of the items is unspecified.
* An empty array indicates that no items are selected.
* <p>
* Note: This is not the actual structure used by the receiver
* to maintain its selection, so modifying the array will
* not affect the receiver.
* </p>
* @return an array representing the selection
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public TreeItem[] getSelection() {
checkWidget();
if ((style & SWT.SINGLE) !is 0) {
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
if (hItem is null)
return new TreeItem[0];
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM | OS.TVIF_STATE;
tvItem.hItem = cast(HTREEITEM) hItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
if ((tvItem.state & OS.TVIS_SELECTED) is 0)
return new TreeItem[0];
return [_getItem(tvItem.hItem, tvItem.lParam)];
}
int count = 0;
TreeItem[] guess = new TreeItem[(style & SWT.VIRTUAL) !is 0 ? 8 : 1];
LONG_PTR oldProc = OS.GetWindowLongPtr(handle, OS.GWLP_WNDPROC);
OS.SetWindowLongPtr(handle, OS.GWLP_WNDPROC, cast(LONG_PTR) TreeProc);
if ((style & SWT.VIRTUAL) !is 0) {
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM | OS.TVIF_STATE;
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
count = getSelection(hItem, &tvItem, guess, 0, -1, false, true);
}
else {
TVITEM tvItem;
static if (OS.IsWinCE) {
//tvItem = new TVITEM ();
tvItem.mask = OS.TVIF_STATE;
}
for (int i = 0; i < items.length; i++) {
TreeItem item = items[i];
if (item !is null) {
HANDLE hItem = item.handle;
.LRESULT state = 0;
static if (OS.IsWinCE) {
tvItem.hItem = hItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
state = tvItem.state;
}
else {
state = OS.SendMessage(handle, OS.TVM_GETITEMSTATE,
hItem, OS.TVIS_SELECTED);
}
if ((state & OS.TVIS_SELECTED) !is 0) {
if (count < guess.length)
guess[count] = item;
count++;
}
}
}
}
OS.SetWindowLongPtr(handle, OS.GWLP_WNDPROC, oldProc);
if (count is 0)
return new TreeItem[0];
if (count is guess.length)
return guess;
TreeItem[] result = new TreeItem[count];
if (count < guess.length) {
System.arraycopy(guess, 0, result, 0, count);
return result;
}
OS.SetWindowLongPtr(handle, OS.GWLP_WNDPROC, cast(LONG_PTR) TreeProc);
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM | OS.TVIF_STATE;
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
auto itemCount = OS.SendMessage(handle, OS.TVM_GETCOUNT, 0, 0);
bool bigSelection = result.length > itemCount / 2;
if (count !is getSelection(hItem, &tvItem, result, 0, count, bigSelection, false)) {
getSelection(hItem, &tvItem, result, 0, count, bigSelection, true);
}
OS.SetWindowLongPtr(handle, OS.GWLP_WNDPROC, oldProc);
return result;
}
/**
* Returns the number of selected items contained in the receiver.
*
* @return the number of selected items
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public int getSelectionCount() {
checkWidget();
if ((style & SWT.SINGLE) !is 0) {
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
if (hItem is null)
return 0;
.LRESULT state = 0;
static if (OS.IsWinCE) {
TVITEM tvItem;
tvItem.hItem = hItem;
tvItem.mask = OS.TVIF_STATE;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
state = tvItem.state;
}
else {
state = OS.SendMessage(handle, OS.TVM_GETITEMSTATE, hItem, OS.TVIS_SELECTED);
}
return (state & OS.TVIS_SELECTED) is 0 ? 0 : 1;
}
int count = 0;
auto oldProc = OS.GetWindowLongPtr(handle, OS.GWLP_WNDPROC);
TVITEM tvItem_;
TVITEM* tvItem = null;
static if (OS.IsWinCE) {
tvItem = &tvitem_;
tvItem.mask = OS.TVIF_STATE;
}
OS.SetWindowLongPtr(handle, OS.GWLP_WNDPROC, cast(LONG_PTR) TreeProc);
if ((style & SWT.VIRTUAL) !is 0) {
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
count = getSelection(hItem, tvItem, null, 0, -1, false, true);
}
else {
for (int i = 0; i < items.length; i++) {
TreeItem item = items[i];
if (item !is null) {
auto hItem = item.handle;
.LRESULT state = 0;
static if (OS.IsWinCE) {
tvItem.hItem = hItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, tvItem);
state = tvItem.state;
}
else {
state = OS.SendMessage(handle, OS.TVM_GETITEMSTATE,
hItem, OS.TVIS_SELECTED);
}
if ((state & OS.TVIS_SELECTED) !is 0)
count++;
}
}
}
OS.SetWindowLongPtr(handle, OS.GWLP_WNDPROC, oldProc);
return count;
}
/**
* Returns the column which shows the sort indicator for
* the receiver. The value may be null if no column shows
* the sort indicator.
*
* @return the sort indicator
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see #setSortColumn(TreeColumn)
*
* @since 3.2
*/
public TreeColumn getSortColumn() {
checkWidget();
return sortColumn;
}
int getSortColumnPixel() {
int pixel = OS.IsWindowEnabled(handle) ? getBackgroundPixel()
: OS.GetSysColor(OS.COLOR_3DFACE);
int red = pixel & 0xFF;
int green = (pixel & 0xFF00) >> 8;
int blue = (pixel & 0xFF0000) >> 16;
if (red > 240 && green > 240 && blue > 240) {
red -= 8;
green -= 8;
blue -= 8;
}
else {
red = Math.min(0xFF, (red / 10) + red);
green = Math.min(0xFF, (green / 10) + green);
blue = Math.min(0xFF, (blue / 10) + blue);
}
return (red & 0xFF) | ((green & 0xFF) << 8) | ((blue & 0xFF) << 16);
}
/**
* Returns the direction of the sort indicator for the receiver.
* The value will be one of <code>UP</code>, <code>DOWN</code>
* or <code>NONE</code>.
*
* @return the sort direction
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see #setSortDirection(int)
*
* @since 3.2
*/
public int getSortDirection() {
checkWidget();
return sortDirection;
}
/**
* Returns the item which is currently at the top of the receiver.
* This item can change when items are expanded, collapsed, scrolled
* or new items are added or removed.
*
* @return the item at the top of the receiver
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 2.1
*/
public TreeItem getTopItem() {
checkWidget();
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM,
OS.TVGN_FIRSTVISIBLE, 0);
return hItem !is null ? _getItem(hItem) : null;
}
bool hitTestSelection(HANDLE hItem, int x, int y) {
if (hItem is null)
return false;
TreeItem item = _getItem(hItem);
if (item is null)
return false;
if (!hooks(SWT.MeasureItem))
return false;
bool result = false;
//BUG? - moved columns, only hittest first column
//BUG? - check drag detect
int[] order = new int[1], index = new int[1];
auto hDC = OS.GetDC(handle);
HFONT oldFont, newFont = cast(HFONT) OS.SendMessage(handle, OS.WM_GETFONT, 0, 0);
if (newFont !is null)
oldFont = OS.SelectObject(hDC, newFont);
auto hFont = item.fontHandle(order[index[0]]);
if (hFont !is cast(HFONT)-1)
hFont = OS.SelectObject(hDC, hFont);
Event event = sendMeasureItemEvent(item, order[index[0]], hDC);
if (event.getBounds().contains(x, y))
result = true;
if (newFont !is null)
OS.SelectObject(hDC, oldFont);
OS.ReleaseDC(handle, hDC);
// if (isDisposed () || item.isDisposed ()) return false;
return result;
}
int imageIndex(Image image, int index) {
if (image is null)
return OS.I_IMAGENONE;
if (imageList is null) {
Rectangle bounds = image.getBounds();
imageList = display.getImageList(style & SWT.RIGHT_TO_LEFT, bounds.width, bounds.height);
}
int imageIndex = imageList.indexOf(image);
if (imageIndex is -1)
imageIndex = imageList.add(image);
if (hwndHeader is null || OS.SendMessage(hwndHeader, OS.HDM_ORDERTOINDEX, 0, 0) is index) {
/*
* Feature in Windows. When setting the same image list multiple
* times, Windows does work making this operation slow. The fix
* is to test for the same image list before setting the new one.
*/
auto hImageList = imageList.getHandle();
auto hOldImageList = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETIMAGELIST, OS.TVSIL_NORMAL, 0);
if (hOldImageList !is hImageList) {
OS.SendMessage(handle, OS.TVM_SETIMAGELIST, OS.TVSIL_NORMAL, hImageList);
updateScrollBar();
}
}
return imageIndex;
}
int imageIndexHeader(Image image) {
if (image is null)
return OS.I_IMAGENONE;
if (headerImageList is null) {
Rectangle bounds = image.getBounds();
headerImageList = display.getImageList(style & SWT.RIGHT_TO_LEFT,
bounds.width, bounds.height);
int index = headerImageList.indexOf(image);
if (index is -1)
index = headerImageList.add(image);
auto hImageList = headerImageList.getHandle();
if (hwndHeader !is null) {
OS.SendMessage(hwndHeader, OS.HDM_SETIMAGELIST, 0, hImageList);
}
updateScrollBar();
return index;
}
int index = headerImageList.indexOf(image);
if (index !is -1)
return index;
return headerImageList.add(image);
}
/**
* Searches the receiver's list starting at the first column
* (index 0) until a column is found that is equal to the
* argument, and returns the index of that column. If no column
* is found, returns -1.
*
* @param column the search column
* @return the index of the column
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the column is null</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.1
*/
public int indexOf(TreeColumn column) {
checkWidget();
if (column is null)
error(SWT.ERROR_NULL_ARGUMENT);
if (column.isDisposed())
error(SWT.ERROR_INVALID_ARGUMENT);
for (int i = 0; i < columnCount; i++) {
if (columns[i] is column)
return i;
}
return -1;
}
/**
* Searches the receiver's list starting at the first item
* (index 0) until an item is found that is equal to the
* argument, and returns the index of that item. If no item
* is found, returns -1.
*
* @param item the search item
* @return the index of the item
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the item is null</li>
* <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.1
*/
public int indexOf(TreeItem item) {
checkWidget();
if (item is null)
error(SWT.ERROR_NULL_ARGUMENT);
if (item.isDisposed())
error(SWT.ERROR_INVALID_ARGUMENT);
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
return hItem is null ? -1 : findIndex(hItem, item.handle);
}
bool isCustomToolTip() {
return hooks(SWT.MeasureItem);
}
bool isItemSelected(NMTVCUSTOMDRAW* nmcd) {
bool selected = false;
if (OS.IsWindowEnabled(handle)) {
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE;
tvItem.hItem = cast(HTREEITEM) nmcd.nmcd.dwItemSpec;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
if ((tvItem.state & (OS.TVIS_SELECTED | OS.TVIS_DROPHILITED)) !is 0) {
selected = true;
/*
* Feature in Windows. When the mouse is pressed and the
* selection is first drawn for a tree, the previously
* selected item is redrawn but the the TVIS_SELECTED bits
* are not cleared. When the user moves the mouse slightly
* and a drag and drop operation is not started, the item is
* drawn again and this time with TVIS_SELECTED is cleared.
* This means that an item that contains colored cells will
* not draw with the correct background until the mouse is
* moved. The fix is to test for the selection colors and
* guess that the item is not selected.
*
* NOTE: This code does not work when the foreground and
* background of the tree are set to the selection colors
* but this does not happen in a regular application.
*/
if (handle is OS.GetFocus()) {
if (OS.GetTextColor(nmcd.nmcd.hdc) !is OS.GetSysColor(OS.COLOR_HIGHLIGHTTEXT)) {
selected = false;
}
else {
if (OS.GetBkColor(nmcd.nmcd.hdc) !is OS.GetSysColor(OS.COLOR_HIGHLIGHT)) {
selected = false;
}
}
}
}
else {
if (nmcd.nmcd.dwDrawStage is OS.CDDS_ITEMPOSTPAINT) {
/*
* Feature in Windows. When the mouse is pressed and the
* selection is first drawn for a tree, the item is drawn
* selected, but the TVIS_SELECTED bits for the item are
* not set. When the user moves the mouse slightly and
* a drag and drop operation is not started, the item is
* drawn again and this time TVIS_SELECTED is set. This
* means that an item that is in a tree that has the style
* TVS_FULLROWSELECT and that also contains colored cells
* will not draw the entire row selected until the user
* moves the mouse. The fix is to test for the selection
* colors and guess that the item is selected.
*
* NOTE: This code does not work when the foreground and
* background of the tree are set to the selection colors
* but this does not happen in a regular application.
*/
if (OS.GetTextColor(nmcd.nmcd.hdc) is OS.GetSysColor(OS.COLOR_HIGHLIGHTTEXT)) {
if (OS.GetBkColor(nmcd.nmcd.hdc) is OS.GetSysColor(OS.COLOR_HIGHLIGHT)) {
selected = true;
}
}
}
}
}
return selected;
}
void redrawSelection() {
if ((style & SWT.SINGLE) !is 0) {
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
if (hItem !is null) {
RECT rect;
if (OS.TreeView_GetItemRect(handle, cast(HTREEITEM) hItem, &rect, false)) {
OS.InvalidateRect(handle, &rect, true);
}
}
}
else {
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0);
if (hItem !is null) {
TVITEM tvItem;
static if (OS.IsWinCE) {
//tvItem = new TVITEM ();
tvItem.mask = OS.TVIF_STATE;
}
RECT rect;
auto index = 0, count = OS.SendMessage(handle, OS.TVM_GETVISIBLECOUNT, 0, 0);
while (index <= count && hItem !is null) {
.LRESULT state = 0;
static if (OS.IsWinCE) {
tvItem.hItem = hItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
state = tvItem.state;
}
else {
state = OS.SendMessage(handle, OS.TVM_GETITEMSTATE,
hItem, OS.TVIS_SELECTED);
}
if ((state & OS.TVIS_SELECTED) !is 0) {
if (OS.TreeView_GetItemRect(handle, cast(HTREEITEM) hItem, &rect, false)) {
OS.InvalidateRect(handle, &rect, true);
}
}
hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_NEXTVISIBLE, hItem);
index++;
}
}
}
}
override void register() {
super.register();
if (hwndParent !is null)
display.addControl(hwndParent, this);
if (hwndHeader !is null)
display.addControl(hwndHeader, this);
}
void releaseItem(HANDLE hItem, TVITEM* tvItem, bool release) {
if (hItem is hAnchor)
hAnchor = null;
if (hItem is hInsert)
hInsert = null;
tvItem.hItem = cast(HTREEITEM) hItem;
if (OS.SendMessage(handle, OS.TVM_GETITEM, 0, tvItem) !is 0) {
if (tvItem.lParam !is -1) {
if (tvItem.lParam < lastID)
lastID = cast(int) /*64bit*/ tvItem.lParam;
if (release) {
TreeItem item = items[tvItem.lParam];
if (item !is null)
item.release(false);
}
items[tvItem.lParam] = null;
}
}
}
void releaseItems(HANDLE hItem, TVITEM* tvItem) {
hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hItem);
while (hItem !is null) {
releaseItems(hItem, tvItem);
releaseItem(hItem, tvItem, true);
hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem);
}
}
override void releaseHandle() {
super.releaseHandle();
hwndParent = hwndHeader = null;
}
override void releaseChildren(bool destroy) {
if (items !is null) {
for (int i = 0; i < items.length; i++) {
TreeItem item = items[i];
if (item !is null && !item.isDisposed()) {
item.release(false);
}
}
items = null;
}
if (columns !is null) {
for (int i = 0; i < columns.length; i++) {
TreeColumn column = columns[i];
if (column !is null && !column.isDisposed()) {
column.release(false);
}
}
columns = null;
}
super.releaseChildren(destroy);
}
override void releaseWidget() {
super.releaseWidget();
/*
* Feature in Windows. For some reason, when TVM_GETIMAGELIST
* or TVM_SETIMAGELIST is sent, the tree issues NM_CUSTOMDRAW
* messages. This behavior is unwanted when the tree is being
* disposed. The fix is to ignore NM_CUSTOMDRAW messages by
* clearing the custom draw flag.
*
* NOTE: This only happens on Windows XP.
*/
customDraw = false;
if (imageList !is null) {
OS.SendMessage(handle, OS.TVM_SETIMAGELIST, OS.TVSIL_NORMAL, 0);
display.releaseImageList(imageList);
}
if (headerImageList !is null) {
if (hwndHeader !is null) {
OS.SendMessage(hwndHeader, OS.HDM_SETIMAGELIST, 0, 0);
}
display.releaseImageList(headerImageList);
}
imageList = headerImageList = null;
auto hStateList = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETIMAGELIST, OS.TVSIL_STATE, 0);
OS.SendMessage(handle, OS.TVM_SETIMAGELIST, OS.TVSIL_STATE, 0);
if (hStateList !is null)
OS.ImageList_Destroy(hStateList);
if (itemToolTipHandle !is null)
OS.DestroyWindow(itemToolTipHandle);
if (headerToolTipHandle !is null)
OS.DestroyWindow(headerToolTipHandle);
itemToolTipHandle = headerToolTipHandle = null;
}
/**
* Removes all of the items from the receiver.
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public void removeAll() {
checkWidget();
hFirstIndexOf = hLastIndexOf = null;
itemCount = -1;
for (int i = 0; i < items.length; i++) {
TreeItem item = items[i];
if (item !is null && !item.isDisposed()) {
item.release(false);
}
}
ignoreDeselect = ignoreSelect = true;
bool redraw = drawCount is 0 && OS.IsWindowVisible(handle);
if (redraw)
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 0, 0);
shrink = ignoreShrink = true;
auto result = OS.SendMessage(handle, OS.TVM_DELETEITEM, 0, OS.TVI_ROOT);
ignoreShrink = false;
if (redraw) {
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 1, 0);
OS.InvalidateRect(handle, null, true);
}
ignoreDeselect = ignoreSelect = false;
if (result is 0)
error(SWT.ERROR_ITEM_NOT_REMOVED);
if (imageList !is null) {
OS.SendMessage(handle, OS.TVM_SETIMAGELIST, 0, 0);
display.releaseImageList(imageList);
}
imageList = null;
if (hwndParent is null && !linesVisible) {
if (!hooks(SWT.MeasureItem) && !hooks(SWT.EraseItem) && !hooks(SWT.PaintItem)) {
customDraw = false;
}
}
hAnchor = hInsert = hFirstIndexOf = hLastIndexOf = null;
itemCount = -1;
items = new TreeItem[4];
scrollWidth = 0;
setScrollWidth();
updateScrollBar();
}
/**
* Removes the listener from the collection of listeners who will
* be notified when the user changes the receiver's selection.
*
* @param listener the listener which should no longer be notified
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see SelectionListener
* @see #addSelectionListener
*/
public void removeSelectionListener(SelectionListener listener) {
checkWidget();
if (listener is null)
error(SWT.ERROR_NULL_ARGUMENT);
eventTable.unhook(SWT.Selection, listener);
eventTable.unhook(SWT.DefaultSelection, listener);
}
/**
* Removes the listener from the collection of listeners who will
* be notified when items in the receiver are expanded or collapsed.
*
* @param listener the listener which should no longer be notified
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see TreeListener
* @see #addTreeListener
*/
public void removeTreeListener(TreeListener listener) {
checkWidget();
if (listener is null)
error(SWT.ERROR_NULL_ARGUMENT);
if (eventTable is null)
return;
eventTable.unhook(SWT.Expand, listener);
eventTable.unhook(SWT.Collapse, listener);
}
/**
* Display a mark indicating the point at which an item will be inserted.
* The drop insert item has a visual hint to show where a dragged item
* will be inserted when dropped on the tree.
*
* @param item the insert item. Null will clear the insertion mark.
* @param before true places the insert mark above 'item'. false places
* the insert mark below 'item'.
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public void setInsertMark(TreeItem item, bool before) {
checkWidget();
HANDLE hItem;
if (item !is null) {
if (item.isDisposed())
error(SWT.ERROR_INVALID_ARGUMENT);
hItem = item.handle;
}
hInsert = hItem;
insertAfter = !before;
OS.SendMessage(handle, OS.TVM_SETINSERTMARK, insertAfter ? 1 : 0, hInsert);
}
/**
* Sets the number of root-level items contained in the receiver.
*
* @param count the number of items
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.2
*/
public void setItemCount(int count) {
checkWidget();
count = Math.max(0, count);
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
setItemCount(count, cast(HANDLE) OS.TVGN_ROOT, hItem);
}
void setItemCount(int count, HANDLE hParent, HANDLE hItem) {
bool redraw = false;
if (OS.SendMessage(handle, OS.TVM_GETCOUNT, 0, 0) is 0) {
redraw = drawCount is 0 && OS.IsWindowVisible(handle);
if (redraw)
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 0, 0);
}
int itemCount = 0;
while (hItem !is null && itemCount < count) {
hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem);
itemCount++;
}
bool expanded = false;
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM;
if (!redraw && (style & SWT.VIRTUAL) !is 0) {
if (OS.IsWinCE) {
tvItem.hItem = cast(HTREEITEM) hParent;
tvItem.mask = OS.TVIF_STATE;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
expanded = (tvItem.state & OS.TVIS_EXPANDED) !is 0;
}
else {
/*
* Bug in Windows. Despite the fact that TVM_GETITEMSTATE claims
* to return only the bits specified by the stateMask, when called
* with TVIS_EXPANDED, the entire state is returned. The fix is
* to explicitly check for the TVIS_EXPANDED bit.
*/
auto state = OS.SendMessage(handle, OS.TVM_GETITEMSTATE,
hParent, OS.TVIS_EXPANDED);
expanded = (state & OS.TVIS_EXPANDED) !is 0;
}
}
while (hItem !is null) {
tvItem.hItem = cast(HTREEITEM) hItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem);
TreeItem item = tvItem.lParam !is -1 ? items[tvItem.lParam] : null;
if (item !is null && !item.isDisposed()) {
item.dispose();
}
else {
releaseItem(tvItem.hItem, &tvItem, false);
destroyItem(null, tvItem.hItem);
}
}
if ((style & SWT.VIRTUAL) !is 0) {
for (int i = itemCount; i < count; i++) {
if (expanded)
ignoreShrink = true;
createItem(null, hParent, cast(HTREEITEM) OS.TVI_LAST, null);
if (expanded)
ignoreShrink = false;
}
}
else {
shrink = true;
int extra = Math.max(4, (count + 3) / 4 * 4);
TreeItem[] newItems = new TreeItem[items.length + extra];
System.arraycopy(items, 0, newItems, 0, items.length);
items = newItems;
for (int i = itemCount; i < count; i++) {
new TreeItem(this, SWT.NONE, hParent, cast(HTREEITEM) OS.TVI_LAST, null);
}
}
if (redraw) {
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 1, 0);
OS.InvalidateRect(handle, null, true);
}
}
/**
* Sets the height of the area which would be used to
* display <em>one</em> of the items in the tree.
*
* @param itemHeight the height of one item
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.2
*/
/*public*/
void setItemHeight(int itemHeight) {
checkWidget();
if (itemHeight < -1)
error(SWT.ERROR_INVALID_ARGUMENT);
OS.SendMessage(handle, OS.TVM_SETITEMHEIGHT, itemHeight, 0);
}
/**
* Marks the receiver's lines as visible if the argument is <code>true</code>,
* and marks it invisible otherwise.
* <p>
* If one of the receiver's ancestors is not visible or some
* other condition makes the receiver not visible, marking
* it visible may not actually cause it to be displayed.
* </p>
*
* @param show the new visibility state
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.1
*/
public void setLinesVisible(bool show) {
checkWidget();
if (linesVisible is show)
return;
linesVisible = show;
if (hwndParent is null && linesVisible)
customDraw = true;
OS.InvalidateRect(handle, null, true);
}
override HWND scrolledHandle() {
if (hwndHeader is null)
return handle;
return columnCount is 0 && scrollWidth is 0 ? handle : hwndParent;
}
void select(HANDLE hItem, TVITEM* tvItem) {
while (hItem !is null) {
tvItem.hItem = cast(HTREEITEM) hItem;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, tvItem);
auto hFirstItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hItem);
select(hFirstItem, tvItem);
hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem);
}
}
/**
* Selects an item in the receiver. If the item was already
* selected, it remains selected.
*
* @param item the item to be selected
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the item is null</li>
* <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.4
*/
public void select(TreeItem item) {
checkWidget();
if (item is null)
error(SWT.ERROR_NULL_ARGUMENT);
if (item.isDisposed())
error(SWT.ERROR_INVALID_ARGUMENT);
if ((style & SWT.SINGLE) !is 0) {
auto hItem = item.handle;
.LRESULT state = 0;
static if (OS.IsWinCE) {
TVITEM tvItem;
tvItem.hItem = hItem;
tvItem.mask = OS.TVIF_STATE;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
state = tvItem.state;
}
else {
state = OS.SendMessage(handle, OS.TVM_GETITEMSTATE, &hItem, OS.TVIS_SELECTED);
}
if ((state & OS.TVIS_SELECTED) !is 0)
return;
/*
* Feature in Windows. When an item is selected with
* TVM_SELECTITEM and TVGN_CARET, the tree expands and
* scrolls to show the new selected item. Unfortunately,
* there is no other way in Windows to set the focus
* and select an item. The fix is to save the current
* scroll bar positions, turn off redraw, select the item,
* then scroll back to the original position and redraw
* the entire tree.
*/
SCROLLINFO* hInfo = null;
int bits = OS.GetWindowLong(handle, OS.GWL_STYLE);
if ((bits & (OS.TVS_NOHSCROLL | OS.TVS_NOSCROLL)) is 0) {
hInfo = new SCROLLINFO();
hInfo.cbSize = SCROLLINFO.sizeof;
hInfo.fMask = OS.SIF_ALL;
OS.GetScrollInfo(handle, OS.SB_HORZ, hInfo);
}
SCROLLINFO vInfo;
vInfo.cbSize = SCROLLINFO.sizeof;
vInfo.fMask = OS.SIF_ALL;
OS.GetScrollInfo(handle, OS.SB_VERT, &vInfo);
bool redraw = drawCount is 0 && OS.IsWindowVisible(handle);
if (redraw) {
OS.UpdateWindow(handle);
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 0, 0);
}
setSelection(item);
if (hInfo !is null) {
auto hThumb = OS.MAKELPARAM(OS.SB_THUMBPOSITION, hInfo.nPos);
OS.SendMessage(handle, OS.WM_HSCROLL, hThumb, 0);
}
auto vThumb = OS.MAKELPARAM(OS.SB_THUMBPOSITION, vInfo.nPos);
OS.SendMessage(handle, OS.WM_VSCROLL, vThumb, 0);
if (redraw) {
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 1, 0);
OS.InvalidateRect(handle, null, true);
if ((style & SWT.DOUBLE_BUFFERED) is 0) {
int oldStyle = style;
style |= SWT.DOUBLE_BUFFERED;
OS.UpdateWindow(handle);
style = oldStyle;
}
}
return;
}
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE;
tvItem.stateMask = OS.TVIS_SELECTED;
tvItem.state = OS.TVIS_SELECTED;
tvItem.hItem = cast(HTREEITEM) item.handle;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
/**
* Selects all of the items in the receiver.
* <p>
* If the receiver is single-select, do nothing.
* </p>
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public void selectAll() {
checkWidget();
if ((style & SWT.SINGLE) !is 0)
return;
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE;
tvItem.state = OS.TVIS_SELECTED;
tvItem.stateMask = OS.TVIS_SELECTED;
auto oldProc = OS.GetWindowLongPtr(handle, OS.GWLP_WNDPROC);
OS.SetWindowLongPtr(handle, OS.GWLP_WNDPROC, cast(LONG_PTR) TreeProc);
if ((style & SWT.VIRTUAL) !is 0) {
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
select(hItem, &tvItem);
}
else {
for (int i = 0; i < items.length; i++) {
TreeItem item = items[i];
if (item !is null) {
tvItem.hItem = cast(HTREEITEM) item.handle;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
}
}
OS.SetWindowLongPtr(handle, OS.GWLP_WNDPROC, oldProc);
}
Event sendEraseItemEvent(TreeItem item, NMTTCUSTOMDRAW* nmcd, int column, RECT* cellRect) {
int nSavedDC = OS.SaveDC(nmcd.nmcd.hdc);
RECT* insetRect = toolTipInset(cellRect);
OS.SetWindowOrgEx(nmcd.nmcd.hdc, insetRect.left, insetRect.top, null);
GCData data = new GCData();
data.device = display;
data.foreground = OS.GetTextColor(nmcd.nmcd.hdc);
data.background = OS.GetBkColor(nmcd.nmcd.hdc);
data.font = item.getFont(column);
data.uiState = cast(int) /*64bit*/ OS.SendMessage(handle, OS.WM_QUERYUISTATE, 0, 0);
GC gc = GC.win32_new(nmcd.nmcd.hdc, data);
Event event = new Event();
event.item = item;
event.index = column;
event.gc = gc;
event.detail |= SWT.FOREGROUND;
event.x = cellRect.left;
event.y = cellRect.top;
event.width = cellRect.right - cellRect.left;
event.height = cellRect.bottom - cellRect.top;
//gc.setClipping (event.x, event.y, event.width, event.height);
sendEvent(SWT.EraseItem, event);
event.gc = null;
//int newTextClr = data.foreground;
gc.dispose();
OS.RestoreDC(nmcd.nmcd.hdc, nSavedDC);
return event;
}
Event sendMeasureItemEvent(TreeItem item, int index, HDC hDC) {
RECT* itemRect = item.getBounds(index, true, true, false, false, false, hDC);
int nSavedDC = OS.SaveDC(hDC);
GCData data = new GCData();
data.device = display;
data.font = item.getFont(index);
GC gc = GC.win32_new(hDC, data);
Event event = new Event();
event.item = item;
event.gc = gc;
event.index = index;
event.x = itemRect.left;
event.y = itemRect.top;
event.width = itemRect.right - itemRect.left;
event.height = itemRect.bottom - itemRect.top;
sendEvent(SWT.MeasureItem, event);
event.gc = null;
gc.dispose();
OS.RestoreDC(hDC, nSavedDC);
if (isDisposed() || item.isDisposed())
return null;
if (hwndHeader !is null) {
if (columnCount is 0) {
if (event.x + event.width > scrollWidth) {
setScrollWidth(scrollWidth = event.x + event.width);
}
}
}
if (event.height > getItemHeight())
setItemHeight(event.height);
return event;
}
Event sendPaintItemEvent(TreeItem item, NMTTCUSTOMDRAW* nmcd, int column, RECT* itemRect) {
int nSavedDC = OS.SaveDC(nmcd.nmcd.hdc);
RECT* insetRect = toolTipInset(itemRect);
OS.SetWindowOrgEx(nmcd.nmcd.hdc, insetRect.left, insetRect.top, null);
GCData data = new GCData();
data.device = display;
data.font = item.getFont(column);
data.foreground = OS.GetTextColor(nmcd.nmcd.hdc);
data.background = OS.GetBkColor(nmcd.nmcd.hdc);
data.uiState = cast(int) /*64bit*/ OS.SendMessage(handle, OS.WM_QUERYUISTATE, 0, 0);
GC gc = GC.win32_new(nmcd.nmcd.hdc, data);
Event event = new Event();
event.item = item;
event.index = column;
event.gc = gc;
event.detail |= SWT.FOREGROUND;
event.x = itemRect.left;
event.y = itemRect.top;
event.width = itemRect.right - itemRect.left;
event.height = itemRect.bottom - itemRect.top;
//gc.setClipping (cellRect.left, cellRect.top, cellWidth, cellHeight);
sendEvent(SWT.PaintItem, event);
event.gc = null;
gc.dispose();
OS.RestoreDC(nmcd.nmcd.hdc, nSavedDC);
return event;
}
override void setBackgroundImage(HBITMAP hBitmap) {
super.setBackgroundImage(hBitmap);
if (hBitmap !is null) {
/*
* Feature in Windows. If TVM_SETBKCOLOR is never
* used to set the background color of a tree, the
* background color of the lines and the plus/minus
* will be drawn using the default background color,
* not the HBRUSH returned from WM_CTLCOLOR. The fix
* is to set the background color to the default (when
* it is already the default) to make Windows use the
* brush.
*/
if (OS.SendMessage(handle, OS.TVM_GETBKCOLOR, 0, 0) is -1) {
OS.SendMessage(handle, OS.TVM_SETBKCOLOR, 0, -1);
}
_setBackgroundPixel(-1);
}
else {
Control control = findBackgroundControl();
if (control is null)
control = this;
if (control.backgroundImage is null) {
setBackgroundPixel(control.getBackgroundPixel());
}
}
/*
* Feature in Windows. When the tree has the style
* TVS_FULLROWSELECT, the background color for the
* entire row is filled when an item is painted,
* drawing on top of the background image. The fix
* is to clear TVS_FULLROWSELECT when a background
* image is set.
*/
updateFullSelection();
}
override void setBackgroundPixel(int pixel) {
Control control = findImageControl();
if (control !is null) {
setBackgroundImage(control.backgroundImage);
return;
}
/*
* Feature in Windows. When a tree is given a background color
* using TVM_SETBKCOLOR and the tree is disabled, Windows draws
* the tree using the background color rather than the disabled
* colors. This is different from the table which draws grayed.
* The fix is to set the default background color while the tree
* is disabled and restore it when enabled.
*/
if (OS.IsWindowEnabled(handle))
_setBackgroundPixel(pixel);
/*
* Feature in Windows. When the tree has the style
* TVS_FULLROWSELECT, the background color for the
* entire row is filled when an item is painted,
* drawing on top of the background image. The fix
* is to restore TVS_FULLROWSELECT when a background
* color is set.
*/
updateFullSelection();
}
override void setCursor() {
/*
* Bug in Windows. Under certain circumstances, when WM_SETCURSOR
* is sent from SendMessage(), Windows GP's in the window proc for
* the tree. The fix is to avoid calling the tree window proc and
* set the cursor for the tree outside of WM_SETCURSOR.
*
* NOTE: This code assumes that the default cursor for the tree
* is IDC_ARROW.
*/
Cursor cursor = findCursor();
auto hCursor = cursor is null ? OS.LoadCursor(null,
cast(TCHAR*) OS.IDC_ARROW) : cursor.handle;
OS.SetCursor(hCursor);
}
/**
* Sets the order that the items in the receiver should
* be displayed in to the given argument which is described
* in terms of the zero-relative ordering of when the items
* were added.
*
* @param order the new order to display the items
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
* @exception IllegalArgumentException <ul>
* <li>ERROR_INVALID_ARGUMENT - if the item order is not the same length as the number of items</li>
* </ul>
*
* @see Tree#getColumnOrder()
* @see TreeColumn#getMoveable()
* @see TreeColumn#setMoveable(bool)
* @see SWT#Move
*
* @since 3.2
*/
public void setColumnOrder(int[] order) {
checkWidget();
// SWT extension: allow null array
//if (order is null) error (SWT.ERROR_NULL_ARGUMENT);
if (columnCount is 0) {
if (order.length !is 0)
error(SWT.ERROR_INVALID_ARGUMENT);
return;
}
if (order.length !is columnCount)
error(SWT.ERROR_INVALID_ARGUMENT);
int[] oldOrder = new int[columnCount];
OS.SendMessage(hwndHeader, OS.HDM_GETORDERARRAY, columnCount, oldOrder.ptr);
bool reorder = false;
bool[] seen = new bool[columnCount];
for (int i = 0; i < order.length; i++) {
int index = order[i];
if (index < 0 || index >= columnCount)
error(SWT.ERROR_INVALID_RANGE);
if (seen[index])
error(SWT.ERROR_INVALID_ARGUMENT);
seen[index] = true;
if (index !is oldOrder[i])
reorder = true;
}
if (reorder) {
RECT[] oldRects = new RECT[columnCount];
for (int i = 0; i < columnCount; i++) {
//oldRects [i] = new RECT ();
OS.SendMessage(hwndHeader, OS.HDM_GETITEMRECT, i, &oldRects[i]);
}
OS.SendMessage(hwndHeader, OS.HDM_SETORDERARRAY, order.length, order.ptr);
OS.InvalidateRect(handle, null, true);
updateImageList();
TreeColumn[] newColumns = new TreeColumn[columnCount];
System.arraycopy(columns, 0, newColumns, 0, columnCount);
RECT newRect;
for (int i = 0; i < columnCount; i++) {
TreeColumn column = newColumns[i];
if (!column.isDisposed()) {
OS.SendMessage(hwndHeader, OS.HDM_GETITEMRECT, i, &newRect);
if (newRect.left !is oldRects[i].left) {
column.updateToolTip(i);
column.sendEvent(SWT.Move);
}
}
}
}
}
void setCheckboxImageList() {
if ((style & SWT.CHECK) is 0)
return;
int count = 5, flags = 0;
static if (OS.IsWinCE) {
flags |= OS.ILC_COLOR;
}
else {
if (OS.COMCTL32_MAJOR >= 6 && OS.IsAppThemed()) {
flags |= OS.ILC_COLOR32;
}
else {
auto hDC = OS.GetDC(handle);
int bits = OS.GetDeviceCaps(hDC, OS.BITSPIXEL);
int planes = OS.GetDeviceCaps(hDC, OS.PLANES);
OS.ReleaseDC(handle, hDC);
int depth = bits * planes;
switch (depth) {
case 4:
flags |= OS.ILC_COLOR4;
break;
case 8:
flags |= OS.ILC_COLOR8;
break;
case 16:
flags |= OS.ILC_COLOR16;
break;
case 24:
flags |= OS.ILC_COLOR24;
break;
case 32:
flags |= OS.ILC_COLOR32;
break;
default:
flags |= OS.ILC_COLOR;
break;
}
flags |= OS.ILC_MASK;
}
}
if ((style & SWT.RIGHT_TO_LEFT) !is 0)
flags |= OS.ILC_MIRROR;
auto height = OS.SendMessage(handle, OS.TVM_GETITEMHEIGHT, 0, 0), width = height;
auto hStateList = OS.ImageList_Create(cast(int) /*64bit*/ width,
cast(int) /*64bit*/ height, flags, count, count);
auto hDC = OS.GetDC(handle);
auto memDC = OS.CreateCompatibleDC(hDC);
auto hBitmap = OS.CreateCompatibleBitmap(hDC, cast(int) /*64bit*/ width * count,
cast(int) /*64bit*/ height);
auto hOldBitmap = OS.SelectObject(memDC, hBitmap);
RECT rect;
OS.SetRect(&rect, 0, 0, cast(int) /*64bit*/ width * count, cast(int) /*64bit*/ height);
/*
* NOTE: DrawFrameControl() draws a black and white
* mask when not drawing a push button. In order to
* make the box surrounding the check mark transparent,
* fill it with a color that is neither black or white.
*/
int clrBackground = 0;
if (OS.COMCTL32_MAJOR >= 6 && OS.IsAppThemed()) {
Control control = findBackgroundControl();
if (control is null)
control = this;
clrBackground = control.getBackgroundPixel();
}
else {
clrBackground = 0x020000FF;
if ((clrBackground & 0xFFFFFF) is OS.GetSysColor(OS.COLOR_WINDOW)) {
clrBackground = 0x0200FF00;
}
}
auto hBrush = OS.CreateSolidBrush(clrBackground);
OS.FillRect(memDC, &rect, hBrush);
OS.DeleteObject(hBrush);
auto oldFont = OS.SelectObject(hDC, defaultFont());
TEXTMETRIC tm;
OS.GetTextMetrics(hDC, &tm);
OS.SelectObject(hDC, oldFont);
int itemWidth = cast(int) /*64bit*/ Math.min(tm.tmHeight, width);
int itemHeight = cast(int) /*64bit*/ Math.min(tm.tmHeight, height);
int left = cast(int) /*64bit*/ (width - itemWidth) / 2,
top = cast(int) /*64bit*/ (height - itemHeight) / 2 + 1;
OS.SetRect(&rect, left + cast(int) /*64bit*/ width, top,
left + cast(int) /*64bit*/ width + itemWidth, top + itemHeight);
if (OS.COMCTL32_MAJOR >= 6 && OS.IsAppThemed()) {
auto hTheme = display.hButtonTheme();
OS.DrawThemeBackground(hTheme, memDC, OS.BP_CHECKBOX,
OS.CBS_UNCHECKEDNORMAL, &rect, null);
rect.left += width;
rect.right += width;
OS.DrawThemeBackground(hTheme, memDC, OS.BP_CHECKBOX,
OS.CBS_CHECKEDNORMAL, &rect, null);
rect.left += width;
rect.right += width;
OS.DrawThemeBackground(hTheme, memDC, OS.BP_CHECKBOX,
OS.CBS_UNCHECKEDNORMAL, &rect, null);
rect.left += width;
rect.right += width;
OS.DrawThemeBackground(hTheme, memDC, OS.BP_CHECKBOX,
OS.CBS_MIXEDNORMAL, &rect, null);
}
else {
OS.DrawFrameControl(memDC, &rect, OS.DFC_BUTTON, OS.DFCS_BUTTONCHECK | OS.DFCS_FLAT);
rect.left += width;
rect.right += width;
OS.DrawFrameControl(memDC, &rect, OS.DFC_BUTTON,
OS.DFCS_BUTTONCHECK | OS.DFCS_CHECKED | OS.DFCS_FLAT);
rect.left += width;
rect.right += width;
OS.DrawFrameControl(memDC, &rect, OS.DFC_BUTTON,
OS.DFCS_BUTTONCHECK | OS.DFCS_INACTIVE | OS.DFCS_FLAT);
rect.left += width;
rect.right += width;
OS.DrawFrameControl(memDC, &rect, OS.DFC_BUTTON,
OS.DFCS_BUTTONCHECK | OS.DFCS_CHECKED | OS.DFCS_INACTIVE | OS.DFCS_FLAT);
}
OS.SelectObject(memDC, hOldBitmap);
OS.DeleteDC(memDC);
OS.ReleaseDC(handle, hDC);
if (OS.COMCTL32_MAJOR >= 6 && OS.IsAppThemed()) {
OS.ImageList_Add(hStateList, hBitmap, null);
}
else {
OS.ImageList_AddMasked(hStateList, hBitmap, clrBackground);
}
OS.DeleteObject(hBitmap);
auto hOldStateList = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETIMAGELIST, OS.TVSIL_STATE, 0);
OS.SendMessage(handle, OS.TVM_SETIMAGELIST, OS.TVSIL_STATE, hStateList);
if (hOldStateList !is null)
OS.ImageList_Destroy(hOldStateList);
}
override public void setFont(Font font) {
checkWidget();
super.setFont(font);
if ((style & SWT.CHECK) !is 0)
setCheckboxImageList();
}
override void setForegroundPixel(int pixel) {
/*
* Bug in Windows. When the tree is using the explorer
* theme, it does not use COLOR_WINDOW_TEXT for the
* foreground. When TVM_SETTEXTCOLOR is called with -1,
* it resets the color to black, not COLOR_WINDOW_TEXT.
* The fix is to explicitly set the color.
*/
if (explorerTheme) {
if (pixel is -1)
pixel = defaultForeground();
}
OS.SendMessage(handle, OS.TVM_SETTEXTCOLOR, 0, pixel);
}
/**
* Marks the receiver's header as visible if the argument is <code>true</code>,
* and marks it invisible otherwise.
* <p>
* If one of the receiver's ancestors is not visible or some
* other condition makes the receiver not visible, marking
* it visible may not actually cause it to be displayed.
* </p>
*
* @param show the new visibility state
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.1
*/
public void setHeaderVisible(bool show) {
checkWidget();
if (hwndHeader is null) {
if (!show)
return;
createParent();
}
int bits = OS.GetWindowLong(hwndHeader, OS.GWL_STYLE);
if (show) {
if ((bits & OS.HDS_HIDDEN) is 0)
return;
bits &= ~OS.HDS_HIDDEN;
OS.SetWindowLong(hwndHeader, OS.GWL_STYLE, bits);
OS.ShowWindow(hwndHeader, OS.SW_SHOW);
}
else {
if ((bits & OS.HDS_HIDDEN) !is 0)
return;
bits |= OS.HDS_HIDDEN;
OS.SetWindowLong(hwndHeader, OS.GWL_STYLE, bits);
OS.ShowWindow(hwndHeader, OS.SW_HIDE);
}
setScrollWidth();
updateHeaderToolTips();
updateScrollBar();
}
override public void setRedraw(bool redraw) {
checkWidget();
/*
* Feature in Windows. When WM_SETREDRAW is used to
* turn off redraw, the scroll bars are updated when
* items are added and removed. The fix is to call
* the default window proc to stop all drawing.
*
* Bug in Windows. For some reason, when WM_SETREDRAW
* is used to turn redraw on for a tree and the tree
* contains no items, the last item in the tree does
* not redraw properly. If the tree has only one item,
* that item is not drawn. If another window is dragged
* on top of the item, parts of the item are redrawn
* and erased at random. The fix is to ensure that this
* case doesn't happen by inserting and deleting an item
* when redraw is turned on and there are no items in
* the tree.
*/
HANDLE hItem;
if (redraw) {
if (drawCount is 1) {
auto count = OS.SendMessage(handle, OS.TVM_GETCOUNT, 0, 0);
if (count is 0) {
TVINSERTSTRUCT tvInsert;
tvInsert.hInsertAfter = cast(HTREEITEM) OS.TVI_FIRST;
hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_INSERTITEM, 0, &tvInsert);
}
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 1, 0);
updateScrollBar();
}
}
super.setRedraw(redraw);
if (!redraw) {
if (drawCount is 1)
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 0, 0);
}
if (hItem !is null) {
ignoreShrink = true;
OS.SendMessage(handle, OS.TVM_DELETEITEM, 0, hItem);
ignoreShrink = false;
}
}
void setScrollWidth() {
if (hwndHeader is null || hwndParent is null)
return;
int width = 0;
HDITEM hdItem;
for (int i = 0; i < columnCount; i++) {
hdItem.mask = OS.HDI_WIDTH;
OS.SendMessage(hwndHeader, OS.HDM_GETITEM, i, &hdItem);
width += hdItem.cxy;
}
setScrollWidth(Math.max(scrollWidth, width));
}
void setScrollWidth(int width) {
if (hwndHeader is null || hwndParent is null)
return;
//TEMPORARY CODE
//scrollWidth = width;
int left = 0;
RECT rect;
SCROLLINFO info;
info.cbSize = SCROLLINFO.sizeof;
info.fMask = OS.SIF_RANGE | OS.SIF_PAGE;
if (columnCount is 0 && width is 0) {
OS.GetScrollInfo(hwndParent, OS.SB_HORZ, &info);
info.nPage = info.nMax + 1;
OS.SetScrollInfo(hwndParent, OS.SB_HORZ, &info, true);
OS.GetScrollInfo(hwndParent, OS.SB_VERT, &info);
info.nPage = info.nMax + 1;
OS.SetScrollInfo(hwndParent, OS.SB_VERT, &info, true);
}
else {
if ((style & SWT.H_SCROLL) !is 0) {
OS.GetClientRect(hwndParent, &rect);
OS.GetScrollInfo(hwndParent, OS.SB_HORZ, &info);
info.nMax = width;
info.nPage = rect.right - rect.left + 1;
OS.SetScrollInfo(hwndParent, OS.SB_HORZ, &info, true);
info.fMask = OS.SIF_POS;
OS.GetScrollInfo(hwndParent, OS.SB_HORZ, &info);
left = info.nPos;
}
}
if (horizontalBar !is null) {
horizontalBar.setIncrement(INCREMENT);
horizontalBar.setPageIncrement(info.nPage);
}
OS.GetClientRect(hwndParent, &rect);
HDLAYOUT playout;
RECT layoutrect = rect;
playout.prc = &layoutrect;
WINDOWPOS pos;
playout.pwpos = &pos;
OS.SendMessage(hwndHeader, OS.HDM_LAYOUT, 0, &playout);
SetWindowPos(hwndHeader, cast(HWND) OS.HWND_TOP, pos.x - left, pos.y,
pos.cx + left, pos.cy, OS.SWP_NOACTIVATE);
int bits = OS.GetWindowLong(handle, OS.GWL_EXSTYLE);
int b = (bits & OS.WS_EX_CLIENTEDGE) !is 0 ? OS.GetSystemMetrics(OS.SM_CXEDGE) : 0;
int w = pos.cx + (columnCount is 0 && width is 0 ? 0 : OS.GetSystemMetrics(OS.SM_CXVSCROLL));
int h = rect.bottom - rect.top - pos.cy;
bool oldIgnore = ignoreResize;
ignoreResize = true;
SetWindowPos(handle, null, pos.x - left - b, pos.y + pos.cy - b,
w + left + b * 2, h + b * 2, OS.SWP_NOACTIVATE | OS.SWP_NOZORDER);
ignoreResize = oldIgnore;
}
void setSelection(HANDLE hItem, TVITEM* tvItem, TreeItem[] selection) {
while (hItem !is null) {
int index = 0;
while (index < selection.length) {
TreeItem item = selection[index];
if (item !is null && item.handle is hItem)
break;
index++;
}
tvItem.hItem = cast(HTREEITEM) hItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
if ((tvItem.state & OS.TVIS_SELECTED) !is 0) {
if (index is selection.length) {
tvItem.state = 0;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
}
else {
if (index !is selection.length) {
tvItem.state = OS.TVIS_SELECTED;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
}
auto hFirstItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hItem);
setSelection(hFirstItem, tvItem, selection);
hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem);
}
}
/**
* Sets the receiver's selection to the given item.
* The current selection is cleared before the new item is selected.
* <p>
* If the item is not in the receiver, then it is ignored.
* </p>
*
* @param item the item to select
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the item is null</li>
* <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.2
*/
public void setSelection(TreeItem item) {
checkWidget();
if (item is null)
error(SWT.ERROR_NULL_ARGUMENT);
setSelection([item]);
}
/**
* Sets the receiver's selection to be the given array of items.
* The current selection is cleared before the new items are selected.
* <p>
* Items that are not in the receiver are ignored.
* If the receiver is single-select and multiple items are specified,
* then all items are ignored.
* </p>
*
* @param items the array of items
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_INVALID_ARGUMENT - if one of the items has been disposed</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see Tree#deselectAll()
*/
public void setSelection(TreeItem[] items) {
checkWidget();
// SWT extension: allow null array
//if (items is null) error (SWT.ERROR_NULL_ARGUMENT);
int length = cast(int) /*64bit*/ items.length;
if (length is 0 || ((style & SWT.SINGLE) !is 0 && length > 1)) {
deselectAll();
return;
}
/* Select/deselect the first item */
TreeItem item = items[0];
if (item !is null) {
if (item.isDisposed())
error(SWT.ERROR_INVALID_ARGUMENT);
HANDLE hOldItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
HANDLE hNewItem = hAnchor = item.handle;
/*
* Bug in Windows. When TVM_SELECTITEM is used to select and
* scroll an item to be visible and the client area of the tree
* is smaller that the size of one item, TVM_SELECTITEM makes
* the next item in the tree visible by making it the top item
* instead of making the desired item visible. The fix is to
* detect the case when the client area is too small and make
* the desired visible item be the top item in the tree.
*
* Note that TVM_SELECTITEM when called with TVGN_FIRSTVISIBLE
* also requires the work around for scrolling.
*/
bool fixScroll = checkScroll(hNewItem);
if (fixScroll) {
OS.SendMessage(handle, OS.WM_SETREDRAW, 1, 0);
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 0, 0);
}
ignoreSelect = true;
OS.SendMessage(handle, OS.TVM_SELECTITEM, OS.TVGN_CARET, hNewItem);
ignoreSelect = false;
if (OS.SendMessage(handle, OS.TVM_GETVISIBLECOUNT, 0, 0) is 0) {
OS.SendMessage(handle, OS.TVM_SELECTITEM, OS.TVGN_FIRSTVISIBLE, hNewItem);
auto hParent = OS.SendMessage(handle, OS.TVM_GETNEXTITEM,
OS.TVGN_PARENT, hNewItem);
if (hParent is 0)
OS.SendMessage(handle, OS.WM_HSCROLL, OS.SB_TOP, 0);
}
if (fixScroll) {
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 1, 0);
OS.SendMessage(handle, OS.WM_SETREDRAW, 0, 0);
}
/*
* Feature in Windows. When the old and new focused item
* are the same, Windows does not check to make sure that
* the item is actually selected, not just focused. The
* fix is to force the item to draw selected by setting
* the state mask, and to ensure that it is visible.
*/
if (hOldItem is hNewItem) {
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE;
tvItem.state = OS.TVIS_SELECTED;
tvItem.stateMask = OS.TVIS_SELECTED;
tvItem.hItem = cast(HTREEITEM) hNewItem;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
showItem(hNewItem);
}
}
if ((style & SWT.SINGLE) !is 0)
return;
/* Select/deselect the rest of the items */
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE;
tvItem.stateMask = OS.TVIS_SELECTED;
auto oldProc = OS.GetWindowLongPtr(handle, OS.GWLP_WNDPROC);
OS.SetWindowLongPtr(handle, OS.GWLP_WNDPROC, cast(LONG_PTR) TreeProc);
if ((style & SWT.VIRTUAL) !is 0) {
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
setSelection(hItem, &tvItem, items);
}
else {
for (int i = 0; i < this.items.length; i++) {
item = this.items[i];
if (item !is null) {
int index = 0;
while (index < length) {
if (items[index] is item)
break;
index++;
}
tvItem.hItem = cast(HTREEITEM) item.handle;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
if ((tvItem.state & OS.TVIS_SELECTED) !is 0) {
if (index is length) {
tvItem.state = 0;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
}
else {
if (index !is length) {
tvItem.state = OS.TVIS_SELECTED;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
}
}
}
}
OS.SetWindowLongPtr(handle, OS.GWLP_WNDPROC, oldProc);
}
/**
* Sets the column used by the sort indicator for the receiver. A null
* value will clear the sort indicator. The current sort column is cleared
* before the new column is set.
*
* @param column the column used by the sort indicator or <code>null</code>
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_INVALID_ARGUMENT - if the column is disposed</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.2
*/
public void setSortColumn(TreeColumn column) {
checkWidget();
if (column !is null && column.isDisposed())
error(SWT.ERROR_INVALID_ARGUMENT);
if (sortColumn !is null && !sortColumn.isDisposed()) {
sortColumn.setSortDirection(SWT.NONE);
}
sortColumn = column;
if (sortColumn !is null && sortDirection !is SWT.NONE) {
sortColumn.setSortDirection(sortDirection);
}
}
/**
* Sets the direction of the sort indicator for the receiver. The value
* can be one of <code>UP</code>, <code>DOWN</code> or <code>NONE</code>.
*
* @param direction the direction of the sort indicator
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.2
*/
public void setSortDirection(int direction) {
checkWidget();
if ((direction & (SWT.UP | SWT.DOWN)) is 0 && direction !is SWT.NONE)
return;
sortDirection = direction;
if (sortColumn !is null && !sortColumn.isDisposed()) {
sortColumn.setSortDirection(direction);
}
}
/**
* Sets the item which is currently at the top of the receiver.
* This item can change when items are expanded, collapsed, scrolled
* or new items are added or removed.
*
* @param item the item to be shown
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the item is null</li>
* <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see Tree#getTopItem()
*
* @since 2.1
*/
public void setTopItem(TreeItem item) {
checkWidget();
if (item is null)
SWT.error(SWT.ERROR_NULL_ARGUMENT);
if (item.isDisposed())
SWT.error(SWT.ERROR_INVALID_ARGUMENT);
HANDLE hItem = item.handle;
auto hTopItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM,
OS.TVGN_FIRSTVISIBLE, 0);
if (hItem is hTopItem)
return;
bool fixScroll = checkScroll(hItem), redraw = false;
if (fixScroll) {
OS.SendMessage(handle, OS.WM_SETREDRAW, 1, 0);
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 0, 0);
}
else {
redraw = drawCount is 0 && OS.IsWindowVisible(handle);
if (redraw)
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 0, 0);
}
OS.SendMessage(handle, OS.TVM_SELECTITEM, OS.TVGN_FIRSTVISIBLE, hItem);
auto hParent = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM,
OS.TVGN_PARENT, hItem);
if (hParent is null)
OS.SendMessage(handle, OS.WM_HSCROLL, OS.SB_TOP, 0);
if (fixScroll) {
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 1, 0);
OS.SendMessage(handle, OS.WM_SETREDRAW, 0, 0);
}
else {
if (redraw) {
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 1, 0);
OS.InvalidateRect(handle, null, true);
}
}
updateScrollBar();
}
void showItem(HANDLE hItem) {
/*
* Bug in Windows. When TVM_ENSUREVISIBLE is used to ensure
* that an item is visible and the client area of the tree is
* smaller that the size of one item, TVM_ENSUREVISIBLE makes
* the next item in the tree visible by making it the top item
* instead of making the desired item visible. The fix is to
* detect the case when the client area is too small and make
* the desired visible item be the top item in the tree.
*/
if (OS.SendMessage(handle, OS.TVM_GETVISIBLECOUNT, 0, 0) is 0) {
bool fixScroll = checkScroll(hItem);
if (fixScroll) {
OS.SendMessage(handle, OS.WM_SETREDRAW, 1, 0);
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 0, 0);
}
OS.SendMessage(handle, OS.TVM_SELECTITEM, OS.TVGN_FIRSTVISIBLE, hItem);
/* This code is intentionally commented */
//auto hParent = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_PARENT, hItem);
//if (hParent is 0) OS.SendMessage (handle, OS.WM_HSCROLL, OS.SB_TOP, 0);
OS.SendMessage(handle, OS.WM_HSCROLL, OS.SB_TOP, 0);
if (fixScroll) {
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 1, 0);
OS.SendMessage(handle, OS.WM_SETREDRAW, 0, 0);
}
}
else {
bool scroll = true;
RECT itemRect;
if (OS.TreeView_GetItemRect(handle, cast(HTREEITEM) hItem, &itemRect, true)) {
forceResize();
RECT rect;
OS.GetClientRect(handle, &rect);
POINT pt;
pt.x = itemRect.left;
pt.y = itemRect.top;
if (OS.PtInRect(&rect, pt)) {
pt.y = itemRect.bottom;
if (OS.PtInRect(&rect, pt))
scroll = false;
}
}
if (scroll) {
bool fixScroll = checkScroll(hItem);
if (fixScroll) {
OS.SendMessage(handle, OS.WM_SETREDRAW, 1, 0);
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 0, 0);
}
OS.SendMessage(handle, OS.TVM_ENSUREVISIBLE, 0, hItem);
if (fixScroll) {
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 1, 0);
OS.SendMessage(handle, OS.WM_SETREDRAW, 0, 0);
}
}
}
if (hwndParent !is null) {
RECT itemRect;
if (OS.TreeView_GetItemRect(handle, cast(HTREEITEM) hItem, &itemRect, true)) {
forceResize();
RECT rect;
OS.GetClientRect(hwndParent, &rect);
OS.MapWindowPoints(hwndParent, handle, cast(POINT*)&rect, 2);
POINT pt;
pt.x = itemRect.left;
pt.y = itemRect.top;
if (!OS.PtInRect(&rect, pt)) {
pt.y = itemRect.bottom;
if (!OS.PtInRect(&rect, pt)) {
SCROLLINFO info;
info.cbSize = SCROLLINFO.sizeof;
info.fMask = OS.SIF_POS;
info.nPos = Math.max(0, pt.x - Tree.INSET / 2);
OS.SetScrollInfo(hwndParent, OS.SB_HORZ, &info, true);
setScrollWidth();
}
}
}
}
updateScrollBar();
}
/**
* Shows the column. If the column is already showing in the receiver,
* this method simply returns. Otherwise, the columns are scrolled until
* the column is visible.
*
* @param column the column to be shown
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the item is null</li>
* <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @since 3.1
*/
public void showColumn(TreeColumn column) {
checkWidget();
if (column is null)
error(SWT.ERROR_NULL_ARGUMENT);
if (column.isDisposed())
error(SWT.ERROR_INVALID_ARGUMENT);
if (column.parent !is this)
return;
int index = indexOf(column);
if (index is -1)
return;
if (0 <= index && index < columnCount) {
forceResize();
RECT rect;
OS.GetClientRect(hwndParent, &rect);
OS.MapWindowPoints(hwndParent, handle, cast(POINT*)&rect, 2);
RECT headerRect;
OS.SendMessage(hwndHeader, OS.HDM_GETITEMRECT, index, &headerRect);
bool scroll = headerRect.left < rect.left;
if (!scroll) {
int width = Math.min(rect.right - rect.left, headerRect.right - headerRect.left);
scroll = headerRect.left + width > rect.right;
}
if (scroll) {
SCROLLINFO info;
info.cbSize = SCROLLINFO.sizeof;
info.fMask = OS.SIF_POS;
info.nPos = Math.max(0, headerRect.left - Tree.INSET / 2);
OS.SetScrollInfo(hwndParent, OS.SB_HORZ, &info, true);
setScrollWidth();
}
}
}
/**
* Shows the item. If the item is already showing in the receiver,
* this method simply returns. Otherwise, the items are scrolled
* and expanded until the item is visible.
*
* @param item the item to be shown
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the item is null</li>
* <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see Tree#showSelection()
*/
public void showItem(TreeItem item) {
checkWidget();
if (item is null)
error(SWT.ERROR_NULL_ARGUMENT);
if (item.isDisposed())
error(SWT.ERROR_INVALID_ARGUMENT);
showItem(item.handle);
}
/**
* Shows the selection. If the selection is already showing in the receiver,
* this method simply returns. Otherwise, the items are scrolled until
* the selection is visible.
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see Tree#showItem(TreeItem)
*/
public void showSelection() {
checkWidget();
HANDLE hItem;
if ((style & SWT.SINGLE) !is 0) {
hItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
if (hItem is null)
return;
.LRESULT state = 0;
static if (OS.IsWinCE) {
TVITEM tvItem;
tvItem.hItem = hItem;
tvItem.mask = OS.TVIF_STATE;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
state = tvItem.state;
}
else {
state = OS.SendMessage(handle, OS.TVM_GETITEMSTATE, hItem, OS.TVIS_SELECTED);
}
if ((state & OS.TVIS_SELECTED) is 0)
return;
}
else {
LONG_PTR oldProc = OS.GetWindowLongPtr(handle, OS.GWLP_WNDPROC);
OS.SetWindowLongPtr(handle, OS.GWLP_WNDPROC, cast(LONG_PTR) TreeProc);
TVITEM tvItem_;
TVITEM* tvItem;
static if (OS.IsWinCE) {
tvItem = &tvItem_;
tvItem.mask = OS.TVIF_STATE;
}
if ((style & SWT.VIRTUAL) !is 0) {
auto hRoot = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
hItem = getNextSelection(hRoot, tvItem);
}
else {
//FIXME - this code expands first selected item it finds
int index = 0;
while (index < items.length) {
TreeItem item = items[index];
if (item !is null) {
.LRESULT state = 0;
static if (OS.IsWinCE) {
tvItem.hItem = item.handle;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, tvItem);
state = tvItem.state;
}
else {
state = OS.SendMessage(handle, OS.TVM_GETITEMSTATE,
item.handle, OS.TVIS_SELECTED);
}
if ((state & OS.TVIS_SELECTED) !is 0) {
hItem = item.handle;
break;
}
}
index++;
}
}
OS.SetWindowLongPtr(handle, OS.GWLP_WNDPROC, oldProc);
}
if (hItem !is null)
showItem(hItem);
}
/*public*/
void sort() {
checkWidget();
if ((style & SWT.VIRTUAL) !is 0)
return;
sort(cast(HTREEITEM) OS.TVI_ROOT, false);
}
void sort(HANDLE hParent, bool all) {
auto itemCount = OS.SendMessage(handle, OS.TVM_GETCOUNT, 0, 0);
if (itemCount is 0 || itemCount is 1)
return;
hFirstIndexOf = hLastIndexOf = null;
itemCount = -1;
if (sortDirection is SWT.UP || sortDirection is SWT.NONE) {
OS.SendMessage(handle, OS.TVM_SORTCHILDREN, all ? 1 : 0, hParent);
}
else {
//Callback compareCallback = new Callback (this, "CompareFunc", 3);
//int lpfnCompare = compareCallback.getAddress ();
sThis = this;
TVSORTCB psort;
psort.hParent = cast(HTREEITEM) hParent;
psort.lpfnCompare = &CompareFunc;
psort.lParam = sortColumn is null ? 0 : indexOf(sortColumn);
OS.SendMessage(handle, OS.TVM_SORTCHILDRENCB, all ? 1 : 0, &psort);
sThis = null;
//compareCallback.dispose ();
}
}
override void subclass() {
super.subclass();
if (hwndHeader !is null) {
OS.SetWindowLongPtr(hwndHeader, OS.GWLP_WNDPROC, display.windowProc);
}
}
RECT* toolTipInset(RECT* rect) {
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0)) {
RECT* insetRect = new RECT();
OS.SetRect(insetRect, rect.left - 1, rect.top - 1, rect.right + 1, rect.bottom + 1);
return insetRect;
}
return rect;
}
RECT* toolTipRect(RECT* rect) {
RECT* toolRect = new RECT();
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0)) {
OS.SetRect(toolRect, rect.left - 1, rect.top - 1, rect.right + 1, rect.bottom + 1);
}
else {
OS.SetRect(toolRect, rect.left, rect.top, rect.right, rect.bottom);
int dwStyle = OS.GetWindowLong(itemToolTipHandle, OS.GWL_STYLE);
int dwExStyle = OS.GetWindowLong(itemToolTipHandle, OS.GWL_EXSTYLE);
OS.AdjustWindowRectEx(toolRect, dwStyle, false, dwExStyle);
}
return toolRect;
}
override String toolTipText(NMTTDISPINFO* hdr) {
auto hwndToolTip = cast(HWND) OS.SendMessage(handle, OS.TVM_GETTOOLTIPS, 0, 0);
if (hwndToolTip is hdr.hdr.hwndFrom && toolTipText_ !is null)
return ""; //$NON-NLS-1$
if (headerToolTipHandle is hdr.hdr.hwndFrom) {
for (int i = 0; i < columnCount; i++) {
TreeColumn column = columns[i];
if (column.id is hdr.hdr.idFrom)
return column.toolTipText;
}
return super.toolTipText(hdr);
}
if (itemToolTipHandle is hdr.hdr.hwndFrom) {
if (toolTipText_ !is null)
return "";
int pos = OS.GetMessagePos();
POINT pt;
OS.POINTSTOPOINT(pt, pos);
OS.ScreenToClient(handle, &pt);
int index;
TreeItem item;
RECT* cellRect, itemRect;
if (findCell(pt.x, pt.y, item, index, cellRect, itemRect)) {
String text = null;
if (index is 0) {
text = item.text;
}
else {
String[] strings = item.strings;
if (strings !is null)
text = strings[index];
}
//TEMPORARY CODE
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0)) {
if (isCustomToolTip())
text = " ";
}
if (text !is null)
return text;
}
}
return super.toolTipText(hdr);
}
override HWND topHandle() {
return hwndParent !is null ? hwndParent : handle;
}
void updateFullSelection() {
if ((style & SWT.FULL_SELECTION) !is 0) {
int oldBits = OS.GetWindowLong(handle, OS.GWL_STYLE), newBits = oldBits;
if ((newBits & OS.TVS_FULLROWSELECT) !is 0) {
if (!OS.IsWindowEnabled(handle) || findImageControl() !is null) {
if (!explorerTheme)
newBits &= ~OS.TVS_FULLROWSELECT;
}
}
else {
if (OS.IsWindowEnabled(handle) && findImageControl() is null) {
if (!hooks(SWT.EraseItem) && !hooks(SWT.PaintItem)) {
newBits |= OS.TVS_FULLROWSELECT;
}
}
}
if (newBits !is oldBits) {
OS.SetWindowLong(handle, OS.GWL_STYLE, newBits);
OS.InvalidateRect(handle, null, true);
}
}
}
void updateHeaderToolTips() {
if (headerToolTipHandle is null)
return;
RECT rect;
TOOLINFO lpti;
lpti.cbSize = OS.TOOLINFO_sizeof;
lpti.uFlags = OS.TTF_SUBCLASS;
lpti.hwnd = hwndHeader;
lpti.lpszText = OS.LPSTR_TEXTCALLBACK;
for (int i = 0; i < columnCount; i++) {
TreeColumn column = columns[i];
if (OS.SendMessage(hwndHeader, OS.HDM_GETITEMRECT, i, &rect) !is 0) {
lpti.uId = column.id = display.nextToolTipId++;
lpti.rect.left = rect.left;
lpti.rect.top = rect.top;
lpti.rect.right = rect.right;
lpti.rect.bottom = rect.bottom;
OS.SendMessage(headerToolTipHandle, OS.TTM_ADDTOOL, 0, &lpti);
}
}
}
void updateImageList() {
if (imageList is null)
return;
if (hwndHeader is null)
return;
auto i = 0, index = OS.SendMessage(hwndHeader, OS.HDM_ORDERTOINDEX, 0, 0);
while (i < items.length) {
TreeItem item = items[i];
if (item !is null) {
Image image = null;
if (index is 0) {
image = item.image;
}
else {
Image[] images = item.images;
if (images !is null)
image = images[index];
}
if (image !is null)
break;
}
i++;
}
/*
* Feature in Windows. When setting the same image list multiple
* times, Windows does work making this operation slow. The fix
* is to test for the same image list before setting the new one.
*/
HBITMAP hImageList = i is items.length ? null : imageList.getHandle();
HANDLE hOldImageList = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETIMAGELIST, OS.TVSIL_NORMAL, 0);
if (hImageList !is hOldImageList) {
OS.SendMessage(handle, OS.TVM_SETIMAGELIST, OS.TVSIL_NORMAL, hImageList);
}
}
override void updateImages() {
if (sortColumn !is null && !sortColumn.isDisposed()) {
if (OS.COMCTL32_MAJOR < 6) {
switch (sortDirection) {
case SWT.UP:
case SWT.DOWN:
sortColumn.setImage(display.getSortImage(sortDirection), true, true);
break;
default:
}
}
}
}
void updateScrollBar() {
if (hwndParent !is null) {
if (columnCount !is 0 || scrollWidth !is 0) {
SCROLLINFO info;
info.cbSize = SCROLLINFO.sizeof;
info.fMask = OS.SIF_ALL;
auto itemCount = OS.SendMessage(handle, OS.TVM_GETCOUNT, 0, 0);
if (itemCount is 0) {
OS.GetScrollInfo(hwndParent, OS.SB_VERT, &info);
info.nPage = info.nMax + 1;
OS.SetScrollInfo(hwndParent, OS.SB_VERT, &info, true);
}
else {
OS.GetScrollInfo(handle, OS.SB_VERT, &info);
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(4, 10)) {
if (info.nPage is 0) {
SCROLLBARINFO psbi;
psbi.cbSize = SCROLLBARINFO.sizeof;
OS.GetScrollBarInfo(handle, OS.OBJID_VSCROLL, &psbi);
if ((psbi.rgstate[0] & OS.STATE_SYSTEM_INVISIBLE) !is 0) {
info.nPage = info.nMax + 1;
}
}
}
OS.SetScrollInfo(hwndParent, OS.SB_VERT, &info, true);
}
}
}
}
override void unsubclass() {
super.unsubclass();
if (hwndHeader !is null) {
OS.SetWindowLongPtr(hwndHeader, OS.GWLP_WNDPROC, cast(LONG_PTR) HeaderProc);
}
}
override int widgetStyle() {
int bits = super.widgetStyle() | OS.TVS_SHOWSELALWAYS
| OS.TVS_LINESATROOT | OS.TVS_HASBUTTONS | OS.TVS_NONEVENHEIGHT;
if (EXPLORER_THEME && !OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6,
0) && OS.IsAppThemed()) {
bits |= OS.TVS_TRACKSELECT;
if ((style & SWT.FULL_SELECTION) !is 0)
bits |= OS.TVS_FULLROWSELECT;
}
else {
if ((style & SWT.FULL_SELECTION) !is 0) {
bits |= OS.TVS_FULLROWSELECT;
}
else {
bits |= OS.TVS_HASLINES;
}
}
if ((style & (SWT.H_SCROLL | SWT.V_SCROLL)) is 0) {
bits &= ~(OS.WS_HSCROLL | OS.WS_VSCROLL);
bits |= OS.TVS_NOSCROLL;
}
else {
if ((style & SWT.H_SCROLL) is 0) {
bits &= ~OS.WS_HSCROLL;
bits |= OS.TVS_NOHSCROLL;
}
}
// bits |= OS.TVS_NOTOOLTIPS | OS.TVS_DISABLEDRAGDROP;
return bits | OS.TVS_DISABLEDRAGDROP;
}
override String windowClass() {
return TCHARsToStr(TreeClass);
}
override ptrdiff_t windowProc() {
return cast(ptrdiff_t) TreeProc;
}
override.LRESULT windowProc(HWND hwnd, int msg, WPARAM wParam, LPARAM lParam) {
if (hwndHeader !is null && hwnd is hwndHeader) {
switch (msg) {
/* This code is intentionally commented */
// case OS.WM_CONTEXTMENU: {
// LRESULT result = wmContextMenu (hwnd, wParam, lParam);
// if (result !is null) return result.value;
// break;
// }
case OS.WM_CAPTURECHANGED: {
/*
* Bug in Windows. When the capture changes during a
* header drag, Windows does not redraw the header item
* such that the header remains pressed. For example,
* when focus is assigned to a push button, the mouse is
* pressed (but not released), then the SPACE key is
* pressed to activate the button, the capture changes,
* the header not notified and NM_RELEASEDCAPTURE is not
* sent. The fix is to redraw the header when the capture
* changes to another control.
*
* This does not happen on XP.
*/
if (OS.COMCTL32_MAJOR < 6) {
if (lParam !is 0 && cast(HANDLE) lParam !is hwndHeader) {
OS.InvalidateRect(hwndHeader, null, true);
}
}
break;
}
case OS.WM_MOUSELEAVE: {
/*
* Bug in Windows. On XP, when a tooltip is hidden
* due to a time out or mouse press, the tooltip
* remains active although no longer visible and
* won't show again until another tooltip becomes
* active. The fix is to reset the tooltip bounds.
*/
if (OS.COMCTL32_MAJOR >= 6)
updateHeaderToolTips();
updateHeaderToolTips();
break;
}
case OS.WM_NOTIFY: {
NMHDR* hdr = cast(NMHDR*) lParam;
//OS.MoveMemory (hdr, lParam, NMHDR.sizeof);
switch (hdr.code) {
case OS.TTN_SHOW:
case OS.TTN_POP:
case OS.TTN_GETDISPINFOA:
case OS.TTN_GETDISPINFOW:
return OS.SendMessage(handle, msg, wParam, lParam);
default:
}
break;
}
case OS.WM_SETCURSOR: {
if (cast(HWND) wParam is hwnd) {
int hitTest = cast(short) OS.LOWORD(lParam);
if (hitTest is OS.HTCLIENT) {
HDHITTESTINFO pinfo;
int pos = OS.GetMessagePos();
POINT pt;
OS.POINTSTOPOINT(pt, pos);
OS.ScreenToClient(hwnd, &pt);
pinfo.pt.x = pt.x;
pinfo.pt.y = pt.y;
auto index = OS.SendMessage(hwndHeader, OS.HDM_HITTEST, 0, &pinfo);
if (0 <= index && index < columnCount && !columns[index].resizable) {
if ((pinfo.flags & (OS.HHT_ONDIVIDER | OS.HHT_ONDIVOPEN)) !is 0) {
OS.SetCursor(OS.LoadCursor(null, cast(TCHAR*) OS.IDC_ARROW));
return 1;
}
}
}
}
break;
}
default:
}
return callWindowProc(hwnd, msg, wParam, lParam);
}
if (hwndParent !is null && hwnd is hwndParent) {
switch (msg) {
case OS.WM_MOVE: {
sendEvent(SWT.Move);
return 0;
}
case OS.WM_SIZE: {
setScrollWidth();
if (ignoreResize)
return 0;
setResizeChildren(false);
auto code = callWindowProc(hwnd, OS.WM_SIZE, wParam, lParam);
sendEvent(SWT.Resize);
if (isDisposed())
return 0;
if (layout_ !is null) {
markLayout(false, false);
updateLayout(false, false);
}
setResizeChildren(true);
updateScrollBar();
return code;
}
case OS.WM_NCPAINT: {
LRESULT result = wmNCPaint(hwnd, wParam, lParam);
if (result !is null)
return result.value;
break;
}
case OS.WM_PRINT: {
LRESULT result = wmPrint(hwnd, wParam, lParam);
if (result !is null)
return result.value;
break;
}
case OS.WM_COMMAND:
case OS.WM_NOTIFY:
case OS.WM_SYSCOLORCHANGE: {
return OS.SendMessage(handle, msg, wParam, lParam);
}
case OS.WM_HSCROLL: {
/*
* Bug on WinCE. lParam should be NULL when the message is not sent
* by a scroll bar control, but it contains the handle to the window.
* When the message is sent by a scroll bar control, it correctly
* contains the handle to the scroll bar. The fix is to check for
* both.
*/
if (horizontalBar !is null && (lParam is 0 || lParam is cast(ptrdiff_t) hwndParent)) {
wmScroll(horizontalBar, true, hwndParent, OS.WM_HSCROLL, wParam, lParam);
}
setScrollWidth();
break;
}
case OS.WM_VSCROLL: {
SCROLLINFO info;
info.cbSize = SCROLLINFO.sizeof;
info.fMask = OS.SIF_ALL;
OS.GetScrollInfo(hwndParent, OS.SB_VERT, &info);
/*
* Update the nPos field to match the nTrackPos field
* so that the tree scrolls when the scroll bar of the
* parent is dragged.
*
* NOTE: For some reason, this code is only necessary
* on Windows Vista.
*/
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0)) {
if (OS.LOWORD(wParam) is OS.SB_THUMBTRACK) {
info.nPos = info.nTrackPos;
}
}
OS.SetScrollInfo(handle, OS.SB_VERT, &info, true);
auto code = OS.SendMessage(handle, OS.WM_VSCROLL, wParam, lParam);
OS.GetScrollInfo(handle, OS.SB_VERT, &info);
OS.SetScrollInfo(hwndParent, OS.SB_VERT, &info, true);
return code;
}
default:
}
return callWindowProc(hwnd, msg, wParam, lParam);
}
if (msg is Display.DI_GETDRAGIMAGE) {
/*
* When there is more than one item selected, DI_GETDRAGIMAGE
* returns the item under the cursor. This happens because
* the tree does not have implement multi-select. The fix
* is to disable DI_GETDRAGIMAGE when more than one item is
* selected.
*/
if ((style & SWT.MULTI) !is 0 || hooks(SWT.EraseItem) || hooks(SWT.PaintItem)) {
auto hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0);
TreeItem[] items = new TreeItem[10];
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM | OS.TVIF_STATE;
int count = getSelection(hItem, &tvItem, items, 0, 10, false, true);
if (count is 0)
return 0;
POINT mousePos;
OS.POINTSTOPOINT(mousePos, OS.GetMessagePos());
OS.MapWindowPoints(null, handle, &mousePos, 1);
RECT clientRect;
OS.GetClientRect(handle, &clientRect);
RECT rect = *(items[0].getBounds(0, true, true, false));
if ((style & SWT.FULL_SELECTION) !is 0) {
int width = DRAG_IMAGE_SIZE;
rect.left = Math.max(clientRect.left, mousePos.x - width / 2);
if (clientRect.right > rect.left + width) {
rect.right = rect.left + width;
}
else {
rect.right = clientRect.right;
rect.left = Math.max(clientRect.left, rect.right - width);
}
}
auto hRgn = OS.CreateRectRgn(rect.left, rect.top, rect.right, rect.bottom);
for (int i = 1; i < count; i++) {
if (rect.bottom - rect.top > DRAG_IMAGE_SIZE)
break;
if (rect.bottom > clientRect.bottom)
break;
RECT itemRect = *(items[i].getBounds(0, true, true, false));
if ((style & SWT.FULL_SELECTION) !is 0) {
itemRect.left = rect.left;
itemRect.right = rect.right;
}
auto rectRgn = OS.CreateRectRgn(itemRect.left,
itemRect.top, itemRect.right, itemRect.bottom);
OS.CombineRgn(hRgn, hRgn, rectRgn, OS.RGN_OR);
OS.DeleteObject(rectRgn);
rect.bottom = itemRect.bottom;
}
OS.GetRgnBox(hRgn, &rect);
/* Create resources */
auto hdc = OS.GetDC(handle);
auto memHdc = OS.CreateCompatibleDC(hdc);
BITMAPINFOHEADER bmiHeader;
bmiHeader.biSize = BITMAPINFOHEADER.sizeof;
bmiHeader.biWidth = rect.right - rect.left;
bmiHeader.biHeight = -(rect.bottom - rect.top);
bmiHeader.biPlanes = 1;
bmiHeader.biBitCount = 32;
bmiHeader.biCompression = OS.BI_RGB;
byte[] bmi = new byte[BITMAPINFOHEADER.sizeof];
OS.MoveMemory(bmi.ptr, &bmiHeader, BITMAPINFOHEADER.sizeof);
void*[1] pBits;
auto memDib = OS.CreateDIBSection(null, cast(BITMAPINFO*) bmi.ptr,
OS.DIB_RGB_COLORS, pBits.ptr, null, 0);
if (memDib is null)
SWT.error(SWT.ERROR_NO_HANDLES);
auto oldMemBitmap = OS.SelectObject(memHdc, memDib);
int colorKey = 0x0000FD;
POINT pt;
OS.SetWindowOrgEx(memHdc, rect.left, rect.top, &pt);
OS.FillRect(memHdc, &rect, findBrush(colorKey, OS.BS_SOLID));
OS.OffsetRgn(hRgn, -rect.left, -rect.top);
OS.SelectClipRgn(memHdc, hRgn);
OS.PrintWindow(handle, memHdc, 0);
OS.SetWindowOrgEx(memHdc, pt.x, pt.y, null);
OS.SelectObject(memHdc, oldMemBitmap);
OS.DeleteDC(memHdc);
OS.ReleaseDC(null, hdc);
OS.DeleteObject(hRgn);
SHDRAGIMAGE shdi;
shdi.hbmpDragImage = memDib;
shdi.crColorKey = colorKey;
shdi.sizeDragImage.cx = bmiHeader.biWidth;
shdi.sizeDragImage.cy = -bmiHeader.biHeight;
shdi.ptOffset.x = mousePos.x - rect.left;
shdi.ptOffset.y = mousePos.y - rect.top;
if ((style & SWT.MIRRORED) !is 0) {
shdi.ptOffset.x = shdi.sizeDragImage.cx - shdi.ptOffset.x;
}
OS.MoveMemory(lParam, &shdi, SHDRAGIMAGE.sizeof);
return 1;
}
}
return super.windowProc(hwnd, msg, wParam, lParam);
}
override LRESULT WM_CHAR(WPARAM wParam, LPARAM lParam) {
LRESULT result = super.WM_CHAR(wParam, lParam);
if (result !is null)
return result;
/*
* Feature in Windows. The tree control beeps
* in WM_CHAR when the search for the item that
* matches the key stroke fails. This is the
* standard tree behavior but is unexpected when
* the key that was typed was ESC, CR or SPACE.
* The fix is to avoid calling the tree window
* proc in these cases.
*/
switch (wParam) {
case ' ': {
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
if (hItem !is null) {
hAnchor = hItem;
OS.SendMessage(handle, OS.TVM_ENSUREVISIBLE, 0, hItem);
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE | OS.TVIF_PARAM;
tvItem.hItem = cast(HTREEITEM) hItem;
if ((style & SWT.CHECK) !is 0) {
tvItem.stateMask = OS.TVIS_STATEIMAGEMASK;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
int state = tvItem.state >> 12;
if ((state & 0x1) !is 0) {
state++;
}
else {
--state;
}
tvItem.state = state << 12;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
static if (!OS.IsWinCE) {
auto id = cast(int) /*64bit*/ hItem;
if (OS.COMCTL32_MAJOR >= 6) {
id = cast(int) /*64bit*/ OS.SendMessage(handle,
OS.TVM_MAPHTREEITEMTOACCID, hItem, 0);
}
OS.NotifyWinEvent(OS.EVENT_OBJECT_FOCUS, handle, OS.OBJID_CLIENT, id);
}
}
tvItem.stateMask = OS.TVIS_SELECTED;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
if ((style & SWT.MULTI) !is 0 && OS.GetKeyState(OS.VK_CONTROL) < 0) {
if ((tvItem.state & OS.TVIS_SELECTED) !is 0) {
tvItem.state &= ~OS.TVIS_SELECTED;
}
else {
tvItem.state |= OS.TVIS_SELECTED;
}
}
else {
tvItem.state |= OS.TVIS_SELECTED;
}
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
TreeItem item = _getItem(hItem, tvItem.lParam);
Event event = new Event();
event.item = item;
postEvent(SWT.Selection, event);
if ((style & SWT.CHECK) !is 0) {
event = new Event();
event.item = item;
event.detail = SWT.CHECK;
postEvent(SWT.Selection, event);
}
}
return LRESULT.ZERO;
}
case SWT.CR: {
/*
* Feature in Windows. Windows sends NM_RETURN from WM_KEYDOWN
* instead of using WM_CHAR. This means that application code
* that expects to consume the key press and therefore avoid a
* SWT.DefaultSelection event from WM_CHAR will fail. The fix
* is to implement SWT.DefaultSelection in WM_CHAR instead of
* using NM_RETURN.
*/
Event event = new Event();
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
if (hItem !is null)
event.item = _getItem(hItem);
postEvent(SWT.DefaultSelection, event);
return LRESULT.ZERO;
}
case SWT.ESC:
return LRESULT.ZERO;
default:
}
return result;
}
override LRESULT WM_ERASEBKGND(WPARAM wParam, LPARAM lParam) {
LRESULT result = super.WM_ERASEBKGND(wParam, lParam);
if ((style & SWT.DOUBLE_BUFFERED) !is 0)
return LRESULT.ONE;
if (findImageControl() !is null)
return LRESULT.ONE;
return result;
}
override LRESULT WM_GETOBJECT(WPARAM wParam, LPARAM lParam) {
/*
* Ensure that there is an accessible object created for this
* control because support for checked item and tree column
* accessibility is temporarily implemented in the accessibility
* package.
*/
if ((style & SWT.CHECK) !is 0 || hwndParent !is null) {
if (accessible is null)
accessible = new_Accessible(this);
}
return super.WM_GETOBJECT(wParam, lParam);
}
override LRESULT WM_HSCROLL(WPARAM wParam, LPARAM lParam) {
bool fixScroll = false;
if ((style & SWT.DOUBLE_BUFFERED) !is 0) {
fixScroll = (style & SWT.VIRTUAL) !is 0 || hooks(SWT.EraseItem) || hooks(SWT.PaintItem);
}
if (fixScroll) {
style &= ~SWT.DOUBLE_BUFFERED;
if (explorerTheme) {
OS.SendMessage(handle, OS.TVM_SETEXTENDEDSTYLE, OS.TVS_EX_DOUBLEBUFFER, 0);
}
}
LRESULT result = super.WM_HSCROLL(wParam, lParam);
if (fixScroll) {
style |= SWT.DOUBLE_BUFFERED;
if (explorerTheme) {
OS.SendMessage(handle, OS.TVM_SETEXTENDEDSTYLE,
OS.TVS_EX_DOUBLEBUFFER, OS.TVS_EX_DOUBLEBUFFER);
}
}
if (result !is null)
return result;
return result;
}
override LRESULT WM_KEYDOWN(WPARAM wParam, LPARAM lParam) {
LRESULT result = super.WM_KEYDOWN(wParam, lParam);
if (result !is null)
return result;
switch (wParam) {
case OS.VK_SPACE:
/*
* Ensure that the window proc does not process VK_SPACE
* so that it can be handled in WM_CHAR. This allows the
* application to cancel an operation that is normally
* performed in WM_KEYDOWN from WM_CHAR.
*/
return LRESULT.ZERO;
case OS.VK_ADD:
if (OS.GetKeyState(OS.VK_CONTROL) < 0) {
if (hwndHeader !is null) {
TreeColumn[] newColumns = new TreeColumn[columnCount];
System.arraycopy(columns, 0, newColumns, 0, columnCount);
for (int i = 0; i < columnCount; i++) {
TreeColumn column = newColumns[i];
if (!column.isDisposed() && column.getResizable()) {
column.pack();
}
}
}
}
break;
case OS.VK_UP:
case OS.VK_DOWN:
case OS.VK_PRIOR:
case OS.VK_NEXT:
case OS.VK_HOME:
case OS.VK_END: {
OS.SendMessage(handle, OS.WM_CHANGEUISTATE, OS.UIS_INITIALIZE, 0);
if ((style & SWT.SINGLE) !is 0)
break;
if (OS.GetKeyState(OS.VK_SHIFT) < 0) {
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
if (hItem !is null) {
if (hAnchor is null)
hAnchor = hItem;
ignoreSelect = ignoreDeselect = true;
auto code = callWindowProc(handle, OS.WM_KEYDOWN, wParam, lParam);
ignoreSelect = ignoreDeselect = false;
auto hNewItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE;
tvItem.stateMask = OS.TVIS_SELECTED;
auto hDeselectItem = hItem;
RECT rect1;
if (!OS.TreeView_GetItemRect(handle,
cast(HTREEITEM) hAnchor, &rect1, false)) {
hAnchor = hItem;
OS.TreeView_GetItemRect(handle, cast(HTREEITEM) hAnchor, &rect1, false);
}
RECT rect2;
OS.TreeView_GetItemRect(handle,
cast(HTREEITEM) hDeselectItem, &rect2, false);
int flags = rect1.top < rect2.top
? OS.TVGN_PREVIOUSVISIBLE : OS.TVGN_NEXTVISIBLE;
while (hDeselectItem !is hAnchor) {
tvItem.hItem = cast(HTREEITEM) hDeselectItem;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
hDeselectItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, flags, hDeselectItem);
}
auto hSelectItem = hAnchor;
OS.TreeView_GetItemRect(handle, cast(HTREEITEM) hNewItem, &rect1, false);
OS.TreeView_GetItemRect(handle, cast(HTREEITEM) hSelectItem, &rect2, false);
tvItem.state = OS.TVIS_SELECTED;
flags = rect1.top < rect2.top ? OS.TVGN_PREVIOUSVISIBLE
: OS.TVGN_NEXTVISIBLE;
while (hSelectItem !is hNewItem) {
tvItem.hItem = cast(HTREEITEM) hSelectItem;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
hSelectItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, flags, hSelectItem);
}
tvItem.hItem = cast(HTREEITEM) hNewItem;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM;
tvItem.hItem = cast(HTREEITEM) hNewItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
Event event = new Event();
event.item = _getItem(hNewItem, tvItem.lParam);
postEvent(SWT.Selection, event);
return new LRESULT(code);
}
}
if (OS.GetKeyState(OS.VK_CONTROL) < 0) {
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
if (hItem !is null) {
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE;
tvItem.stateMask = OS.TVIS_SELECTED;
tvItem.hItem = cast(HTREEITEM) hItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
bool oldSelected = (tvItem.state & OS.TVIS_SELECTED) !is 0;
HANDLE hNewItem;
switch (wParam) {
case OS.VK_UP:
hNewItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_PREVIOUSVISIBLE, hItem);
break;
case OS.VK_DOWN:
hNewItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_NEXTVISIBLE, hItem);
break;
case OS.VK_HOME:
hNewItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
break;
case OS.VK_PRIOR:
hNewItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0);
if (hNewItem is hItem) {
OS.SendMessage(handle, OS.WM_VSCROLL, OS.SB_PAGEUP, 0);
hNewItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0);
}
break;
case OS.VK_NEXT:
RECT rect, clientRect;
OS.GetClientRect(handle, &clientRect);
hNewItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0);
do {
auto hVisible = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_NEXTVISIBLE, hNewItem);
if (hVisible is null)
break;
if (!OS.TreeView_GetItemRect(handle,
cast(HTREEITEM) hVisible, &rect, false))
break;
if (rect.bottom > clientRect.bottom)
break;
if ((hNewItem = hVisible) is hItem) {
OS.SendMessage(handle, OS.WM_VSCROLL, OS.SB_PAGEDOWN, 0);
}
}
while (hNewItem !is null);
break;
case OS.VK_END:
hNewItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_LASTVISIBLE, 0);
break;
default:
}
if (hNewItem !is null) {
OS.SendMessage(handle, OS.TVM_ENSUREVISIBLE, 0, hNewItem);
tvItem.hItem = cast(HTREEITEM) hNewItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
bool newSelected = (tvItem.state & OS.TVIS_SELECTED) !is 0;
bool redraw = !newSelected && drawCount is 0
&& OS.IsWindowVisible(handle);
if (redraw) {
OS.UpdateWindow(handle);
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 0, 0);
}
hSelect = hNewItem;
ignoreSelect = true;
OS.SendMessage(handle, OS.TVM_SELECTITEM, OS.TVGN_CARET, hNewItem);
ignoreSelect = false;
hSelect = null;
if (oldSelected) {
tvItem.state = OS.TVIS_SELECTED;
tvItem.hItem = cast(HTREEITEM) hItem;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
if (!newSelected) {
tvItem.state = 0;
tvItem.hItem = cast(HTREEITEM) hNewItem;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
if (redraw) {
RECT rect1, rect2;
bool fItemRect = (style & SWT.FULL_SELECTION) is 0;
if (hooks(SWT.EraseItem) || hooks(SWT.PaintItem))
fItemRect = false;
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0))
fItemRect = false;
OS.TreeView_GetItemRect(handle,
cast(HTREEITEM) hItem, &rect1, fItemRect);
OS.TreeView_GetItemRect(handle,
cast(HTREEITEM) hNewItem, &rect2, fItemRect);
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 1, 0);
OS.InvalidateRect(handle, &rect1, true);
OS.InvalidateRect(handle, &rect2, true);
OS.UpdateWindow(handle);
}
return LRESULT.ZERO;
}
}
}
auto code = callWindowProc(handle, OS.WM_KEYDOWN, wParam, lParam);
hAnchor = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
return new LRESULT(code);
}
default:
}
return result;
}
override LRESULT WM_KILLFOCUS(WPARAM wParam, LPARAM lParam) {
/*
* Bug in Windows. When a tree item that has an image
* with alpha is expanded or collapsed, the area where
* the image is drawn is not erased before it is drawn.
* This means that the image gets darker each time.
* The fix is to redraw the selection.
*
* Feature in Windows. When multiple item have
* the TVIS_SELECTED state, Windows redraws only
* the focused item in the color used to show the
* selection when the tree loses or gains focus.
* The fix is to force Windows to redraw the
* selection when focus is gained or lost.
*/
bool redraw = (style & SWT.MULTI) !is 0;
if (!redraw) {
if (!OS.IsWinCE && OS.COMCTL32_MAJOR >= 6) {
if (imageList !is null) {
int bits = OS.GetWindowLong(handle, OS.GWL_STYLE);
if ((bits & OS.TVS_FULLROWSELECT) is 0) {
redraw = true;
}
}
}
}
if (redraw)
redrawSelection();
return super.WM_KILLFOCUS(wParam, lParam);
}
override LRESULT WM_LBUTTONDBLCLK(WPARAM wParam, LPARAM lParam) {
TVHITTESTINFO lpht;
lpht.pt.x = OS.GET_X_LPARAM(lParam);
lpht.pt.y = OS.GET_Y_LPARAM(lParam);
OS.SendMessage(handle, OS.TVM_HITTEST, 0, &lpht);
if (lpht.hItem !is null) {
if ((style & SWT.CHECK) !is 0) {
if ((lpht.flags & OS.TVHT_ONITEMSTATEICON) !is 0) {
Display display = this.display;
display.captureChanged = false;
sendMouseEvent(SWT.MouseDown, 1, handle, OS.WM_LBUTTONDOWN, wParam, lParam);
if (!sendMouseEvent(SWT.MouseDoubleClick, 1, handle,
OS.WM_LBUTTONDBLCLK, wParam, lParam)) {
if (!display.captureChanged && !isDisposed()) {
if (OS.GetCapture() !is handle)
OS.SetCapture(handle);
}
return LRESULT.ZERO;
}
if (!display.captureChanged && !isDisposed()) {
if (OS.GetCapture() !is handle)
OS.SetCapture(handle);
}
OS.SetFocus(handle);
TVITEM tvItem;
tvItem.hItem = lpht.hItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM | OS.TVIF_STATE;
tvItem.stateMask = OS.TVIS_STATEIMAGEMASK;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
int state = tvItem.state >> 12;
if ((state & 0x1) !is 0) {
state++;
}
else {
--state;
}
tvItem.state = state << 12;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
static if (!OS.IsWinCE) {
int id = cast(int) /*64bit*/ tvItem.hItem;
if (OS.COMCTL32_MAJOR >= 6) {
id = cast(int) /*64bit*/ OS.SendMessage(handle,
OS.TVM_MAPHTREEITEMTOACCID, tvItem.hItem, 0);
}
OS.NotifyWinEvent(OS.EVENT_OBJECT_FOCUS, handle, OS.OBJID_CLIENT, id);
}
Event event = new Event();
event.item = _getItem(tvItem.hItem, tvItem.lParam);
event.detail = SWT.CHECK;
postEvent(SWT.Selection, event);
return LRESULT.ZERO;
}
}
}
LRESULT result = super.WM_LBUTTONDBLCLK(wParam, lParam);
if (result is LRESULT.ZERO)
return result;
if (lpht.hItem !is null) {
int flags = OS.TVHT_ONITEM;
if ((style & SWT.FULL_SELECTION) !is 0) {
flags |= OS.TVHT_ONITEMRIGHT | OS.TVHT_ONITEMINDENT;
}
else {
if (hooks(SWT.MeasureItem)) {
lpht.flags &= ~(OS.TVHT_ONITEMICON | OS.TVHT_ONITEMLABEL);
if (hitTestSelection(lpht.hItem, lpht.pt.x, lpht.pt.y)) {
lpht.flags |= OS.TVHT_ONITEMICON | OS.TVHT_ONITEMLABEL;
}
}
}
if ((lpht.flags & flags) !is 0) {
Event event = new Event();
event.item = _getItem(lpht.hItem);
postEvent(SWT.DefaultSelection, event);
}
}
return result;
}
override LRESULT WM_LBUTTONDOWN(WPARAM wParam, LPARAM lParam) {
/*
* In a multi-select tree, if the user is collapsing a subtree that
* contains selected items, clear the selection from these items and
* issue a selection event. Only items that are selected and visible
* are cleared. This code also runs in the case when the white space
* below the last item is selected.
*/
TVHITTESTINFO lpht;
lpht.pt.x = OS.GET_X_LPARAM(lParam);
lpht.pt.y = OS.GET_Y_LPARAM(lParam);
OS.SendMessage(handle, OS.TVM_HITTEST, 0, &lpht);
if (lpht.hItem is null || (lpht.flags & OS.TVHT_ONITEMBUTTON) !is 0) {
Display display = this.display;
display.captureChanged = false;
if (!sendMouseEvent(SWT.MouseDown, 1, handle, OS.WM_LBUTTONDOWN, wParam, lParam)) {
if (!display.captureChanged && !isDisposed()) {
if (OS.GetCapture() !is handle)
OS.SetCapture(handle);
}
return LRESULT.ZERO;
}
bool fixSelection = false, deselected = false;
HANDLE hOldSelection = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
if (lpht.hItem !is null && (style & SWT.MULTI) !is 0) {
if (hOldSelection !is null) {
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE;
tvItem.hItem = lpht.hItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
if ((tvItem.state & OS.TVIS_EXPANDED) !is 0) {
fixSelection = true;
tvItem.stateMask = OS.TVIS_SELECTED;
auto hNext = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_NEXTVISIBLE, lpht.hItem);
while (hNext !is null) {
if (hNext is hAnchor)
hAnchor = null;
tvItem.hItem = cast(HTREEITEM) hNext;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
if ((tvItem.state & OS.TVIS_SELECTED) !is 0)
deselected = true;
tvItem.state = 0;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
HANDLE hItem = hNext = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_NEXTVISIBLE, hNext);
while (hItem !is null && hItem !is lpht.hItem) {
hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_PARENT, hItem);
}
if (hItem is null)
break;
}
}
}
}
dragStarted = gestureCompleted = false;
if (fixSelection)
ignoreDeselect = ignoreSelect = lockSelection = true;
auto code = callWindowProc(handle, OS.WM_LBUTTONDOWN, wParam, lParam);
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0)) {
if (OS.GetFocus() !is handle)
OS.SetFocus(handle);
}
if (fixSelection)
ignoreDeselect = ignoreSelect = lockSelection = false;
HANDLE hNewSelection = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
if (hOldSelection !is hNewSelection)
hAnchor = hNewSelection;
if (dragStarted) {
if (!display.captureChanged && !isDisposed()) {
if (OS.GetCapture() !is handle)
OS.SetCapture(handle);
}
}
/*
* Bug in Windows. When a tree has no images and an item is
* expanded or collapsed, for some reason, Windows changes
* the size of the selection. When the user expands a tree
* item, the selection rectangle is made a few pixels larger.
* When the user collapses an item, the selection rectangle
* is restored to the original size but the selection is not
* redrawn, causing pixel corruption. The fix is to detect
* this case and redraw the item.
*/
if ((lpht.flags & OS.TVHT_ONITEMBUTTON) !is 0) {
int bits = OS.GetWindowLong(handle, OS.GWL_STYLE);
if ((bits & OS.TVS_FULLROWSELECT) is 0) {
if (OS.SendMessage(handle, OS.TVM_GETIMAGELIST, OS.TVSIL_NORMAL, 0) is 0) {
auto hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
if (hItem !is null) {
RECT rect;
if (OS.TreeView_GetItemRect(handle,
cast(HTREEITEM) hItem, &rect, false)) {
OS.InvalidateRect(handle, &rect, true);
}
}
}
}
}
if (deselected) {
Event event = new Event();
event.item = _getItem(lpht.hItem);
postEvent(SWT.Selection, event);
}
return new LRESULT(code);
}
/* Look for check/uncheck */
if ((style & SWT.CHECK) !is 0) {
if ((lpht.flags & OS.TVHT_ONITEMSTATEICON) !is 0) {
Display display = this.display;
display.captureChanged = false;
if (!sendMouseEvent(SWT.MouseDown, 1, handle, OS.WM_LBUTTONDOWN, wParam, lParam)) {
if (!display.captureChanged && !isDisposed()) {
if (OS.GetCapture() !is handle)
OS.SetCapture(handle);
}
return LRESULT.ZERO;
}
if (!display.captureChanged && !isDisposed()) {
if (OS.GetCapture() !is handle)
OS.SetCapture(handle);
}
OS.SetFocus(handle);
TVITEM tvItem;
tvItem.hItem = lpht.hItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM | OS.TVIF_STATE;
tvItem.stateMask = OS.TVIS_STATEIMAGEMASK;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
int state = tvItem.state >> 12;
if ((state & 0x1) !is 0) {
state++;
}
else {
--state;
}
tvItem.state = state << 12;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
static if (!OS.IsWinCE) {
int id = cast(int) /*64bit*/ tvItem.hItem;
if (OS.COMCTL32_MAJOR >= 6) {
id = cast(int) /*64bit*/ OS.SendMessage(handle,
OS.TVM_MAPHTREEITEMTOACCID, tvItem.hItem, 0);
}
OS.NotifyWinEvent(OS.EVENT_OBJECT_FOCUS, handle, OS.OBJID_CLIENT, id);
}
Event event = new Event();
event.item = _getItem(tvItem.hItem, tvItem.lParam);
event.detail = SWT.CHECK;
postEvent(SWT.Selection, event);
return LRESULT.ZERO;
}
}
/*
* Feature in Windows. When the tree has the style
* TVS_FULLROWSELECT, the background color for the
* entire row is filled when an item is painted,
* drawing on top of any custom drawing. The fix
* is to emulate TVS_FULLROWSELECT.
*/
bool selected = false;
bool fakeSelection = false;
if (lpht.hItem !is null) {
if ((style & SWT.FULL_SELECTION) !is 0) {
int bits = OS.GetWindowLong(handle, OS.GWL_STYLE);
if ((bits & OS.TVS_FULLROWSELECT) is 0)
fakeSelection = true;
}
else {
if (hooks(SWT.MeasureItem)) {
selected = hitTestSelection(lpht.hItem, lpht.pt.x, lpht.pt.y) !is 0;
if (selected) {
if ((lpht.flags & OS.TVHT_ONITEM) is 0)
fakeSelection = true;
}
}
}
}
/* Process the mouse when an item is not selected */
if (!selected && (style & SWT.FULL_SELECTION) is 0) {
if ((lpht.flags & OS.TVHT_ONITEM) is 0) {
Display display = this.display;
display.captureChanged = false;
if (!sendMouseEvent(SWT.MouseDown, 1, handle, OS.WM_LBUTTONDOWN, wParam, lParam)) {
if (!display.captureChanged && !isDisposed()) {
if (OS.GetCapture() !is handle)
OS.SetCapture(handle);
}
return LRESULT.ZERO;
}
auto code = callWindowProc(handle, OS.WM_LBUTTONDOWN, wParam, lParam);
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0)) {
if (OS.GetFocus() !is handle)
OS.SetFocus(handle);
}
if (!display.captureChanged && !isDisposed()) {
if (OS.GetCapture() !is handle)
OS.SetCapture(handle);
}
return new LRESULT(code);
}
}
/* Get the selected state of the item under the mouse */
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE;
tvItem.stateMask = OS.TVIS_SELECTED;
bool hittestSelected = false;
if ((style & SWT.MULTI) !is 0) {
tvItem.hItem = lpht.hItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
hittestSelected = (tvItem.state & OS.TVIS_SELECTED) !is 0;
}
/* Get the selected state of the last selected item */
auto hOldItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
if ((style & SWT.MULTI) !is 0) {
tvItem.hItem = cast(HTREEITEM) hOldItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
/* Check for CONTROL or drag selection */
if (hittestSelected || (wParam & OS.MK_CONTROL) !is 0) {
/*
* Feature in Windows. When the tree is not drawing focus
* and the user selects a tree item while the CONTROL key
* is down, the tree window proc sends WM_UPDATEUISTATE
* to the top level window, causing controls within the shell
* to redraw. When drag detect is enabled, the tree window
* proc runs a modal loop that allows WM_PAINT messages to be
* delivered during WM_LBUTTONDOWN. When WM_SETREDRAW is used
* to disable drawing for the tree and a WM_PAINT happens for
* a parent of the tree (or a sibling that overlaps), the parent
* will draw on top of the tree. If WM_SETREDRAW is turned back
* on without redrawing the entire tree, pixel corruption occurs.
* This case only seems to happen when the tree has been given
* focus from WM_MOUSEACTIVATE of the shell. The fix is to
* force the WM_UPDATEUISTATE to be sent before disabling
* the drawing.
*
* NOTE: Any redraw of a parent (or sibling) will be dispatched
* during the modal drag detect loop. This code only fixes the
* case where the tree causes a redraw from WM_UPDATEUISTATE.
* In SWT, the InvalidateRect() that caused the pixel corruption
* is found in Composite.WM_UPDATEUISTATE().
*/
auto uiState = OS.SendMessage(handle, OS.WM_QUERYUISTATE, 0, 0);
if ((uiState & OS.UISF_HIDEFOCUS) !is 0) {
OS.SendMessage(handle, OS.WM_CHANGEUISTATE, OS.UIS_INITIALIZE, 0);
}
OS.UpdateWindow(handle);
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 0, 0);
}
else {
deselectAll();
}
}
/* Do the selection */
Display display = this.display;
display.captureChanged = false;
if (!sendMouseEvent(SWT.MouseDown, 1, handle, OS.WM_LBUTTONDOWN, wParam, lParam)) {
if (!display.captureChanged && !isDisposed()) {
if (OS.GetCapture() !is handle)
OS.SetCapture(handle);
}
return LRESULT.ZERO;
}
hSelect = lpht.hItem;
dragStarted = gestureCompleted = false;
ignoreDeselect = ignoreSelect = true;
auto code = callWindowProc(handle, OS.WM_LBUTTONDOWN, wParam, lParam);
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0)) {
if (OS.GetFocus() !is handle)
OS.SetFocus(handle);
}
auto hNewItem = cast(HANDLE) OS.SendMessage(handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
if (fakeSelection) {
if (hOldItem is null || (hNewItem is hOldItem && lpht.hItem !is hOldItem)) {
OS.SendMessage(handle, OS.TVM_SELECTITEM, OS.TVGN_CARET, lpht.hItem);
hNewItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0);
}
if (!dragStarted && (state & DRAG_DETECT) !is 0 && hooks(SWT.DragDetect)) {
dragStarted = dragDetect(handle, lpht.pt.x, lpht.pt.y, false, null, null);
}
}
ignoreDeselect = ignoreSelect = false;
hSelect = null;
if (dragStarted) {
if (!display.captureChanged && !isDisposed()) {
if (OS.GetCapture() !is handle)
OS.SetCapture(handle);
}
}
/*
* Feature in Windows. When the old and new focused item
* are the same, Windows does not check to make sure that
* the item is actually selected, not just focused. The
* fix is to force the item to draw selected by setting
* the state mask. This is only necessary when the tree
* is single select.
*/
if ((style & SWT.SINGLE) !is 0) {
if (hOldItem is hNewItem) {
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE;
tvItem.state = OS.TVIS_SELECTED;
tvItem.stateMask = OS.TVIS_SELECTED;
tvItem.hItem = cast(HTREEITEM) hNewItem;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
}
/* Reselect the last item that was unselected */
if ((style & SWT.MULTI) !is 0) {
/* Check for CONTROL and reselect the last item */
if (hittestSelected || (wParam & OS.MK_CONTROL) !is 0) {
if (hOldItem is hNewItem && hOldItem is lpht.hItem) {
if ((wParam & OS.MK_CONTROL) !is 0) {
tvItem.state ^= OS.TVIS_SELECTED;
if (dragStarted)
tvItem.state = OS.TVIS_SELECTED;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
}
else {
if ((tvItem.state & OS.TVIS_SELECTED) !is 0) {
tvItem.state = OS.TVIS_SELECTED;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
if ((wParam & OS.MK_CONTROL) !is 0 && !dragStarted) {
if (hittestSelected) {
tvItem.state = 0;
tvItem.hItem = lpht.hItem;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
}
}
RECT rect1, rect2;
bool fItemRect = (style & SWT.FULL_SELECTION) is 0;
if (hooks(SWT.EraseItem) || hooks(SWT.PaintItem))
fItemRect = false;
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0))
fItemRect = false;
OS.TreeView_GetItemRect(handle, cast(HTREEITEM) hOldItem, &rect1, fItemRect);
OS.TreeView_GetItemRect(handle, cast(HTREEITEM) hNewItem, &rect2, fItemRect);
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 1, 0);
OS.InvalidateRect(handle, &rect1, true);
OS.InvalidateRect(handle, &rect2, true);
OS.UpdateWindow(handle);
}
/* Check for SHIFT or normal select and deselect/reselect items */
if ((wParam & OS.MK_CONTROL) is 0) {
if (!hittestSelected || !dragStarted) {
tvItem.state = 0;
auto oldProc = OS.GetWindowLongPtr(handle, OS.GWLP_WNDPROC);
OS.SetWindowLongPtr(handle, OS.GWLP_WNDPROC, cast(LONG_PTR) TreeProc);
if ((style & SWT.VIRTUAL) !is 0) {
HANDLE hItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0);
deselect(hItem, &tvItem, hNewItem);
}
else {
for (int i = 0; i < items.length; i++) {
TreeItem item = items[i];
if (item !is null && item.handle !is hNewItem) {
tvItem.hItem = cast(HTREEITEM) item.handle;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
}
}
tvItem.hItem = cast(HTREEITEM) hNewItem;
tvItem.state = OS.TVIS_SELECTED;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
OS.SetWindowLongPtr(handle, OS.GWLP_WNDPROC, oldProc);
if ((wParam & OS.MK_SHIFT) !is 0) {
RECT rect1;
if (hAnchor is null)
hAnchor = hNewItem;
if (OS.TreeView_GetItemRect(handle, cast(HTREEITEM) hAnchor, &rect1, false)) {
RECT rect2;
if (OS.TreeView_GetItemRect(handle,
cast(HTREEITEM) hNewItem, &rect2, false)) {
int flags = rect1.top < rect2.top
? OS.TVGN_NEXTVISIBLE : OS.TVGN_PREVIOUSVISIBLE;
tvItem.state = OS.TVIS_SELECTED;
auto hItem = tvItem.hItem = cast(HTREEITEM) hAnchor;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
while (hItem !is hNewItem) {
tvItem.hItem = hItem;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
hItem = cast(HTREEITEM) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, flags, hItem);
}
}
}
}
}
}
}
if ((wParam & OS.MK_SHIFT) is 0)
hAnchor = hNewItem;
/* Issue notification */
if (!gestureCompleted) {
tvItem.hItem = cast(HTREEITEM) hNewItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
Event event = new Event();
event.item = _getItem(tvItem.hItem, tvItem.lParam);
postEvent(SWT.Selection, event);
}
gestureCompleted = false;
/*
* Feature in Windows. Inside WM_LBUTTONDOWN and WM_RBUTTONDOWN,
* the widget starts a modal loop to determine if the user wants
* to begin a drag/drop operation or marquee select. Unfortunately,
* this modal loop eats the corresponding mouse up. The fix is to
* detect the cases when the modal loop has eaten the mouse up and
* issue a fake mouse up.
*/
if (dragStarted) {
sendDragEvent(1, OS.GET_X_LPARAM(lParam), OS.GET_Y_LPARAM(lParam));
}
else {
int bits = OS.GetWindowLong(handle, OS.GWL_STYLE);
if ((bits & OS.TVS_DISABLEDRAGDROP) is 0) {
sendMouseEvent(SWT.MouseUp, 1, handle, OS.WM_LBUTTONUP, wParam, lParam);
}
}
dragStarted = false;
return new LRESULT(code);
}
override LRESULT WM_MOUSEMOVE(WPARAM wParam, LPARAM lParam) {
Display display = this.display;
LRESULT result = super.WM_MOUSEMOVE(wParam, lParam);
if (result !is null)
return result;
if (itemToolTipHandle !is null) {
/*
* Bug in Windows. On some machines that do not have XBUTTONs,
* the MK_XBUTTON1 and OS.MK_XBUTTON2 bits are sometimes set,
* causing mouse capture to become stuck. The fix is to test
* for the extra buttons only when they exist.
*/
int mask = OS.MK_LBUTTON | OS.MK_MBUTTON | OS.MK_RBUTTON;
if (display.xMouse)
mask |= OS.MK_XBUTTON1 | OS.MK_XBUTTON2;
if ((wParam & mask) is 0) {
int x = OS.GET_X_LPARAM(lParam);
int y = OS.GET_Y_LPARAM(lParam);
int index;
TreeItem item;
RECT* cellRect, itemRect;
if (findCell(x, y, item, index, cellRect, itemRect)) {
/*
* Feature in Windows. When the new tool rectangle is
* set using TTM_NEWTOOLRECT and the tooltip is visible,
* Windows draws the tooltip right away and the sends
* WM_NOTIFY with TTN_SHOW. This means that the tooltip
* shows first at the wrong location and then moves to
* the right one. The fix is to hide the tooltip window.
*/
if (OS.SendMessage(itemToolTipHandle, OS.TTM_GETCURRENTTOOL, 0, 0) is 0) {
if (OS.IsWindowVisible(itemToolTipHandle)) {
OS.ShowWindow(itemToolTipHandle, OS.SW_HIDE);
}
}
TOOLINFO lpti;
lpti.cbSize = OS.TOOLINFO_sizeof;
lpti.hwnd = handle;
lpti.uId = cast(ptrdiff_t) handle;
lpti.uFlags = OS.TTF_SUBCLASS | OS.TTF_TRANSPARENT;
lpti.rect.left = cellRect.left;
lpti.rect.top = cellRect.top;
lpti.rect.right = cellRect.right;
lpti.rect.bottom = cellRect.bottom;
OS.SendMessage(itemToolTipHandle, OS.TTM_NEWTOOLRECT, 0, &lpti);
}
}
}
return result;
}
override LRESULT WM_MOVE(WPARAM wParam, LPARAM lParam) {
if (ignoreResize)
return null;
return super.WM_MOVE(wParam, lParam);
}
override LRESULT WM_RBUTTONDOWN(WPARAM wParam, LPARAM lParam) {
/*
* Feature in Windows. The receiver uses WM_RBUTTONDOWN
* to initiate a drag/drop operation depending on how the
* user moves the mouse. If the user clicks the right button,
* without moving the mouse, the tree consumes the corresponding
* WM_RBUTTONUP. The fix is to avoid calling the window proc for
* the tree.
*/
Display display = this.display;
display.captureChanged = false;
if (!sendMouseEvent(SWT.MouseDown, 3, handle, OS.WM_RBUTTONDOWN, wParam, lParam)) {
if (!display.captureChanged && !isDisposed()) {
if (OS.GetCapture() !is handle)
OS.SetCapture(handle);
}
return LRESULT.ZERO;
}
/*
* This code is intentionally commented.
*/
// if (OS.GetCapture () !is handle) OS.SetCapture (handle);
if (OS.GetFocus() !is handle)
OS.SetFocus(handle);
/*
* Feature in Windows. When the user selects a tree item
* with the right mouse button, the item remains selected
* only as long as the user does not release or move the
* mouse. As soon as this happens, the selection snaps
* back to the previous selection. This behavior can be
* observed in the Explorer but is not instantly apparent
* because the Explorer explicitly sets the selection when
* the user chooses a menu item. If the user cancels the
* menu, the selection snaps back. The fix is to avoid
* calling the window proc and do the selection ourselves.
* This behavior is consistent with the table.
*/
TVHITTESTINFO lpht;
lpht.pt.x = OS.GET_X_LPARAM(lParam);
lpht.pt.y = OS.GET_Y_LPARAM(lParam);
OS.SendMessage(handle, OS.TVM_HITTEST, 0, &lpht);
if (lpht.hItem !is null) {
bool fakeSelection = (style & SWT.FULL_SELECTION) !is 0;
if (!fakeSelection) {
if (hooks(SWT.MeasureItem)) {
fakeSelection = hitTestSelection(lpht.hItem, lpht.pt.x, lpht.pt.y);
}
else {
int flags = OS.TVHT_ONITEMICON | OS.TVHT_ONITEMLABEL;
fakeSelection = (lpht.flags & flags) !is 0;
}
}
if (fakeSelection) {
if ((wParam & (OS.MK_CONTROL | OS.MK_SHIFT)) is 0) {
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE;
tvItem.stateMask = OS.TVIS_SELECTED;
tvItem.hItem = lpht.hItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
if ((tvItem.state & OS.TVIS_SELECTED) is 0) {
ignoreSelect = true;
OS.SendMessage(handle, OS.TVM_SELECTITEM, OS.TVGN_CARET, 0);
ignoreSelect = false;
OS.SendMessage(handle, OS.TVM_SELECTITEM, OS.TVGN_CARET, lpht.hItem);
}
}
}
}
return LRESULT.ZERO;
}
override LRESULT WM_PAINT(WPARAM wParam, LPARAM lParam) {
if (shrink && !ignoreShrink) {
/* Resize the item array to fit the last item */
int count = cast(int) /*64bit*/ items.length - 1;
while (count >= 0) {
if (items[count]!is null)
break;
--count;
}
count++;
if (items.length > 4 && items.length - count > 3) {
int length = Math.max(4, (count + 3) / 4 * 4);
TreeItem[] newItems = new TreeItem[length];
System.arraycopy(items, 0, newItems, 0, count);
items = newItems;
}
shrink = false;
}
if ((style & SWT.DOUBLE_BUFFERED) !is 0 || findImageControl() !is null) {
bool doubleBuffer = true;
if (explorerTheme) {
auto exStyle = OS.SendMessage(handle, OS.TVM_GETEXTENDEDSTYLE, 0, 0);
if ((exStyle & OS.TVS_EX_DOUBLEBUFFER) !is 0)
doubleBuffer = false;
}
if (doubleBuffer) {
GC gc = null;
HDC paintDC;
PAINTSTRUCT ps;
bool hooksPaint = hooks(SWT.Paint);
if (hooksPaint) {
GCData data = new GCData();
data.ps = &ps;
data.hwnd = handle;
gc = GC.win32_new(this, data);
paintDC = gc.handle;
}
else {
paintDC = OS.BeginPaint(handle, &ps);
}
int width = ps.rcPaint.right - ps.rcPaint.left;
int height = ps.rcPaint.bottom - ps.rcPaint.top;
if (width !is 0 && height !is 0) {
auto hDC = OS.CreateCompatibleDC(paintDC);
POINT lpPoint1, lpPoint2;
OS.SetWindowOrgEx(hDC, ps.rcPaint.left, ps.rcPaint.top, &lpPoint1);
OS.SetBrushOrgEx(hDC, ps.rcPaint.left, ps.rcPaint.top, &lpPoint2);
auto hBitmap = OS.CreateCompatibleBitmap(paintDC, width, height);
auto hOldBitmap = OS.SelectObject(hDC, hBitmap);
RECT rect;
OS.SetRect(&rect, ps.rcPaint.left, ps.rcPaint.top,
ps.rcPaint.right, ps.rcPaint.bottom);
drawBackground(hDC, &rect);
callWindowProc(handle, OS.WM_PAINT, cast(WPARAM) hDC, 0);
OS.SetWindowOrgEx(hDC, lpPoint1.x, lpPoint1.y, null);
OS.SetBrushOrgEx(hDC, lpPoint2.x, lpPoint2.y, null);
OS.BitBlt(paintDC, ps.rcPaint.left, ps.rcPaint.top, width,
height, hDC, 0, 0, OS.SRCCOPY);
OS.SelectObject(hDC, hOldBitmap);
OS.DeleteObject(hBitmap);
OS.DeleteObject(hDC);
if (hooksPaint) {
Event event = new Event();
event.gc = gc;
event.x = ps.rcPaint.left;
event.y = ps.rcPaint.top;
event.width = ps.rcPaint.right - ps.rcPaint.left;
event.height = ps.rcPaint.bottom - ps.rcPaint.top;
sendEvent(SWT.Paint, event);
// widget could be disposed at this point
event.gc = null;
}
}
if (hooksPaint) {
gc.dispose();
}
else {
OS.EndPaint(handle, &ps);
}
return LRESULT.ZERO;
}
}
return super.WM_PAINT(wParam, lParam);
}
override LRESULT WM_PRINTCLIENT(WPARAM wParam, LPARAM lParam) {
LRESULT result = super.WM_PRINTCLIENT(wParam, lParam);
if (result !is null)
return result;
/*
* Feature in Windows. For some reason, when WM_PRINT is used
* to capture an image of a hierarchy that contains a tree with
* columns, the clipping that is used to stop the first column
* from drawing on top of subsequent columns stops the first
* column and the tree lines from drawing. This does not happen
* during WM_PAINT. The fix is to draw without clipping and
* then draw the rest of the columns on top. Since the drawing
* is happening in WM_PRINTCLIENT, the redrawing is not visible.
*/
printClient = true;
auto code = callWindowProc(handle, OS.WM_PRINTCLIENT, wParam, lParam);
printClient = false;
return new LRESULT(code);
}
override LRESULT WM_SETFOCUS(WPARAM wParam, LPARAM lParam) {
/*
* Bug in Windows. When a tree item that has an image
* with alpha is expanded or collapsed, the area where
* the image is drawn is not erased before it is drawn.
* This means that the image gets darker each time.
* The fix is to redraw the selection.
*
* Feature in Windows. When multiple item have
* the TVIS_SELECTED state, Windows redraws only
* the focused item in the color used to show the
* selection when the tree loses or gains focus.
* The fix is to force Windows to redraw the
* selection when focus is gained or lost.
*/
bool redraw = (style & SWT.MULTI) !is 0;
if (!redraw) {
if (!OS.IsWinCE && OS.COMCTL32_MAJOR >= 6) {
if (imageList !is null) {
int bits = OS.GetWindowLong(handle, OS.GWL_STYLE);
if ((bits & OS.TVS_FULLROWSELECT) is 0) {
redraw = true;
}
}
}
}
if (redraw)
redrawSelection();
return super.WM_SETFOCUS(wParam, lParam);
}
override LRESULT WM_SETFONT(WPARAM wParam, LPARAM lParam) {
LRESULT result = super.WM_SETFONT(wParam, lParam);
if (result !is null)
return result;
if (hwndHeader !is null) {
/*
* Bug in Windows. When a header has a sort indicator
* triangle, Windows resizes the indicator based on the
* size of the n-1th font. The fix is to always make
* the n-1th font be the default. This makes the sort
* indicator always be the default size.
*/
OS.SendMessage(hwndHeader, OS.WM_SETFONT, 0, lParam);
OS.SendMessage(hwndHeader, OS.WM_SETFONT, wParam, lParam);
}
if (itemToolTipHandle !is null) {
OS.SendMessage(itemToolTipHandle, OS.WM_SETFONT, wParam, lParam);
}
if (headerToolTipHandle !is null) {
OS.SendMessage(headerToolTipHandle, OS.WM_SETFONT, wParam, lParam);
}
return result;
}
override LRESULT WM_SETREDRAW(WPARAM wParam, LPARAM lParam) {
LRESULT result = super.WM_SETREDRAW(wParam, lParam);
if (result !is null)
return result;
/*
* Bug in Windows. Under certain circumstances, when
* WM_SETREDRAW is used to turn off drawing and then
* TVM_GETITEMRECT is sent to get the bounds of an item
* that is not inside the client area, Windows segment
* faults. The fix is to call the default window proc
* rather than the default tree proc.
*
* NOTE: This problem is intermittent and happens on
* Windows Vista running under the theme manager.
*/
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0)) {
auto code = OS.DefWindowProc(handle, OS.WM_SETREDRAW, wParam, lParam);
return code is 0 ? LRESULT.ZERO : new LRESULT(code);
}
return result;
}
override LRESULT WM_SIZE(WPARAM wParam, LPARAM lParam) {
/*
* Bug in Windows. When TVS_NOHSCROLL is set when the
* size of the tree is zero, the scroll bar is shown the
* next time the tree resizes. The fix is to hide the
* scroll bar every time the tree is resized.
*/
int bits = OS.GetWindowLong(handle, OS.GWL_STYLE);
if ((bits & OS.TVS_NOHSCROLL) !is 0) {
static if (!OS.IsWinCE)
OS.ShowScrollBar(handle, OS.SB_HORZ, false);
}
/*
* Bug in Windows. On Vista, when the Explorer theme
* is used with a full selection tree, when the tree
* is resized to be smaller, the rounded right edge
* of the selected items is not drawn. The fix is the
* redraw the entire tree.
*/
if (explorerTheme && (style & SWT.FULL_SELECTION) !is 0) {
OS.InvalidateRect(handle, null, false);
}
if (ignoreResize)
return null;
return super.WM_SIZE(wParam, lParam);
}
override LRESULT WM_SYSCOLORCHANGE(WPARAM wParam, LPARAM lParam) {
LRESULT result = super.WM_SYSCOLORCHANGE(wParam, lParam);
if (result !is null)
return result;
/*
* Bug in Windows. When the tree is using the explorer
* theme, it does not use COLOR_WINDOW_TEXT for the
* default foreground color. The fix is to explicitly
* set the foreground.
*/
if (explorerTheme) {
if (foreground is -1)
setForegroundPixel(-1);
}
if ((style & SWT.CHECK) !is 0)
setCheckboxImageList();
return result;
}
override LRESULT WM_VSCROLL(WPARAM wParam, LPARAM lParam) {
bool fixScroll = false;
if ((style & SWT.DOUBLE_BUFFERED) !is 0) {
int code = OS.LOWORD(wParam);
switch (code) {
case OS.SB_TOP:
case OS.SB_BOTTOM:
case OS.SB_LINEDOWN:
case OS.SB_LINEUP:
case OS.SB_PAGEDOWN:
case OS.SB_PAGEUP:
fixScroll = (style & SWT.VIRTUAL) !is 0
|| hooks(SWT.EraseItem) || hooks(SWT.PaintItem);
break;
default:
}
}
if (fixScroll) {
style &= ~SWT.DOUBLE_BUFFERED;
if (explorerTheme) {
OS.SendMessage(handle, OS.TVM_SETEXTENDEDSTYLE, OS.TVS_EX_DOUBLEBUFFER, 0);
}
}
LRESULT result = super.WM_VSCROLL(wParam, lParam);
if (fixScroll) {
style |= SWT.DOUBLE_BUFFERED;
if (explorerTheme) {
OS.SendMessage(handle, OS.TVM_SETEXTENDEDSTYLE,
OS.TVS_EX_DOUBLEBUFFER, OS.TVS_EX_DOUBLEBUFFER);
}
}
if (result !is null)
return result;
return result;
}
override LRESULT wmColorChild(WPARAM wParam, LPARAM lParam) {
if (findImageControl() !is null) {
if (OS.COMCTL32_MAJOR < 6) {
return super.wmColorChild(wParam, lParam);
}
return new LRESULT(OS.GetStockObject(OS.NULL_BRUSH));
}
/*
* Feature in Windows. Tree controls send WM_CTLCOLOREDIT
* to allow application code to change the default colors.
* This is undocumented and conflicts with TVM_SETTEXTCOLOR
* and TVM_SETBKCOLOR, the documented way to do this. The
* fix is to ignore WM_CTLCOLOREDIT messages from trees.
*/
return null;
}
override LRESULT wmNotify(NMHDR* hdr, WPARAM wParam, LPARAM lParam) {
if (hdr.hwndFrom is itemToolTipHandle) {
LRESULT result = wmNotifyToolTip(hdr, wParam, lParam);
if (result !is null)
return result;
}
if (hdr.hwndFrom is hwndHeader) {
LRESULT result = wmNotifyHeader(hdr, wParam, lParam);
if (result !is null)
return result;
}
return super.wmNotify(hdr, wParam, lParam);
}
override LRESULT wmNotifyChild(NMHDR* hdr, WPARAM wParam, LPARAM lParam) {
switch (hdr.code) {
case OS.TVN_GETDISPINFOA:
case OS.TVN_GETDISPINFOW: {
NMTVDISPINFO* lptvdi = cast(NMTVDISPINFO*) lParam;
//OS.MoveMemory (lptvdi, lParam, NMTVDISPINFO.sizeof);
if ((style & SWT.VIRTUAL) !is 0) {
/*
* Feature in Windows. When a new tree item is inserted
* using TVM_INSERTITEM, a TVN_GETDISPINFO is sent before
* TVM_INSERTITEM returns and before the item is added to
* the items array. The fix is to check for null.
*
* NOTE: This only happens on XP with the version 6.00 of
* COMCTL32.DLL.
*/
bool checkVisible = true;
/*
* When an item is being deleted from a virtual tree, do not
* allow the application to provide data for a new item that
* becomes visible until the item has been removed from the
* items array. Because arbitrary application code can run
* during the callback, the items array might be accessed
* in an inconsistent state. Rather than answering the data
* right away, queue a redraw for later.
*/
if (!ignoreShrink) {
if (items !is null && lptvdi.item.lParam !is -1) {
if (items[lptvdi.item.lParam]!is null
&& items[lptvdi.item.lParam].cached) {
checkVisible = false;
}
}
}
if (checkVisible) {
if (drawCount !is 0 || !OS.IsWindowVisible(handle))
break;
RECT itemRect;
if (!OS.TreeView_GetItemRect(handle, lptvdi.item.hItem, &itemRect, false)) {
break;
}
RECT rect;
OS.GetClientRect(handle, &rect);
if (!OS.IntersectRect(&rect, &rect, &itemRect))
break;
if (ignoreShrink) {
OS.InvalidateRect(handle, &rect, true);
break;
}
}
}
if (items is null)
break;
/*
* Bug in Windows. If the lParam field of TVITEM
* is changed during custom draw using TVM_SETITEM,
* the lItemlParam field of the NMTVCUSTOMDRAW struct
* is not updated until the next custom draw. The
* fix is to query the field from the item instead
* of using the struct.
*/
auto id = lptvdi.item.lParam;
if ((style & SWT.VIRTUAL) !is 0) {
if (id is -1) {
TVITEM tvItem;
tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM;
tvItem.hItem = lptvdi.item.hItem;
OS.SendMessage(handle, OS.TVM_GETITEM, 0, &tvItem);
id = tvItem.lParam;
}
}
TreeItem item = _getItem(lptvdi.item.hItem, id);
/*
* Feature in Windows. When a new tree item is inserted
* using TVM_INSERTITEM, a TVN_GETDISPINFO is sent before
* TVM_INSERTITEM returns and before the item is added to
* the items array. The fix is to check for null.
*
* NOTE: This only happens on XP with the version 6.00 of
* COMCTL32.DLL.
*
* Feature in Windows. When TVM_DELETEITEM is called with
* TVI_ROOT to remove all items from a tree, under certain
* circumstances, the tree sends TVN_GETDISPINFO for items
* that are about to be disposed. The fix is to check for
* disposed items.
*/
if (item is null)
break;
if (item.isDisposed())
break;
if (!item.cached) {
if ((style & SWT.VIRTUAL) !is 0) {
if (!checkData(item, false))
break;
}
if (painted)
item.cached = true;
}
.LRESULT index = 0;
if (hwndHeader !is null) {
index = OS.SendMessage(hwndHeader, OS.HDM_ORDERTOINDEX, 0, 0);
}
if ((lptvdi.item.mask & OS.TVIF_TEXT) !is 0) {
String string = null;
if (index is 0) {
string = item.text;
}
else {
String[] strings = item.strings;
if (strings !is null)
string = strings[index];
}
if (string !is null) {
StringT buffer = StrToTCHARs(getCodePage(), string, false);
auto byteCount = Math.min(buffer.length,
lptvdi.item.cchTextMax - 1) * TCHAR.sizeof;
OS.MoveMemory(lptvdi.item.pszText, buffer.ptr, byteCount);
auto st = byteCount / TCHAR.sizeof;
lptvdi.item.pszText[st .. st + 1] = 0;
//OS.MoveMemory (lptvdi.pszText + byteCount, new byte [TCHAR.sizeof], TCHAR.sizeof);
lptvdi.item.cchTextMax = cast(int) /*64bit*/ Math.min(lptvdi.item.cchTextMax,
string.length + 1);
}
}
if ((lptvdi.item.mask & (OS.TVIF_IMAGE | OS.TVIF_SELECTEDIMAGE)) !is 0) {
Image image = null;
if (index is 0) {
image = item.image;
}
else {
Image[] images = item.images;
if (images !is null)
image = images[index];
}
lptvdi.item.iImage = lptvdi.item.iSelectedImage = OS.I_IMAGENONE;
if (image !is null) {
lptvdi.item.iImage = lptvdi.item.iSelectedImage = imageIndex(image,
cast(int) /*64bit*/ index);
}
if (explorerTheme && OS.IsWindowEnabled(handle)) {
if (findImageControl() !is null) {
lptvdi.item.iImage = lptvdi.item.iSelectedImage = OS.I_IMAGENONE;
}
}
}
//OS.MoveMemory (cast(void*)lParam, lptvdi, NMTVDISPINFO.sizeof);
break;
}
case OS.NM_CUSTOMDRAW: {
if (hdr.hwndFrom is hwndHeader)
break;
if (hooks(SWT.MeasureItem)) {
if (hwndHeader is null)
createParent();
}
if (!customDraw && findImageControl() is null) {
if (OS.COMCTL32_MAJOR >= 6 && OS.IsAppThemed()) {
if (sortColumn is null || sortDirection is SWT.NONE) {
break;
}
}
}
NMTVCUSTOMDRAW* nmcd = cast(NMTVCUSTOMDRAW*) lParam;
//OS.MoveMemory (nmcd, lParam, NMTVCUSTOMDRAW.sizeof);
switch (nmcd.nmcd.dwDrawStage) {
case OS.CDDS_PREPAINT:
return CDDS_PREPAINT(nmcd, wParam, lParam);
case OS.CDDS_ITEMPREPAINT:
return CDDS_ITEMPREPAINT(nmcd, wParam, lParam);
case OS.CDDS_ITEMPOSTPAINT:
return CDDS_ITEMPOSTPAINT(nmcd, wParam, lParam);
case OS.CDDS_POSTPAINT:
return CDDS_POSTPAINT(nmcd, wParam, lParam);
default:
}
break;
}
case OS.NM_DBLCLK: {
/*
* When the user double clicks on a tree item
* or a line beside the item, the window proc
* for the tree collapses or expand the branch.
* When application code associates an action
* with double clicking, then the tree expand
* is unexpected and unwanted. The fix is to
* avoid the operation by testing to see whether
* the mouse was inside a tree item.
*/
if (hooks(SWT.MeasureItem))
return LRESULT.ONE;
if (hooks(SWT.DefaultSelection)) {
POINT pt;
int pos = OS.GetMessagePos();
OS.POINTSTOPOINT(pt, pos);
OS.ScreenToClient(handle, &pt);
TVHITTESTINFO lpht;
lpht.pt.x = pt.x;
lpht.pt.y = pt.y;
OS.SendMessage(handle, OS.TVM_HITTEST, 0, &lpht);
if (lpht.hItem !is null && (lpht.flags & OS.TVHT_ONITEM) !is 0) {
return LRESULT.ONE;
}
}
break;
}
/*
* Bug in Windows. On Vista, when TVM_SELECTITEM is called
* with TVGN_CARET in order to set the selection, for some
* reason, Windows deselects the previous two items that
* were selected. The fix is to stop the selection from
* changing on all but the item that is supposed to be
* selected.
*/
case OS.TVN_ITEMCHANGINGA:
case OS.TVN_ITEMCHANGINGW: {
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0)) {
if ((style & SWT.MULTI) !is 0) {
if (hSelect !is null) {
NMTVITEMCHANGE* pnm = cast(NMTVITEMCHANGE*) lParam;
//OS.MoveMemory (pnm, lParam, NMTVITEMCHANGE.sizeof);
if (hSelect is pnm.hItem)
break;
return LRESULT.ONE;
}
}
}
break;
}
case OS.TVN_SELCHANGINGA:
case OS.TVN_SELCHANGINGW: {
if ((style & SWT.MULTI) !is 0) {
if (lockSelection) {
/* Save the old selection state for both items */
auto treeView = cast(NMTREEVIEW*) lParam;
TVITEM* tvItem = &treeView.itemOld;
oldSelected = (tvItem.state & OS.TVIS_SELECTED) !is 0;
tvItem = &treeView.itemNew;
newSelected = (tvItem.state & OS.TVIS_SELECTED) !is 0;
}
}
if (!ignoreSelect && !ignoreDeselect) {
hAnchor = null;
if ((style & SWT.MULTI) !is 0)
deselectAll();
}
break;
}
case OS.TVN_SELCHANGEDA:
case OS.TVN_SELCHANGEDW: {
NMTREEVIEW* treeView = null;
if ((style & SWT.MULTI) !is 0) {
if (lockSelection) {
/* Restore the old selection state of both items */
if (oldSelected) {
if (treeView is null) {
treeView = cast(NMTREEVIEW*) lParam;
}
TVITEM tvItem = treeView.itemOld;
tvItem.mask = OS.TVIF_STATE;
tvItem.stateMask = OS.TVIS_SELECTED;
tvItem.state = OS.TVIS_SELECTED;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
if (!newSelected && ignoreSelect) {
if (treeView is null) {
treeView = cast(NMTREEVIEW*) lParam;
}
TVITEM tvItem = treeView.itemNew;
tvItem.mask = OS.TVIF_STATE;
tvItem.stateMask = OS.TVIS_SELECTED;
tvItem.state = 0;
OS.SendMessage(handle, OS.TVM_SETITEM, 0, &tvItem);
}
}
}
if (!ignoreSelect) {
if (treeView is null) {
treeView = cast(NMTREEVIEW*) lParam;
}
TVITEM tvItem = treeView.itemNew;
hAnchor = tvItem.hItem;
Event event = new Event();
event.item = _getItem(&tvItem.hItem, tvItem.lParam);
postEvent(SWT.Selection, event);
}
updateScrollBar();
break;
}
case OS.TVN_ITEMEXPANDINGA:
case OS.TVN_ITEMEXPANDINGW: {
bool runExpanded = false;
if ((style & SWT.VIRTUAL) !is 0)
style &= ~SWT.DOUBLE_BUFFERED;
if (hooks(SWT.EraseItem) || hooks(SWT.PaintItem))
style &= ~SWT.DOUBLE_BUFFERED;
if (findImageControl() !is null && drawCount is 0 && OS.IsWindowVisible(handle)) {
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 0, 0);
}
/*
* Bug in Windows. When TVM_SETINSERTMARK is used to set
* an insert mark for a tree and an item is expanded or
* collapsed near the insert mark, the tree does not redraw
* the insert mark properly. The fix is to hide and show
* the insert mark whenever an item is expanded or collapsed.
*/
if (hInsert !is null) {
OS.SendMessage(handle, OS.TVM_SETINSERTMARK, 0, 0);
}
if (!ignoreExpand) {
NMTREEVIEW* treeView = cast(NMTREEVIEW*) lParam;
TVITEM* tvItem = &treeView.itemNew;
/*
* Feature in Windows. In some cases, TVM_ITEMEXPANDING
* is sent from within TVM_DELETEITEM for the tree item
* being destroyed. By the time the message is sent,
* the item has already been removed from the list of
* items. The fix is to check for null.
*/
if (items is null)
break;
TreeItem item = _getItem(tvItem.hItem, tvItem.lParam);
if (item is null)
break;
Event event = new Event();
event.item = item;
switch (treeView.action) {
case OS.TVE_EXPAND:
/*
* Bug in Windows. When the numeric keypad asterisk
* key is used to expand every item in the tree, Windows
* sends TVN_ITEMEXPANDING to items in the tree that
* have already been expanded. The fix is to detect
* that the item is already expanded and ignore the
* notification.
*/
if ((tvItem.state & OS.TVIS_EXPANDED) is 0) {
sendEvent(SWT.Expand, event);
if (isDisposed())
return LRESULT.ZERO;
}
break;
case OS.TVE_COLLAPSE:
sendEvent(SWT.Collapse, event);
if (isDisposed())
return LRESULT.ZERO;
break;
default:
}
/*
* Bug in Windows. When all of the items are deleted during
* TVN_ITEMEXPANDING, Windows does not send TVN_ITEMEXPANDED.
* The fix is to detect this case and run the TVN_ITEMEXPANDED
* code in this method.
*/
auto hFirstItem = cast(HANDLE) OS.SendMessage(handle,
OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, tvItem.hItem);
runExpanded = hFirstItem is null;
}
if (!runExpanded)
break;
//FALL THROUGH
goto case;
}
case OS.TVN_ITEMEXPANDEDA:
case OS.TVN_ITEMEXPANDEDW: {
if ((style & SWT.VIRTUAL) !is 0)
style |= SWT.DOUBLE_BUFFERED;
if (hooks(SWT.EraseItem) || hooks(SWT.PaintItem))
style |= SWT.DOUBLE_BUFFERED;
if (findImageControl() !is null && drawCount is 0 /*&& OS.IsWindowVisible (handle)*/ ) {
OS.DefWindowProc(handle, OS.WM_SETREDRAW, 1, 0);
OS.InvalidateRect(handle, null, true);
}
/*
* Bug in Windows. When TVM_SETINSERTMARK is used to set
* an insert mark for a tree and an item is expanded or
* collapsed near the insert mark, the tree does not redraw
* the insert mark properly. The fix is to hide and show
* the insert mark whenever an item is expanded or collapsed.
*/
if (hInsert !is null) {
OS.SendMessage(handle, OS.TVM_SETINSERTMARK, insertAfter ? 1 : 0, hInsert);
}
/*
* Bug in Windows. When a tree item that has an image
* with alpha is expanded or collapsed, the area where
* the image is drawn is not erased before it is drawn.
* This means that the image gets darker each time.
* The fix is to redraw the item.
*/
if (!OS.IsWinCE && OS.COMCTL32_MAJOR >= 6) {
if (imageList !is null) {
NMTREEVIEW* treeView = cast(NMTREEVIEW*) lParam;
TVITEM* tvItem = &treeView.itemNew;
if (tvItem.hItem !is null) {
int bits = OS.GetWindowLong(handle, OS.GWL_STYLE);
if ((bits & OS.TVS_FULLROWSELECT) is 0) {
RECT rect;
if (OS.TreeView_GetItemRect(handle, tvItem.hItem, &rect, false)) {
OS.InvalidateRect(handle, &rect, true);
}
}
}
}
}
updateScrollBar();
break;
}
case OS.TVN_BEGINDRAGA:
case OS.TVN_BEGINDRAGW:
if (OS.GetKeyState(OS.VK_LBUTTON) >= 0)
break;
//FALL THROUGH
goto case;
case OS.TVN_BEGINRDRAGA:
case OS.TVN_BEGINRDRAGW: {
dragStarted = true;
NMTREEVIEW* treeView = cast(NMTREEVIEW*) lParam;
TVITEM* tvItem = &treeView.itemNew;
if (tvItem.hItem !is null && (tvItem.state & OS.TVIS_SELECTED) is 0) {
hSelect = tvItem.hItem;
ignoreSelect = ignoreDeselect = true;
OS.SendMessage(handle, OS.TVM_SELECTITEM, OS.TVGN_CARET, tvItem.hItem);
ignoreSelect = ignoreDeselect = false;
hSelect = null;
}
break;
}
case OS.NM_RECOGNIZEGESTURE: {
/*
* Feature in Pocket PC. The tree and table controls detect the tap
* and hold gesture by default. They send a GN_CONTEXTMENU message to show
* the popup menu. This default behaviour is unwanted on Pocket PC 2002
* when no menu has been set, as it still draws a red circle. The fix
* is to disable this default behaviour when no menu is set by returning
* TRUE when receiving the Pocket PC 2002 specific NM_RECOGNIZEGESTURE
* message.
*/
if (OS.IsPPC) {
bool hasMenu = menu !is null && !menu.isDisposed();
if (!hasMenu && !hooks(SWT.MenuDetect))
return LRESULT.ONE;
}
break;
}
case OS.GN_CONTEXTMENU: {
if (OS.IsPPC) {
bool hasMenu = menu !is null && !menu.isDisposed();
if (hasMenu || hooks(SWT.MenuDetect)) {
NMRGINFO* nmrg = cast(NMRGINFO*) lParam;
//OS.MoveMemory (nmrg, lParam, NMRGINFO.sizeof);
showMenu(nmrg.x, nmrg.y);
gestureCompleted = true;
return LRESULT.ONE;
}
}
break;
}
default:
}
return super.wmNotifyChild(hdr, wParam, lParam);
}
LRESULT wmNotifyHeader(NMHDR* hdr, WPARAM wParam, LPARAM lParam) {
/*
* Feature in Windows. On NT, the automatically created
* header control is created as a UNICODE window, not an
* ANSI window despite the fact that the parent is created
* as an ANSI window. This means that it sends UNICODE
* notification messages to the parent window on NT for
* no good reason. The data and size in the NMHEADER and
* HDITEM structs is identical between the platforms so no
* different message is actually necessary. Despite this,
* Windows sends different messages. The fix is to look
* for both messages, despite the platform. This works
* because only one will be sent on either platform, never
* both.
*/
switch (hdr.code) {
case OS.HDN_BEGINTRACKW:
case OS.HDN_BEGINTRACKA:
case OS.HDN_DIVIDERDBLCLICKW:
case OS.HDN_DIVIDERDBLCLICKA: {
NMHEADER* phdn = cast(NMHEADER*) lParam;
TreeColumn column = columns[phdn.iItem];
if (column !is null && !column.getResizable()) {
return LRESULT.ONE;
}
ignoreColumnMove = true;
switch (hdr.code) {
case OS.HDN_DIVIDERDBLCLICKW:
case OS.HDN_DIVIDERDBLCLICKA:
if (column !is null)
column.pack();
goto default;
default:
}
break;
}
case OS.NM_RELEASEDCAPTURE: {
if (!ignoreColumnMove) {
for (int i = 0; i < columnCount; i++) {
TreeColumn column = columns[i];
column.updateToolTip(i);
}
updateImageList();
}
ignoreColumnMove = false;
break;
}
case OS.HDN_BEGINDRAG: {
if (ignoreColumnMove)
return LRESULT.ONE;
NMHEADER* phdn = cast(NMHEADER*) lParam;
if (phdn.iItem !is -1) {
TreeColumn column = columns[phdn.iItem];
if (column !is null && !column.getMoveable()) {
ignoreColumnMove = true;
return LRESULT.ONE;
}
}
break;
}
case OS.HDN_ENDDRAG: {
NMHEADER* phdn = cast(NMHEADER*) lParam;
if (phdn.iItem !is -1 && phdn.pitem !is null) {
HDITEM* pitem = cast(HDITEM*) phdn.pitem;
if ((pitem.mask & OS.HDI_ORDER) !is 0 && pitem.iOrder !is -1) {
int[] order = new int[columnCount];
OS.SendMessage(hwndHeader, OS.HDM_GETORDERARRAY, columnCount, order.ptr);
int index = 0;
while (index < order.length) {
if (order[index] is phdn.iItem)
break;
index++;
}
if (index is order.length)
index = 0;
if (index is pitem.iOrder)
break;
int start = Math.min(index, pitem.iOrder);
int end = Math.max(index, pitem.iOrder);
RECT rect, headerRect;
OS.GetClientRect(handle, &rect);
OS.SendMessage(hwndHeader, OS.HDM_GETITEMRECT, order[start], &headerRect);
rect.left = Math.max(rect.left, headerRect.left);
OS.SendMessage(hwndHeader, OS.HDM_GETITEMRECT, order[end], &headerRect);
rect.right = Math.min(rect.right, headerRect.right);
OS.InvalidateRect(handle, &rect, true);
ignoreColumnMove = false;
for (int i = start; i <= end; i++) {
TreeColumn column = columns[order[i]];
if (!column.isDisposed()) {
column.postEvent(SWT.Move);
}
}
}
}
break;
}
case OS.HDN_ITEMCHANGINGW:
case OS.HDN_ITEMCHANGINGA: {
NMHEADER* phdn = cast(NMHEADER*) lParam;
if (phdn.pitem !is null) {
HDITEM* newItem = cast(HDITEM*) phdn.pitem;
if ((newItem.mask & OS.HDI_WIDTH) !is 0) {
RECT rect;
OS.GetClientRect(handle, &rect);
HDITEM oldItem;
oldItem.mask = OS.HDI_WIDTH;
OS.SendMessage(hwndHeader, OS.HDM_GETITEM, phdn.iItem, &oldItem);
int deltaX = newItem.cxy - oldItem.cxy;
RECT headerRect;
OS.SendMessage(hwndHeader, OS.HDM_GETITEMRECT, phdn.iItem, &headerRect);
int gridWidth = linesVisible ? GRID_WIDTH : 0;
rect.left = headerRect.right - gridWidth;
int newX = rect.left + deltaX;
rect.right = Math.max(rect.right, rect.left + Math.abs(deltaX));
if (explorerTheme || (findImageControl() !is null
|| hooks(SWT.MeasureItem)
|| hooks(SWT.EraseItem) || hooks(SWT.PaintItem))) {
rect.left -= OS.GetSystemMetrics(OS.SM_CXFOCUSBORDER);
OS.InvalidateRect(handle, &rect, true);
OS.OffsetRect(&rect, deltaX, 0);
OS.InvalidateRect(handle, &rect, true);
}
else {
int flags = OS.SW_INVALIDATE | OS.SW_ERASE;
OS.ScrollWindowEx(handle, deltaX, 0, &rect, null, null, null, flags);
}
if (OS.SendMessage(hwndHeader, OS.HDM_ORDERTOINDEX, phdn.iItem, 0) !is 0) {
rect.left = headerRect.left;
rect.right = newX;
OS.InvalidateRect(handle, &rect, true);
}
setScrollWidth();
}
}
break;
}
case OS.HDN_ITEMCHANGEDW:
case OS.HDN_ITEMCHANGEDA: {
NMHEADER* phdn = cast(NMHEADER*) lParam;
if (phdn.pitem !is null) {
HDITEM* pitem = cast(HDITEM*) phdn.pitem;
if ((pitem.mask & OS.HDI_WIDTH) !is 0) {
if (ignoreColumnMove) {
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0)) {
int flags = OS.RDW_UPDATENOW | OS.RDW_ALLCHILDREN;
OS.RedrawWindow(handle, null, null, flags);
}
else {
if ((style & SWT.DOUBLE_BUFFERED) is 0) {
int oldStyle = style;
style |= SWT.DOUBLE_BUFFERED;
OS.UpdateWindow(handle);
style = oldStyle;
}
}
}
TreeColumn column = columns[phdn.iItem];
if (column !is null) {
column.updateToolTip(phdn.iItem);
column.sendEvent(SWT.Resize);
if (isDisposed())
return LRESULT.ZERO;
TreeColumn[] newColumns = new TreeColumn[columnCount];
System.arraycopy(columns, 0, newColumns, 0, columnCount);
int[] order = new int[columnCount];
OS.SendMessage(hwndHeader, OS.HDM_GETORDERARRAY,
columnCount, order.ptr);
bool moved = false;
for (int i = 0; i < columnCount; i++) {
TreeColumn nextColumn = newColumns[order[i]];
if (moved && !nextColumn.isDisposed()) {
nextColumn.updateToolTip(order[i]);
nextColumn.sendEvent(SWT.Move);
}
if (nextColumn is column)
moved = true;
}
}
}
setScrollWidth();
}
break;
}
case OS.HDN_ITEMCLICKW:
case OS.HDN_ITEMCLICKA: {
NMHEADER* phdn = cast(NMHEADER*) lParam;
TreeColumn column = columns[phdn.iItem];
if (column !is null) {
column.postEvent(SWT.Selection);
}
break;
}
case OS.HDN_ITEMDBLCLICKW:
case OS.HDN_ITEMDBLCLICKA: {
NMHEADER* phdn = cast(NMHEADER*) lParam;
TreeColumn column = columns[phdn.iItem];
if (column !is null) {
column.postEvent(SWT.DefaultSelection);
}
break;
}
default:
}
return null;
}
LRESULT wmNotifyToolTip(NMHDR* hdr, WPARAM wParam, LPARAM lParam) {
if (OS.IsWinCE)
return null;
switch (hdr.code) {
case OS.NM_CUSTOMDRAW: {
NMTTCUSTOMDRAW* nmcd = cast(NMTTCUSTOMDRAW*) lParam;
return wmNotifyToolTip(nmcd, lParam);
}
case OS.TTN_SHOW: {
LRESULT result = super.wmNotify(hdr, wParam, lParam);
if (result !is null)
return result;
int pos = OS.GetMessagePos();
POINT pt;
OS.POINTSTOPOINT(pt, pos);
OS.ScreenToClient(handle, &pt);
int index;
TreeItem item;
RECT* cellRect, itemRect;
if (findCell(pt.x, pt.y, item, index, cellRect, itemRect)) {
RECT* toolRect = toolTipRect(itemRect);
OS.MapWindowPoints(handle, null, cast(POINT*) toolRect, 2);
int width = toolRect.right - toolRect.left;
int height = toolRect.bottom - toolRect.top;
int flags = OS.SWP_NOACTIVATE | OS.SWP_NOZORDER | OS.SWP_NOSIZE;
if (isCustomToolTip())
flags &= ~OS.SWP_NOSIZE;
SetWindowPos(itemToolTipHandle, null, toolRect.left,
toolRect.top, width, height, flags);
return LRESULT.ONE;
}
return result;
}
default:
}
return null;
}
LRESULT wmNotifyToolTip(NMTTCUSTOMDRAW* nmcd, LPARAM lParam) {
if (OS.IsWinCE)
return null;
switch (nmcd.nmcd.dwDrawStage) {
case OS.CDDS_PREPAINT: {
if (isCustomToolTip()) {
//TEMPORARY CODE
//nmcd.uDrawFlags |= OS.DT_CALCRECT;
//OS.MoveMemory (lParam, nmcd, NMTTCUSTOMDRAW.sizeof);
if (!OS.IsWinCE && OS.WIN32_VERSION < OS.VERSION(6, 0)) {
OS.SetTextColor(nmcd.nmcd.hdc, OS.GetSysColor(OS.COLOR_INFOBK));
}
return new LRESULT(OS.CDRF_NOTIFYPOSTPAINT | OS.CDRF_NEWFONT);
}
break;
}
case OS.CDDS_POSTPAINT: {
if (!OS.IsWinCE && OS.WIN32_VERSION < OS.VERSION(6, 0)) {
OS.SetTextColor(nmcd.nmcd.hdc, OS.GetSysColor(OS.COLOR_INFOTEXT));
}
if (OS.SendMessage(itemToolTipHandle, OS.TTM_GETCURRENTTOOL, 0, 0) !is 0) {
TOOLINFO lpti;
lpti.cbSize = OS.TOOLINFO_sizeof;
if (OS.SendMessage(itemToolTipHandle, OS.TTM_GETCURRENTTOOL, 0, &lpti) !is 0) {
int index;
TreeItem item;
RECT* cellRect, itemRect;
int pos = OS.GetMessagePos();
POINT pt;
OS.POINTSTOPOINT(pt, pos);
OS.ScreenToClient(handle, &pt);
if (findCell(pt.x, pt.y, item, index, cellRect, itemRect)) {
auto hDC = OS.GetDC(handle);
auto hFont = item.fontHandle(index);
if (hFont is cast(HFONT)-1)
hFont = cast(HFONT) OS.SendMessage(handle, OS.WM_GETFONT, 0, 0);
HFONT oldFont = OS.SelectObject(hDC, hFont);
LRESULT result = null;
bool drawForeground = true;
cellRect = item.getBounds(index, true, true, false, false, false, hDC);
if (hooks(SWT.EraseItem)) {
Event event = sendEraseItemEvent(item, nmcd, index, cellRect);
if (isDisposed() || item.isDisposed())
break;
if (event.doit) {
drawForeground = (event.detail & SWT.FOREGROUND) !is 0;
}
else {
drawForeground = false;
}
}
if (drawForeground) {
int nSavedDC = OS.SaveDC(nmcd.nmcd.hdc);
int gridWidth = getLinesVisible() ? Table.GRID_WIDTH : 0;
RECT* insetRect = toolTipInset(cellRect);
OS.SetWindowOrgEx(nmcd.nmcd.hdc,
insetRect.left, insetRect.top, null);
GCData data = new GCData();
data.device = display;
data.foreground = OS.GetTextColor(nmcd.nmcd.hdc);
data.background = OS.GetBkColor(nmcd.nmcd.hdc);
data.font = Font.win32_new(display, hFont);
GC gc = GC.win32_new(nmcd.nmcd.hdc, data);
int x = cellRect.left + INSET;
if (index !is 0)
x -= gridWidth;
Image image = item.getImage(index);
if (image !is null || index is 0) {
Point size = getImageSize();
RECT* imageRect = item.getBounds(index,
false, true, false, false, false, hDC);
if (imageList is null)
size.x = imageRect.right - imageRect.left;
if (image !is null) {
Rectangle rect = image.getBounds();
gc.drawImage(image, rect.x, rect.y, rect.width,
rect.height, x, imageRect.top, size.x, size.y);
x += INSET + (index is 0 ? 1 : 0);
}
x += size.x;
}
else {
x += INSET;
}
String string = item.getText(index);
if (string !is null) {
int flags = OS.DT_NOPREFIX | OS.DT_SINGLELINE | OS.DT_VCENTER;
TreeColumn column = columns !is null ? columns[index] : null;
if (column !is null) {
if ((column.style & SWT.CENTER) !is 0)
flags |= OS.DT_CENTER;
if ((column.style & SWT.RIGHT) !is 0)
flags |= OS.DT_RIGHT;
}
StringT buffer = StrToTCHARs(getCodePage(), string, false);
RECT textRect;
OS.SetRect(&textRect, x, cellRect.top,
cellRect.right, cellRect.bottom);
OS.DrawText(nmcd.nmcd.hdc, buffer.ptr,
cast(int) /*64bit*/ buffer.length, &textRect, flags);
}
gc.dispose();
OS.RestoreDC(nmcd.nmcd.hdc, nSavedDC);
}
if (hooks(SWT.PaintItem)) {
itemRect = item.getBounds(index, true, true,
false, false, false, hDC);
sendPaintItemEvent(item, nmcd, index, itemRect);
}
OS.SelectObject(hDC, oldFont);
OS.ReleaseDC(handle, hDC);
if (result !is null)
return result;
}
break;
}
}
break;
}
default:
}
return null;
}
}
|
D
|
module benchmark.type.fiber;
import benchmark.benchmark;
import benchmark.server, benchmark.client;
import std.socket, std.stdio, std.concurrency;
import core.thread;
class FiberBenchmark : AbstractBenchmark
{
public:
this(InternetAddress address)
{
super(address);
}
override void doBenchmark()
{
auto scheduler = new FiberScheduler;
scheduler.start({
auto server = new Server(address);
auto serverSocket = server.start();
auto sset = new SocketSet;
for (;;sset.reset()) {
sset.add(serverSocket);
Fiber.yield;
if (Socket.select(sset, null, null) <= 0) {
writeln("End of server socket");
break;
}
if (sset.isSet(serverSocket)) {
auto clientSocket = serverSocket.accept();
Fiber.yield;
scheduler.spawn({
auto client = new Client(clientSocket);
Fiber.yield;
client.readRequest();
Fiber.yield;
client.writeAnswer();
Fiber.yield;
client.close();
});
}
Fiber.yield;
}
});
}
}
|
D
|
a cord fastened around the neck with an ornamental clasp and worn as a necktie
long heavy knife with a single edge
|
D
|
/Users/setiyadi/Projects/Xcode/CodeTest-303Software/Carthage/Checkouts/SwiftyJSON/Build/Intermediates/SwiftyJSON.build/Release/SwiftyJSON\ OSX.build/Objects-normal/x86_64/SwiftyJSON.o : /Users/setiyadi/Projects/Xcode/CodeTest-303Software/Carthage/Checkouts/SwiftyJSON/Source/SwiftyJSON.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Users/setiyadi/Projects/Xcode/CodeTest-303Software/Carthage/Checkouts/SwiftyJSON/Source/SwiftyJSON.h /Users/setiyadi/Projects/Xcode/CodeTest-303Software/Carthage/Checkouts/SwiftyJSON/Build/Intermediates/SwiftyJSON.build/Release/SwiftyJSON\ OSX.build/unextended-module.modulemap /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/Darwin.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/ObjectiveC.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/IOKit.swiftmodule
/Users/setiyadi/Projects/Xcode/CodeTest-303Software/Carthage/Checkouts/SwiftyJSON/Build/Intermediates/SwiftyJSON.build/Release/SwiftyJSON\ OSX.build/Objects-normal/x86_64/SwiftyJSON~partial.swiftmodule : /Users/setiyadi/Projects/Xcode/CodeTest-303Software/Carthage/Checkouts/SwiftyJSON/Source/SwiftyJSON.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Users/setiyadi/Projects/Xcode/CodeTest-303Software/Carthage/Checkouts/SwiftyJSON/Source/SwiftyJSON.h /Users/setiyadi/Projects/Xcode/CodeTest-303Software/Carthage/Checkouts/SwiftyJSON/Build/Intermediates/SwiftyJSON.build/Release/SwiftyJSON\ OSX.build/unextended-module.modulemap /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/Darwin.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/ObjectiveC.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/IOKit.swiftmodule
/Users/setiyadi/Projects/Xcode/CodeTest-303Software/Carthage/Checkouts/SwiftyJSON/Build/Intermediates/SwiftyJSON.build/Release/SwiftyJSON\ OSX.build/Objects-normal/x86_64/SwiftyJSON~partial.swiftdoc : /Users/setiyadi/Projects/Xcode/CodeTest-303Software/Carthage/Checkouts/SwiftyJSON/Source/SwiftyJSON.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Users/setiyadi/Projects/Xcode/CodeTest-303Software/Carthage/Checkouts/SwiftyJSON/Source/SwiftyJSON.h /Users/setiyadi/Projects/Xcode/CodeTest-303Software/Carthage/Checkouts/SwiftyJSON/Build/Intermediates/SwiftyJSON.build/Release/SwiftyJSON\ OSX.build/unextended-module.modulemap /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/Darwin.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/ObjectiveC.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/IOKit.swiftmodule
|
D
|
/**
* D header file for GNU stdio.
*
* Copyright: Danny Milosavljevic 2014
* License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
* Authors: Danny Milosavljevic
*/
module core.sys.linux.stdio;
version (CRuntime_Glibc):
public import core.sys.posix.stdio;
import core.sys.posix.sys.types : ssize_t, off64_t = off_t;
import core.sys.linux.config : __USE_FILE_OFFSET64;
import core.stdc.stdio : FILE;
import core.stdc.stddef : wchar_t;
@system:
extern(C) nothrow
{
alias ssize_t function(void *cookie, char *buf, size_t size) cookie_read_function_t;
alias ssize_t function(void *cookie, const(char) *buf, size_t size) cookie_write_function_t;
alias int function(void *cookie, off64_t *offset, int whence) cookie_seek_function_t;
alias int function(void *cookie) cookie_close_function_t;
struct cookie_io_functions_t
{
cookie_read_function_t read;
cookie_write_function_t write;
cookie_seek_function_t seek;
cookie_close_function_t close;
}
FILE* fopencookie(in void* cookie, in char* mode, cookie_io_functions_t io_funcs);
void setbuffer(FILE *stream, char *buf, size_t size); // note: _DEFAULT_SOURCE
}
unittest
{
static int flag = 0;
static int written = 0;
static int closed = 0;
// Note: this test needs to run on both a 32 and a 64 bit machine, both have to pass.
import core.stdc.errno : errno, EBADF;
//import core.sys.posix.sys.stat : off64_t;
import core.stdc.stdio : FILE, fflush, fileno, fprintf, fgetc, EOF, fclose;
import core.stdc.string : memcpy, memset;
extern (C) ssize_t specialRead(void *cookie, char *buf, size_t size) nothrow
{
memset(buf, 'a', size);
return size;
}
extern (C) int specialClose(void* cookie) nothrow
{
++closed;
return 0;
}
extern (C) ssize_t specialWrite(void *cookie, const(char) *buf, size_t size) nothrow
{
int* c = cast(int*) cookie;
flag = *c;
written += size;
return size;
}
int dummy = 42;
cookie_io_functions_t fns =
{
read: &specialRead,
write: &specialWrite,
close: &specialClose,
};
FILE* f = fopencookie(&dummy, "r+", fns);
assert(f !is null);
//File.open();
//auto g = File(f);
assert(fileno(f) == -1 && errno == EBADF);
assert(fprintf(f, "hello") == "hello".length);
//assert(errno == EBADF);
assert(fflush(f) == 0);
assert(written == "hello".length);
// Note: do not swap reading and writing here.
int c = 0;
while ((c = fgetc(f)) != EOF)
{
assert(c == 'a');
break; // endless otherwise
}
assert(c == 'a');
assert(fclose(f) == 0);
assert(closed == 1);
assert(flag == dummy);
//stdin.getFP();
//assert(stdin.fileno() == 0);
}
unittest
{ /* setbuffer */
char buf;
int c;
byte[10] dummy = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
FILE* f = fmemopen(dummy.ptr, 10, "r");
assert(f !is null);
setbuffer(f, &buf, 1);
assert(fgetc(f) == 1);
assert(fgetc(f) == 2);
assert(fgetc(f) == 3);
assert(fgetc(f) == 4);
assert(fclose(f) == 0);
}
|
D
|
// Written in the D programming language.
/**
* Templates with which to extract information about types and symbols at
* compile time.
*
* <script type="text/javascript">inhibitQuickIndex = 1</script>
*
* $(BOOKTABLE ,
* $(TR $(TH Category) $(TH Templates))
* $(TR $(TD Symbol Name _traits) $(TD
* $(LREF packageName)
* $(LREF moduleName)
* $(LREF fullyQualifiedName)
* ))
* $(TR $(TD Function _traits) $(TD
* $(LREF ReturnType)
* $(LREF ParameterTypeTuple)
* $(LREF arity)
* $(LREF ParameterStorageClassTuple)
* $(LREF ParameterIdentifierTuple)
* $(LREF ParameterDefaultValueTuple)
* $(LREF functionAttributes)
* $(LREF isSafe)
* $(LREF isUnsafe)
* $(LREF functionLinkage)
* $(LREF variadicFunctionStyle)
* $(LREF FunctionTypeOf)
* $(LREF SetFunctionAttributes)
* ))
* $(TR $(TD Aggregate Type _traits) $(TD
* $(LREF isNested)
* $(LREF hasNested)
* $(LREF FieldTypeTuple)
* $(LREF RepresentationTypeTuple)
* $(LREF hasAliasing)
* $(LREF hasIndirections)
* $(LREF hasUnsharedAliasing)
* $(LREF hasElaborateCopyConstructor)
* $(LREF hasElaborateAssign)
* $(LREF hasElaborateDestructor)
* $(LREF hasMember)
* $(LREF EnumMembers)
* $(LREF BaseTypeTuple)
* $(LREF BaseClassesTuple)
* $(LREF InterfacesTuple)
* $(LREF TransitiveBaseTypeTuple)
* $(LREF MemberFunctionsTuple)
* $(LREF TemplateOf)
* $(LREF TemplateArgsOf)
* $(LREF classInstanceAlignment)
* ))
* $(TR $(TD Type Conversion) $(TD
* $(LREF CommonType)
* $(LREF ImplicitConversionTargets)
* $(LREF isImplicitlyConvertible)
* $(LREF isAssignable)
* $(LREF isCovariantWith)
* ))
* <!--$(TR $(TD SomethingTypeOf) $(TD
* $(LREF BooleanTypeOf)
* $(LREF IntegralTypeOf)
* $(LREF FloatingPointTypeOf)
* $(LREF NumericTypeOf)
* $(LREF UnsignedTypeOf)
* $(LREF SignedTypeOf)
* $(LREF CharTypeOf)
* $(LREF StaticArrayTypeOf)
* $(LREF DynamicArrayTypeOf)
* $(LREF ArrayTypeOf)
* $(LREF StringTypeOf)
* $(LREF AssocArrayTypeOf)
* $(LREF BuiltinTypeOf)
* ))-->
* $(TR $(TD IsSomething) $(TD
* $(LREF isBoolean)
* $(LREF isIntegral)
* $(LREF isFloatingPoint)
* $(LREF isNumeric)
* $(LREF isScalarType)
* $(LREF isBasicType)
* $(LREF isUnsigned)
* $(LREF isSigned)
* $(LREF isSomeChar)
* $(LREF isSomeString)
* $(LREF isNarrowString)
* $(LREF isStaticArray)
* $(LREF isDynamicArray)
* $(LREF isArray)
* $(LREF isAssociativeArray)
* $(LREF isBuiltinType)
* $(LREF isPointer)
* $(LREF isAggregateType)
* ))
* $(TR $(TD xxx) $(TD
* $(LREF isIterable)
* $(LREF isMutable)
* $(LREF isInstanceOf)
* $(LREF isExpressionTuple)
* $(LREF isTypeTuple)
* $(LREF isFunctionPointer)
* $(LREF isDelegate)
* $(LREF isSomeFunction)
* $(LREF isCallable)
* $(LREF isAbstractFunction)
* $(LREF isFinalFunction)
* $(LREF isAbstractClass)
* $(LREF isFinalClass)
* ))
* $(TR $(TD General Types) $(TD
* $(LREF Unqual)
* $(LREF ForeachType)
* $(LREF OriginalType)
* $(LREF PointerTarget)
* $(LREF KeyType)
* $(LREF ValueType)
* $(LREF Unsigned)
* $(LREF Largest)
* $(LREF Signed)
* $(LREF unsigned)
* $(LREF mostNegative)
* ))
* $(TR $(TD Misc) $(TD
* $(LREF mangledName)
* $(LREF Select)
* $(LREF select)
* ))
* )
*
* 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),
* $(WEB klickverbot.at, David Nadlinger),
* Kenji Hara,
* Shoichi Kato
* 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.typetuple;
///////////////////////////////////////////////////////////////////////////////
// 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,
'i': FunctionAttribute.nogc
];
uint atts = 0;
// FuncAttrs --> FuncAttr | FuncAttr FuncAttrs
// FuncAttr --> empty | Na | Nb | Nc | Nd | Ne | Nf
// except 'Ng' == inout, because it is a qualifier of function type
while (mstr.length >= 2 && mstr[0] == 'N' && mstr[1] != 'g')
{
if (FunctionAttribute att = LOOKUP_ATTRIBUTE[ mstr[1] ])
{
atts |= att;
mstr = mstr[2 .. $];
}
else assert(0);
}
return Demangle!uint(atts, mstr);
}
alias IntegralTypeList = TypeTuple!(byte, ubyte, short, ushort, int, uint, long, ulong);
alias SignedIntTypeList = TypeTuple!(byte, short, int, long);
alias UnsignedIntTypeList = TypeTuple!(ubyte, ushort, uint, ulong);
alias FloatingPointTypeList = TypeTuple!(float, double, real);
alias ImaginaryTypeList = TypeTuple!(ifloat, idouble, ireal);
alias ComplexTypeList = TypeTuple!(cfloat, cdouble, creal);
alias NumericTypeList = TypeTuple!(IntegralTypeList, FloatingPointTypeList);
alias CharTypeList = TypeTuple!(char, wchar, dchar);
}
package
{
// Add specific qualifier to the given type T
template MutableOf(T) { alias MutableOf = T ; }
template InoutOf(T) { alias InoutOf = inout(T) ; }
template ConstOf(T) { alias ConstOf = const(T) ; }
template SharedOf(T) { alias SharedOf = shared(T) ; }
template SharedInoutOf(T) { alias SharedInoutOf = shared(inout(T)); }
template SharedConstOf(T) { alias SharedConstOf = shared(const(T)); }
template ImmutableOf(T) { alias ImmutableOf = immutable(T) ; }
unittest
{
static assert(is( MutableOf!int == int));
static assert(is( InoutOf!int == inout int));
static assert(is( ConstOf!int == const int));
static assert(is( SharedOf!int == shared int));
static assert(is(SharedInoutOf!int == shared inout int));
static assert(is(SharedConstOf!int == shared const int));
static assert(is( ImmutableOf!int == immutable int));
}
// Get qualifier template from the given type T
template QualifierOf(T)
{
static if (is(T == shared(const U), U)) alias QualifierOf = SharedConstOf;
else static if (is(T == const U , U)) alias QualifierOf = ConstOf;
else static if (is(T == shared(inout U), U)) alias QualifierOf = SharedInoutOf;
else static if (is(T == inout U , U)) alias QualifierOf = InoutOf;
else static if (is(T == immutable U , U)) alias QualifierOf = ImmutableOf;
else static if (is(T == shared U , U)) alias QualifierOf = SharedOf;
else alias QualifierOf = MutableOf;
}
unittest
{
alias Qual1 = QualifierOf!( int); static assert(is(Qual1!long == long));
alias Qual2 = QualifierOf!( inout int); static assert(is(Qual2!long == inout long));
alias Qual3 = QualifierOf!( const int); static assert(is(Qual3!long == const long));
alias Qual4 = QualifierOf!(shared int); static assert(is(Qual4!long == shared long));
alias Qual5 = QualifierOf!(shared inout int); static assert(is(Qual5!long == shared inout long));
alias Qual6 = QualifierOf!(shared const int); static assert(is(Qual6!long == shared const long));
alias Qual7 = QualifierOf!( immutable int); static assert(is(Qual7!long == immutable long));
}
}
version(unittest)
{
alias TypeQualifierList = TypeTuple!(MutableOf, ConstOf, SharedOf, SharedConstOf, ImmutableOf);
struct SubTypeOf(T)
{
T val;
alias val this;
}
}
private alias parentOf(alias sym) = Identity!(__traits(parent, sym));
private alias parentOf(alias sym : T!Args, alias T, Args...) = Identity!(__traits(parent, T));
/**
* Get the full package name for the given symbol.
* Example:
* ---
* import std.traits;
* static assert(packageName!packageName == "std");
* ---
*/
template packageName(alias T)
{
import std.algorithm : startsWith;
static if (__traits(compiles, parentOf!T))
enum parent = packageName!(parentOf!T);
else
enum string parent = null;
static if (T.stringof.startsWith("package "))
enum packageName = (parent.length ? parent ~ '.' : "") ~ T.stringof[8 .. $];
else static if (parent)
enum packageName = parent;
else
static assert(false, T.stringof ~ " has no parent");
}
unittest
{
import std.algorithm;
// Commented out because of dmd @@@BUG8922@@@
// static assert(packageName!std == "std"); // this package (currently: "std.std")
static assert(packageName!(std.traits) == "std"); // this module
static assert(packageName!packageName == "std"); // symbol in this module
static assert(packageName!(std.algorithm) == "std"); // other module from same package
import core.sync.barrier; // local import
static assert(packageName!core == "core");
static assert(packageName!(core.sync) == "core.sync");
static assert(packageName!Barrier == "core.sync");
struct X12287(T) { T i; }
static assert(packageName!(X12287!int.i) == "std");
}
version (none) version(unittest) //Please uncomment me when changing packageName to test global imports
{
import core.sync.barrier; // global import
static assert(packageName!core == "core");
static assert(packageName!(core.sync) == "core.sync");
static assert(packageName!Barrier == "core.sync");
}
/**
* Get the module name (including package) for the given symbol.
* Example:
* ---
* import std.traits;
* static assert(moduleName!moduleName == "std.traits");
* ---
*/
template moduleName(alias T)
{
import std.algorithm : startsWith;
static assert(!T.stringof.startsWith("package "), "cannot get the module name for a package");
static if (T.stringof.startsWith("module "))
{
static if (__traits(compiles, packageName!T))
enum packagePrefix = packageName!T ~ '.';
else
enum packagePrefix = "";
enum moduleName = packagePrefix ~ T.stringof[7..$];
}
else
alias moduleName = moduleName!(parentOf!T); // If you use enum, it will cause compiler ICE
}
unittest
{
import std.algorithm;
static assert(!__traits(compiles, moduleName!std));
static assert(moduleName!(std.traits) == "std.traits"); // this module
static assert(moduleName!moduleName == "std.traits"); // symbol in this module
static assert(moduleName!(std.algorithm) == "std.algorithm"); // other module
static assert(moduleName!(std.algorithm.map) == "std.algorithm"); // symbol in other module
import core.sync.barrier; // local import
static assert(!__traits(compiles, moduleName!(core.sync)));
static assert(moduleName!(core.sync.barrier) == "core.sync.barrier");
static assert(moduleName!Barrier == "core.sync.barrier");
struct X12287(T) { T i; }
static assert(moduleName!(X12287!int.i) == "std.traits");
}
version (none) version(unittest) //Please uncomment me when changing moduleName to test global imports
{
import core.sync.barrier; // global import
static assert(!__traits(compiles, moduleName!(core.sync)));
static assert(moduleName!(core.sync.barrier) == "core.sync.barrier");
static assert(moduleName!Barrier == "core.sync.barrier");
}
/***
* Get the fully qualified name of a type or a symbol. Can act as an intelligent type/symbol to string converter.
* Example:
* ---
* module mymodule;
* import std.traits;
* struct MyStruct {}
* static assert(fullyQualifiedName!(const MyStruct[]) == "const(mymodule.MyStruct[])");
* static assert(fullyQualifiedName!fullyQualifiedName == "std.traits.fullyQualifiedName");
* ---
*/
template fullyQualifiedName(T...)
if (T.length == 1)
{
static if (is(T))
enum fullyQualifiedName = fqnType!(T[0], false, false, false, false);
else
enum fullyQualifiedName = fqnSym!(T[0]);
}
version(unittest)
{
// Used for both fqnType and fqnSym unittests
private struct QualifiedNameTests
{
struct Inner
{
const int opCmp(ref const Inner) { return 0; }
}
ref const(Inner[string]) func( ref Inner var1, lazy scope string var2 );
inout Inner inoutFunc(inout Inner);
shared(const(Inner[string])[]) data;
const Inner delegate(double, string) @safe nothrow deleg;
inout int delegate(inout int) inout inoutDeleg;
Inner function(out double, string) funcPtr;
extern(C) Inner function(double, string) cFuncPtr;
extern(C) void cVarArg(int, ...);
void dVarArg(...);
void dVarArg2(int, ...);
void typesafeVarArg(int[] ...);
Inner[] array;
Inner[16] sarray;
Inner[Inner] aarray;
const(Inner[const(Inner)]) qualAarray;
shared(immutable(Inner) delegate(ref double, scope string) const shared @trusted nothrow) attrDeleg;
struct Data(T) { int x; }
void tfunc(T...)(T args) {}
template Inst(alias A) { int x; }
class Test12309(T, int x, string s) {}
}
private enum QualifiedEnum
{
a = 42
}
}
private template fqnSym(alias T : X!A, alias X, A...)
{
template fqnTuple(T...)
{
static if (T.length == 0)
enum fqnTuple = "";
else static if (T.length == 1)
{
static if (isExpressionTuple!T)
enum fqnTuple = T[0].stringof;
else
enum fqnTuple = fullyQualifiedName!(T[0]);
}
else
enum fqnTuple = fqnTuple!(T[0]) ~ ", " ~ fqnTuple!(T[1 .. $]);
}
enum fqnSym =
fqnSym!(__traits(parent, X)) ~
'.' ~ __traits(identifier, X) ~ "!(" ~ fqnTuple!A ~ ")";
}
private template fqnSym(alias T)
{
static if (__traits(compiles, __traits(parent, T)))
enum parentPrefix = fqnSym!(__traits(parent, T)) ~ '.';
else
enum parentPrefix = null;
static string adjustIdent(string s)
{
import std.algorithm : skipOver, findSplit;
if (s.skipOver("package ") || s.skipOver("module "))
return s;
return s.findSplit("(")[0];
}
enum fqnSym = parentPrefix ~ adjustIdent(__traits(identifier, T));
}
unittest
{
alias fqn = fullyQualifiedName;
// Make sure those 2 are the same
static assert(fqnSym!fqn == fqn!fqn);
static assert(fqn!fqn == "std.traits.fullyQualifiedName");
alias qnTests = QualifiedNameTests;
enum prefix = "std.traits.QualifiedNameTests.";
static assert(fqn!(qnTests.Inner) == prefix ~ "Inner");
static assert(fqn!(qnTests.func) == prefix ~ "func");
static assert(fqn!(qnTests.Data!int) == prefix ~ "Data!(int)");
static assert(fqn!(qnTests.Data!int.x) == prefix ~ "Data!(int).x");
static assert(fqn!(qnTests.tfunc!(int[])) == prefix ~ "tfunc!(int[])");
static assert(fqn!(qnTests.Inst!(Object)) == prefix ~ "Inst!(object.Object)");
static assert(fqn!(qnTests.Inst!(Object).x) == prefix ~ "Inst!(object.Object).x");
static assert(fqn!(qnTests.Test12309!(int, 10, "str"))
== prefix ~ "Test12309!(int, 10, \"str\")");
import core.sync.barrier;
static assert(fqn!Barrier == "core.sync.barrier.Barrier");
}
private template fqnType(T,
bool alreadyConst, bool alreadyImmutable, bool alreadyShared, bool alreadyInout)
{
import std.string;
// Convenience tags
enum {
_const = 0,
_immutable = 1,
_shared = 2,
_inout = 3
}
alias qualifiers = TypeTuple!(is(T == const), is(T == immutable), is(T == shared), is(T == inout));
alias noQualifiers = TypeTuple!(false, false, false, false);
string storageClassesString(uint psc)() @property
{
alias PSC = ParameterStorageClass;
return format("%s%s%s%s",
psc & PSC.scope_ ? "scope " : "",
psc & PSC.out_ ? "out " : "",
psc & PSC.ref_ ? "ref " : "",
psc & PSC.lazy_ ? "lazy " : ""
);
}
string parametersTypeString(T)() @property
{
import std.array, std.algorithm, std.range;
alias parameters = ParameterTypeTuple!(T);
alias parameterStC = ParameterStorageClassTuple!(T);
enum variadic = variadicFunctionStyle!T;
static if (variadic == Variadic.no)
enum variadicStr = "";
else static if (variadic == Variadic.c)
enum variadicStr = ", ...";
else static if (variadic == Variadic.d)
enum variadicStr = parameters.length ? ", ..." : "...";
else static if (variadic == Variadic.typesafe)
enum variadicStr = " ...";
else
static assert(0, "New variadic style has been added, please update fullyQualifiedName implementation");
static if (parameters.length)
{
string result = join(
map!(a => format("%s%s", a[0], a[1]))(
zip([staticMap!(storageClassesString, parameterStC)],
[staticMap!(fullyQualifiedName, parameters)])
),
", "
);
return result ~= variadicStr;
}
else
return variadicStr;
}
string linkageString(T)() @property
{
enum linkage = functionLinkage!T;
if (linkage != "D")
return format("extern(%s) ", linkage);
else
return "";
}
string functionAttributeString(T)() @property
{
alias FA = FunctionAttribute;
enum attrs = functionAttributes!T;
static if (attrs == FA.none)
return "";
else
return format("%s%s%s%s%s%s",
attrs & FA.pure_ ? " pure" : "",
attrs & FA.nothrow_ ? " nothrow" : "",
attrs & FA.ref_ ? " ref" : "",
attrs & FA.property ? " @property" : "",
attrs & FA.trusted ? " @trusted" : "",
attrs & FA.safe ? " @safe" : ""
);
}
string addQualifiers(string typeString,
bool addConst, bool addImmutable, bool addShared, bool addInout)
{
auto result = typeString;
if (addShared)
{
result = format("shared(%s)", result);
}
if (addConst || addImmutable || addInout)
{
result = format("%s(%s)",
addConst ? "const" :
addImmutable ? "immutable" : "inout",
result
);
}
return result;
}
// Convenience template to avoid copy-paste
template chain(string current)
{
enum chain = addQualifiers(current,
qualifiers[_const] && !alreadyConst,
qualifiers[_immutable] && !alreadyImmutable,
qualifiers[_shared] && !alreadyShared,
qualifiers[_inout] && !alreadyInout);
}
static if (is(T == string))
{
enum fqnType = "string";
}
else static if (is(T == wstring))
{
enum fqnType = "wstring";
}
else static if (is(T == dstring))
{
enum fqnType = "dstring";
}
else static if (isBasicType!T && !is(T == enum))
{
enum fqnType = chain!((Unqual!T).stringof);
}
else static if (isAggregateType!T || is(T == enum))
{
enum fqnType = chain!(fqnSym!T);
}
else static if (isStaticArray!T)
{
import std.conv;
enum fqnType = chain!(
format("%s[%s]", fqnType!(typeof(T.init[0]), qualifiers), T.length)
);
}
else static if (isArray!T)
{
enum fqnType = chain!(
format("%s[]", fqnType!(typeof(T.init[0]), qualifiers))
);
}
else static if (isAssociativeArray!T)
{
enum fqnType = chain!(
format("%s[%s]", fqnType!(ValueType!T, qualifiers), fqnType!(KeyType!T, noQualifiers))
);
}
else static if (isSomeFunction!T)
{
static if (is(T F == delegate))
{
enum qualifierString = format("%s%s",
is(F == shared) ? " shared" : "",
is(F == inout) ? " inout" :
is(F == immutable) ? " immutable" :
is(F == const) ? " const" : ""
);
enum formatStr = "%s%s delegate(%s)%s%s";
enum fqnType = chain!(
format(formatStr, linkageString!T, fqnType!(ReturnType!T, noQualifiers),
parametersTypeString!(T), functionAttributeString!T, qualifierString)
);
}
else
{
static if (isFunctionPointer!T)
enum formatStr = "%s%s function(%s)%s";
else
enum formatStr = "%s%s(%s)%s";
enum fqnType = chain!(
format(formatStr, linkageString!T, fqnType!(ReturnType!T, noQualifiers),
parametersTypeString!(T), functionAttributeString!T)
);
}
}
else static if (isPointer!T)
{
enum fqnType = chain!(
format("%s*", fqnType!(PointerTarget!T, qualifiers))
);
}
else static if (is(T : __vector(V[N]), V, size_t N))
{
enum fqnType = chain!(
format("__vector(%s[%s])", fqnType!(V, qualifiers), N)
);
}
else
// In case something is forgotten
static assert(0, "Unrecognized type " ~ T.stringof ~ ", can't convert to fully qualified string");
}
unittest
{
import std.string : format;
alias fqn = fullyQualifiedName;
// Verify those 2 are the same for simple case
alias Ambiguous = const(QualifiedNameTests.Inner);
static assert(fqn!Ambiguous == fqnType!(Ambiguous, false, false, false, false));
// Main tests
enum inner_name = "std.traits.QualifiedNameTests.Inner";
with (QualifiedNameTests)
{
// Special cases
static assert(fqn!(string) == "string");
static assert(fqn!(wstring) == "wstring");
static assert(fqn!(dstring) == "dstring");
// Basic qualified name
static assert(fqn!(Inner) == inner_name);
static assert(fqn!(QualifiedEnum) == "std.traits.QualifiedEnum"); // type
static assert(fqn!(QualifiedEnum.a) == "std.traits.QualifiedEnum.a"); // symbol
// Array types
static assert(fqn!(typeof(array)) == format("%s[]", inner_name));
static assert(fqn!(typeof(sarray)) == format("%s[16]", inner_name));
static assert(fqn!(typeof(aarray)) == format("%s[%s]", inner_name, inner_name));
// qualified key for AA
static assert(fqn!(typeof(qualAarray)) == format("const(%s[const(%s)])", inner_name, inner_name));
// Qualified composed data types
static assert(fqn!(typeof(data)) == format("shared(const(%s[string])[])", inner_name));
// Function types + function attributes
static assert(fqn!(typeof(func)) == format("const(%s[string])(ref %s, scope lazy string) ref", inner_name, inner_name));
static assert(fqn!(typeof(inoutFunc)) == format("inout(%s(inout(%s)))", inner_name, inner_name));
static assert(fqn!(typeof(deleg)) == format("const(%s delegate(double, string) nothrow @safe)", inner_name));
static assert(fqn!(typeof(inoutDeleg)) == "inout(int delegate(inout(int)) inout)");
static assert(fqn!(typeof(funcPtr)) == format("%s function(out double, string)", inner_name));
static assert(fqn!(typeof(cFuncPtr)) == format("extern(C) %s function(double, string)", inner_name));
// Delegate type with qualified function type
static assert(fqn!(typeof(attrDeleg)) == format("shared(immutable(%s) "~
"delegate(ref double, scope string) nothrow @trusted shared const)", inner_name));
// Variable argument function types
static assert(fqn!(typeof(cVarArg)) == "extern(C) void(int, ...)");
static assert(fqn!(typeof(dVarArg)) == "void(...)");
static assert(fqn!(typeof(dVarArg2)) == "void(int, ...)");
static assert(fqn!(typeof(typesafeVarArg)) == "void(int[] ...)");
// SIMD vector
static if (is(__vector(float[4])))
{
static assert(fqn!(__vector(float[4])) == "__vector(float[4])");
}
}
}
/***
* 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 $(D opCall). Please note that $(D_KEYWORD ref)
* is not part of a type, but the attribute of the function
* (see template $(LREF functionAttributes)).
* 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 ReturnType = R;
else
static assert(0, "argument has no return type");
}
unittest
{
struct G
{
int opCall (int i) { return 1;}
}
alias ShouldBeInt = ReturnType!G;
static assert(is(ShouldBeInt == int));
G g;
static assert(is(ReturnType!g == int));
G* p;
alias pg = ReturnType!p;
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 R_Test_prop = ReturnType!(Test.prop);
static assert(is(R_Test_prop == int));
alias R_dglit = ReturnType!((int a) { return a; });
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 ParameterTypeTuple = P;
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 P_Test_prop = ParameterTypeTuple!(Test.prop);
static assert(P_Test_prop.length == 0);
alias P_dglit = ParameterTypeTuple!((int a){});
static assert(P_dglit.length == 1);
static assert(is(P_dglit[0] == int));
}
/**
Returns the number of arguments of function $(D func).
arity is undefined for variadic functions.
Example:
---
void foo(){}
static assert(arity!foo==0);
void bar(uint){}
static assert(arity!bar==1);
---
*/
template arity(alias func)
if ( isCallable!func && variadicFunctionStyle!func == Variadic.no )
{
enum size_t arity = ParameterTypeTuple!func.length;
}
unittest {
void foo(){}
static assert(arity!foo==0);
void bar(uint){}
static assert(arity!bar==1);
void variadicFoo(uint...){}
static assert(__traits(compiles,arity!variadicFoo)==false);
}
/**
Returns a tuple consisting of the storage classes of the parameters of a
function $(D func).
Example:
--------------------
alias STC = ParameterStorageClass; // shorten the enum name
void func(ref int ctx, out real result, real param)
{
}
alias pstc = ParameterStorageClassTuple!func;
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,
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 Func = Unqual!(FunctionTypeOf!func);
/*
* TypeFuncion:
* CallConvention FuncAttrs Arguments ArgClose Type
*/
alias Params = ParameterTypeTuple!Func;
// 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 demangleNextParameter =
TypeTuple!(
demang.value + 0, // workaround: "not evaluatable at ..."
demangleNextParameter!(rest[skip .. $], i + 1)
);
}
else // went thru all the parameters
{
alias demangleNextParameter = TypeTuple!();
}
}
alias ParameterStorageClassTuple = demangleNextParameter!margs;
}
unittest
{
alias STC = ParameterStorageClass;
void noparam() {}
static assert(ParameterStorageClassTuple!noparam.length == 0);
void test(scope int, ref int, out int, lazy int, int) { }
alias test_pstc = ParameterStorageClassTuple!test;
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 test_const_pstc = ParameterStorageClassTuple!(Test.test_const);
static assert(test_const_pstc.length == 1);
static assert(test_const_pstc[0] == STC.none);
alias test_sharedconst_pstc = ParameterStorageClassTuple!(testi.test_sharedconst);
static assert(test_sharedconst_pstc.length == 1);
static assert(test_sharedconst_pstc[0] == STC.none);
alias dglit_pstc = ParameterStorageClassTuple!((ref int a) {});
static assert(dglit_pstc.length == 1);
static assert(dglit_pstc[0] == STC.ref_);
// Bugzilla 9317
static inout(int) func(inout int param) { return param; }
static assert(ParameterStorageClassTuple!(typeof(func))[0] == STC.none);
}
/**
Get, as a tuple, the identifiers of the parameters to a function symbol.
*/
template ParameterIdentifierTuple(func...)
if (func.length == 1 && isCallable!func)
{
static if (is(FunctionTypeOf!func PT == __parameters))
{
template Get(size_t i)
{
static if (!isFunctionPointer!func && !isDelegate!func)
{
enum Get = __traits(identifier, PT[i..i+1]);
}
else
{
enum Get = "";
}
}
}
else
{
static assert(0, func[0].stringof ~ "is not a function");
// Define dummy entities to avoid pointless errors
template Get(size_t i) { enum Get = ""; }
alias PT = TypeTuple!();
}
template Impl(size_t i = 0)
{
static if (i == PT.length)
alias Impl = TypeTuple!();
else
alias Impl = TypeTuple!(Get!i, Impl!(i+1));
}
alias ParameterIdentifierTuple = Impl!();
}
///
unittest
{
import std.traits;
int foo(int num, string name);
static assert([ParameterIdentifierTuple!foo] == ["num", "name"]);
}
unittest
{
alias PIT = ParameterIdentifierTuple;
void bar(int num, string name, int[] array){}
static assert([PIT!bar] == ["num", "name", "array"]);
// might be changed in the future?
void function(int num, string name) fp;
static assert([PIT!fp] == ["", ""]);
// might be changed in the future?
void delegate(int num, string name, int[long] aa) dg;
static assert([PIT!dg] == ["", "", ""]);
interface Test
{
@property string getter();
@property void setter(int a);
Test method(int a, long b, string c);
}
static assert([PIT!(Test.getter)] == []);
static assert([PIT!(Test.setter)] == ["a"]);
static assert([PIT!(Test.method)] == ["a", "b", "c"]);
/+
// depends on internal
void baw(int, string, int[]){}
static assert([PIT!baw] == ["_param_0", "_param_1", "_param_2"]);
// depends on internal
void baz(TypeTuple!(int, string, int[]) args){}
static assert([PIT!baz] == ["_param_0", "_param_1", "_param_2"]);
+/
}
/**
Get, as a tuple, the default value of the parameters to a function symbol.
If a parameter doesn't have the default value, $(D void) is returned instead.
*/
template ParameterDefaultValueTuple(func...)
if (func.length == 1 && isCallable!func)
{
static if (is(FunctionTypeOf!(func[0]) PT == __parameters))
{
template Get(size_t i)
{
enum get = (PT[i..i+1] args) => args[0];
static if (is(typeof(get())))
enum Get = get();
else
alias Get = void;
// If default arg doesn't exist, returns void instead.
}
}
else static if (is(FunctionTypeOf!func PT == __parameters))
{
template Get(size_t i)
{
enum Get = "";
}
}
else
{
static assert(0, func[0].stringof ~ "is not a function");
// Define dummy entities to avoid pointless errors
template Get(size_t i) { enum Get = ""; }
alias PT = TypeTuple!();
}
template Impl(size_t i = 0)
{
static if (i == PT.length)
alias Impl = TypeTuple!();
else
alias Impl = TypeTuple!(Get!i, Impl!(i+1));
}
alias ParameterDefaultValueTuple = Impl!();
}
///
unittest
{
import std.traits;
int foo(int num, string name = "hello", int[] arr = [1,2,3]);
static assert(is(ParameterDefaultValueTuple!foo[0] == void));
static assert( ParameterDefaultValueTuple!foo[1] == "hello");
static assert( ParameterDefaultValueTuple!foo[2] == [1,2,3]);
}
unittest
{
alias PDVT = ParameterDefaultValueTuple;
void bar(int n = 1, string s = "hello"){}
static assert(PDVT!bar.length == 2);
static assert(PDVT!bar[0] == 1);
static assert(PDVT!bar[1] == "hello");
static assert(is(typeof(PDVT!bar) == typeof(TypeTuple!(1, "hello"))));
void baz(int x, int n = 1, string s = "hello"){}
static assert(PDVT!baz.length == 3);
static assert(is(PDVT!baz[0] == void));
static assert( PDVT!baz[1] == 1);
static assert( PDVT!baz[2] == "hello");
static assert(is(typeof(PDVT!baz) == typeof(TypeTuple!(void, 1, "hello"))));
// bug 10800 - property functions return empty string
@property void foo(int x = 3) { }
static assert(PDVT!foo.length == 1);
static assert(PDVT!foo[0] == 3);
static assert(is(typeof(PDVT!foo) == typeof(TypeTuple!(3))));
struct Colour
{
ubyte a,r,g,b;
static immutable Colour white = Colour(255,255,255,255);
}
void bug8106(Colour c = Colour.white){}
//pragma(msg, PDVT!bug8106);
static assert(PDVT!bug8106[0] == Colour.white);
}
/**
Returns the attributes attached to a function $(D func).
Example:
--------------------
alias FA = FunctionAttribute; // shorten the enum name
real func(real x) @safe pure nothrow
{
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,
pure_ = 0b00000001, /// ditto
nothrow_ = 0b00000010, /// ditto
ref_ = 0b00000100, /// ditto
property = 0b00001000, /// ditto
trusted = 0b00010000, /// ditto
safe = 0b00100000, /// ditto
nogc = 0b01000000, /// ditto
}
/// ditto
template functionAttributes(func...)
if (func.length == 1 && isCallable!func)
{
alias Func = Unqual!(FunctionTypeOf!func);
enum uint functionAttributes =
demangleFunctionAttributes(mangledName!Func[1 .. $]).value;
}
unittest
{
alias FA = FunctionAttribute;
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 ref int static_ref_property() @property { return *(new int); }
ref int ref_property() @property { return *(new int); }
void safe_nothrow() @safe nothrow { }
static assert(functionAttributes!pure_nothrow == (FA.pure_ | FA.nothrow_));
static assert(functionAttributes!static_ref_property == (FA.ref_ | FA.property));
static assert(functionAttributes!ref_property == (FA.ref_ | FA.property));
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_ | FA.nogc));
auto safeDel = delegate() @safe {};
static assert(functionAttributes!safeDel == (FA.safe | FA.pure_ | FA.nothrow_ | FA.nogc));
auto trustedDel = delegate() @trusted {};
static assert(functionAttributes!trustedDel == (FA.trusted | FA.pure_ | FA.nothrow_ | FA.nogc));
auto systemDel = delegate() @system {};
static assert(functionAttributes!systemDel == (FA.pure_ | FA.nothrow_ | FA.nogc));
}
/**
$(D true) if $(D func) is $(D @safe) or $(D @trusted).
Example:
--------------------
@safe int add(int a, int b) {return a+b;}
@trusted int sub(int a, int b) {return a-b;}
@system int mul(int a, int b) {return a*b;}
static assert( isSafe!add);
static assert( isSafe!sub);
static assert(!isSafe!mul);
--------------------
*/
template isSafe(alias func)
if(isCallable!func)
{
enum isSafe = (functionAttributes!func & FunctionAttribute.safe) != 0 ||
(functionAttributes!func & FunctionAttribute.trusted) != 0;
}
//Verify Examples.
unittest
{
@safe int add(int a, int b) {return a+b;}
@trusted int sub(int a, int b) {return a-b;}
@system int mul(int a, int b) {return a*b;}
static assert( isSafe!add);
static assert( isSafe!sub);
static assert(!isSafe!mul);
}
unittest
{
//Member functions
interface Set
{
int systemF() @system;
int trustedF() @trusted;
int safeF() @safe;
}
static assert( isSafe!(Set.safeF));
static assert( isSafe!(Set.trustedF));
static assert(!isSafe!(Set.systemF));
//Functions
@safe static safeFunc() {}
@trusted static trustedFunc() {}
@system static systemFunc() {}
static assert( isSafe!safeFunc);
static assert( isSafe!trustedFunc);
static assert(!isSafe!systemFunc);
//Delegates
auto safeDel = delegate() @safe {};
auto trustedDel = delegate() @trusted {};
auto systemDel = delegate() @system {};
static assert( isSafe!safeDel);
static assert( isSafe!trustedDel);
static assert(!isSafe!systemDel);
//Lambdas
static assert( isSafe!({safeDel();}));
static assert( isSafe!({trustedDel();}));
static assert(!isSafe!({systemDel();}));
//Static opCall
struct SafeStatic { @safe static SafeStatic opCall() { return SafeStatic.init; } }
struct TrustedStatic { @trusted static TrustedStatic opCall() { return TrustedStatic.init; } }
struct SystemStatic { @system static SystemStatic opCall() { return SystemStatic.init; } }
static assert( isSafe!(SafeStatic()));
static assert( isSafe!(TrustedStatic()));
static assert(!isSafe!(SystemStatic()));
//Non-static opCall
struct Safe { @safe Safe opCall() { return Safe.init; } }
struct Trusted { @trusted Trusted opCall() { return Trusted.init; } }
struct System { @system System opCall() { return System.init; } }
static assert( isSafe!(Safe.init()));
static assert( isSafe!(Trusted.init()));
static assert(!isSafe!(System.init()));
}
/**
$(D true) if $(D func) is $(D @system).
Example:
--------------------
@safe int add(int a, int b) {return a+b;}
@trusted int sub(int a, int b) {return a-b;}
@system int mul(int a, int b) {return a*b;}
static assert(!isUnsafe!add);
static assert(!isUnsafe!sub);
static assert( isUnsafe!mul);
--------------------
*/
template isUnsafe(alias func)
{
enum isUnsafe = !isSafe!func;
}
//Verify Examples.
unittest
{
@safe int add(int a, int b) {return a+b;}
@trusted int sub(int a, int b) {return a-b;}
@system int mul(int a, int b) {return a*b;}
static assert(!isUnsafe!add);
static assert(!isUnsafe!sub);
static assert( isUnsafe!mul);
}
unittest
{
//Member functions
interface Set
{
int systemF() @system;
int trustedF() @trusted;
int safeF() @safe;
}
static assert(!isUnsafe!(Set.safeF));
static assert(!isUnsafe!(Set.trustedF));
static assert( isUnsafe!(Set.systemF));
//Functions
@safe static safeFunc() {}
@trusted static trustedFunc() {}
@system static systemFunc() {}
static assert(!isUnsafe!safeFunc);
static assert(!isUnsafe!trustedFunc);
static assert( isUnsafe!systemFunc);
//Delegates
auto safeDel = delegate() @safe {};
auto trustedDel = delegate() @trusted {};
auto systemDel = delegate() @system {};
static assert(!isUnsafe!safeDel);
static assert(!isUnsafe!trustedDel);
static assert( isUnsafe!systemDel);
//Lambdas
static assert(!isUnsafe!({safeDel();}));
static assert(!isUnsafe!({trustedDel();}));
static assert( isUnsafe!({systemDel();}));
//Static opCall
struct SafeStatic { @safe static SafeStatic opCall() { return SafeStatic.init; } }
struct TrustedStatic { @trusted static TrustedStatic opCall() { return TrustedStatic.init; } }
struct SystemStatic { @system static SystemStatic opCall() { return SystemStatic.init; } }
static assert(!isUnsafe!(SafeStatic()));
static assert(!isUnsafe!(TrustedStatic()));
static assert( isUnsafe!(SystemStatic()));
//Non-static opCall
struct Safe { @safe Safe opCall() { return Safe.init; } }
struct Trusted { @trusted Trusted opCall() { return Trusted.init; } }
struct System { @system System opCall() { return System.init; } }
static assert(!isUnsafe!(Safe.init()));
static assert(!isUnsafe!(Trusted.init()));
static assert( isUnsafe!(System.init()));
}
/**
$(RED Scheduled for deprecation in January 2013. It's badly named and provides
redundant functionality. It was also badly broken prior to 2.060 (bug# 8362), so
any code which uses it probably needs to be changed anyway. Please use
$(D allSatisfy(isSafe, ...)) instead.)
$(D true) all functions are $(D isSafe).
Example:
--------------------
@safe int add(int a, int b) {return a+b;}
@trusted int sub(int a, int b) {return a-b;}
@system int mul(int a, int b) {return a*b;}
static assert( areAllSafe!(add, add));
static assert( areAllSafe!(add, sub));
static assert(!areAllSafe!(sub, mul));
--------------------
*/
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;
}
}
//Verify Example
unittest
{
@safe int add(int a, int b) {return a+b;}
@trusted int sub(int a, int b) {return a-b;}
@system int mul(int a, int b) {return a*b;}
static assert( areAllSafe!(add, add));
static assert( areAllSafe!(add, sub));
static assert(!areAllSafe!(sub, mul));
}
unittest
{
interface Set
{
int systemF() @system;
int trustedF() @trusted;
int safeF() @safe;
}
static assert( areAllSafe!((int a){}, Set.safeF));
static assert( areAllSafe!((int a){}, Set.safeF, Set.trustedF));
static assert(!areAllSafe!(Set.trustedF, 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)
{
alias Func = Unqual!(FunctionTypeOf!func);
enum string functionLinkage =
[
'F': "D",
'U': "C",
'W': "Windows",
'V': "Pascal",
'R': "C++"
][ mangledName!Func[0] ];
}
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)
{
alias Func = Unqual!(FunctionTypeOf!func);
// TypeFuncion --> CallConvention FuncAttrs Arguments ArgClose Type
enum callconv = functionLinkage!Func;
enum mfunc = mangledName!Func;
enum mtype = mangledName!(ReturnType!Func);
static assert(mfunc[$ - mtype.length .. $] == mtype, mfunc ~ "|" ~ mtype);
enum argclose = mfunc[$ - mtype.length - 1];
static assert(argclose >= 'X' && argclose <= 'Z');
enum Variadic variadicFunctionStyle =
argclose == 'X' ? Variadic.typesafe :
argclose == 'Y' ? (callconv == "C") ? Variadic.c : Variadic.d :
Variadic.no; // 'Z'
}
unittest
{
import core.vararg;
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 FunctionTypeOf = Fsym; // HIT: (nested) function symbol
}
else static if (is(typeof(& func[0].opCall) Fobj == delegate))
{
alias FunctionTypeOf = Fobj; // HIT: callable object
}
else static if (is(typeof(& func[0].opCall) Ftyp : Ftyp*) && is(Ftyp == function))
{
alias FunctionTypeOf = Ftyp; // HIT: callable type
}
else static if (is(func[0] T) || is(typeof(func[0]) T))
{
static if (is(T == function))
alias FunctionTypeOf = T; // HIT: function
else static if (is(T Fptr : Fptr*) && is(Fptr == function))
alias FunctionTypeOf = Fptr; // HIT: function pointer
else static if (is(T Fdlg == delegate))
alias FunctionTypeOf = Fdlg; // 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 ov = TypeTuple!(__traits(getVirtualFunctions, Overloads, "test"));
alias F_ov0 = FunctionTypeOf!(ov[0]);
alias F_ov1 = FunctionTypeOf!(ov[1]);
alias F_ov2 = FunctionTypeOf!(ov[2]);
alias F_ov3 = FunctionTypeOf!(ov[3]);
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 F_dglit = FunctionTypeOf!((int a){ return a; });
static assert(is(F_dglit* : int function(int)));
}
/**
* Constructs a new function or delegate type with the same basic signature
* as the given one, but different attributes (including linkage).
*
* This is especially useful for adding/removing attributes to/from types in
* generic code, where the actual type name cannot be spelt out.
*
* Params:
* T = The base type.
* linkage = The desired linkage of the result type.
* attrs = The desired $(LREF FunctionAttribute)s of the result type.
*
* Examples:
* ---
* alias ExternC(T) = SetFunctionAttributes!(T, "C", functionAttributes!T);
* ---
*
* ---
* auto assumePure(T)(T t)
* if (isFunctionPointer!T || isDelegate!T)
* {
* enum attrs = functionAttributes!T | FunctionAttribute.pure_;
* return cast(SetFunctionAttributes!(T, functionLinkage!T, attrs)) t;
* }
* ---
*/
template SetFunctionAttributes(T, string linkage, uint attrs)
if (isFunctionPointer!T || isDelegate!T)
{
mixin({
import std.algorithm : canFind;
static assert(!(attrs & FunctionAttribute.trusted) ||
!(attrs & FunctionAttribute.safe),
"Cannot have a function/delegate that is both trusted and safe.");
enum linkages = ["D", "C", "Windows", "Pascal", "C++", "System"];
static assert(canFind(linkages, linkage), "Invalid linkage '" ~
linkage ~ "', must be one of " ~ linkages.stringof ~ ".");
string result = "alias ";
static if (linkage != "D")
result ~= "extern(" ~ linkage ~ ") ";
static if (attrs & FunctionAttribute.ref_)
result ~= "ref ";
result ~= "ReturnType!T";
static if (isDelegate!T)
result ~= " delegate";
else
result ~= " function";
result ~= "(";
static if (ParameterTypeTuple!T.length > 0)
result ~= "ParameterTypeTuple!T";
enum varStyle = variadicFunctionStyle!T;
static if (varStyle == Variadic.c)
result ~= ", ...";
else static if (varStyle == Variadic.d)
result ~= "...";
else static if (varStyle == Variadic.typesafe)
result ~= "...";
result ~= ")";
static if (attrs & FunctionAttribute.pure_)
result ~= " pure";
static if (attrs & FunctionAttribute.nothrow_)
result ~= " nothrow";
static if (attrs & FunctionAttribute.nogc)
result ~= " @nogc";
static if (attrs & FunctionAttribute.property)
result ~= " @property";
static if (attrs & FunctionAttribute.trusted)
result ~= " @trusted";
static if (attrs & FunctionAttribute.safe)
result ~= " @safe";
result ~= " SetFunctionAttributes;";
return result;
}());
}
/// Ditto
template SetFunctionAttributes(T, string linkage, uint attrs)
if (is(T == function))
{
// To avoid a lot of syntactic headaches, we just use the above version to
// operate on the corresponding function pointer type and then remove the
// indirection again.
alias SetFunctionAttributes = FunctionTypeOf!(SetFunctionAttributes!(T*, linkage, attrs));
}
version (unittest)
{
// Some function types to test.
int sc(scope int, ref int, out int, lazy int, int);
extern(System) int novar();
extern(C) int cstyle(int, ...);
extern(D) int dstyle(...);
extern(D) int typesafe(int[]...);
}
unittest
{
import std.algorithm : reduce;
alias FA = FunctionAttribute;
foreach (BaseT; TypeTuple!(typeof(&sc), typeof(&novar), typeof(&cstyle),
typeof(&dstyle), typeof(&typesafe)))
{
foreach (T; TypeTuple!(BaseT, FunctionTypeOf!BaseT))
{
enum linkage = functionLinkage!T;
enum attrs = functionAttributes!T;
static assert(is(SetFunctionAttributes!(T, linkage, attrs) == T),
"Identity check failed for: " ~ T.stringof);
// Check that all linkage types work (D-style variadics require D linkage).
static if (variadicFunctionStyle!T != Variadic.d)
{
foreach (newLinkage; TypeTuple!("D", "C", "Windows", "Pascal", "C++"))
{
alias New = SetFunctionAttributes!(T, newLinkage, attrs);
static assert(functionLinkage!New == newLinkage,
"Linkage test failed for: " ~ T.stringof ~ ", " ~ newLinkage ~
" (got " ~ New.stringof ~ ")");
}
}
// Add @safe.
alias T1 = SetFunctionAttributes!(T, functionLinkage!T, FA.safe);
static assert(functionAttributes!T1 == FA.safe);
// Add all known attributes, excluding conflicting ones.
enum allAttrs = reduce!"a | b"([EnumMembers!FA]) & ~FA.safe & ~FA.property;
alias T2 = SetFunctionAttributes!(T1, functionLinkage!T, allAttrs);
static assert(functionAttributes!T2 == allAttrs);
// Strip all attributes again.
alias T3 = SetFunctionAttributes!(T2, functionLinkage!T, FA.none);
static assert(is(T3 == T));
}
}
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// Aggregate Types
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
/**
Determines whether $(D T) has its own context pointer.
$(D T) must be either $(D class), $(D struct), or $(D union).
*/
template isNested(T)
if(is(T == class) || is(T == struct) || is(T == union))
{
enum isNested = __traits(isNested, T);
}
///
unittest
{
static struct S { }
static assert(!isNested!S);
int i;
struct NestedStruct { void f() { ++i; } }
static assert(isNested!NestedStruct);
}
/**
Determines whether $(D T) or any of its representation types
have a context pointer.
*/
template hasNested(T)
{
static if(isStaticArray!T && T.length)
enum hasNested = hasNested!(typeof(T.init[0]));
else static if(is(T == class) || is(T == struct) || is(T == union))
enum hasNested = isNested!T ||
anySatisfy!(.hasNested, FieldTypeTuple!T);
else
enum hasNested = false;
}
///
unittest
{
static struct S { }
int i;
struct NS { void f() { ++i; } }
static assert(!hasNested!(S[2]));
static assert(hasNested!(NS[2]));
}
unittest
{
static assert(!__traits(compiles, isNested!int));
static assert(!hasNested!int);
static struct StaticStruct { }
static assert(!isNested!StaticStruct);
static assert(!hasNested!StaticStruct);
int i;
struct NestedStruct { void f() { ++i; } }
static assert( isNested!NestedStruct);
static assert( hasNested!NestedStruct);
static assert( isNested!(immutable NestedStruct));
static assert( hasNested!(immutable NestedStruct));
static assert(!__traits(compiles, isNested!(NestedStruct[1])));
static assert( hasNested!(NestedStruct[1]));
static assert(!hasNested!(NestedStruct[0]));
struct S1 { NestedStruct nested; }
static assert(!isNested!S1);
static assert( hasNested!S1);
static struct S2 { NestedStruct nested; }
static assert(!isNested!S2);
static assert( hasNested!S2);
static struct S3 { NestedStruct[0] nested; }
static assert(!isNested!S3);
static assert(!hasNested!S3);
static union U { NestedStruct nested; }
static assert(!isNested!U);
static assert( hasNested!U);
static class StaticClass { }
static assert(!isNested!StaticClass);
static assert(!hasNested!StaticClass);
class NestedClass { void f() { ++i; } }
static assert( isNested!NestedClass);
static assert( hasNested!NestedClass);
static assert( isNested!(immutable NestedClass));
static assert( hasNested!(immutable NestedClass));
static assert(!__traits(compiles, isNested!(NestedClass[1])));
static assert( hasNested!(NestedClass[1]));
static assert(!hasNested!(NestedClass[0]));
}
/***
* Get as a typetuple the types of the fields of a struct, class, or union.
* This consists of the fields that take up memory space,
* excluding the hidden fields like the virtual function
* table pointer or a context pointer for nested types.
* If $(D T) isn't a struct, class, or union returns typetuple
* with one element $(D T).
*/
template FieldTypeTuple(T)
{
static if (is(T == struct) || is(T == union))
alias FieldTypeTuple = typeof(T.tupleof[0 .. $ - isNested!T]);
else static if (is(T == class))
alias FieldTypeTuple = typeof(T.tupleof);
else
alias FieldTypeTuple = TypeTuple!T;
}
///
unittest
{
struct S { int x; float y; }
static assert(is(FieldTypeTuple!S == TypeTuple!(int, float)));
}
unittest
{
static assert(is(FieldTypeTuple!int == TypeTuple!int));
static struct StaticStruct1 { }
static assert(is(FieldTypeTuple!StaticStruct1 == TypeTuple!()));
static struct StaticStruct2 { int a, b; }
static assert(is(FieldTypeTuple!StaticStruct2 == TypeTuple!(int, int)));
int i;
struct NestedStruct1 { void f() { ++i; } }
static assert(is(FieldTypeTuple!NestedStruct1 == TypeTuple!()));
struct NestedStruct2 { int a; void f() { ++i; } }
static assert(is(FieldTypeTuple!NestedStruct2 == TypeTuple!int));
class NestedClass { int a; void f() { ++i; } }
static assert(is(FieldTypeTuple!NestedClass == TypeTuple!int));
}
// // 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 T1 = FieldOffsetsTuple!int;
// assert(T1.length == 1 && T1[0] == 0);
// //
// struct S2 { char a; int b; char c; double d; char e, f; }
// alias T2 = FieldOffsetsTuple!S2;
// //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 T3 = FieldOffsetsTuple!S3;
// //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 T4 = FieldOffsetsTuple!S4;
// //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 R = RepresentationTypeTuple!S2;
assert(R.length == 4
&& is(R[0] == char[]) && is(R[1] == int)
&& is(R[2] == float) && is(R[3] == S1*));
----
*/
template RepresentationTypeTuple(T)
{
template Impl(T...)
{
static if (T.length == 0)
{
alias Impl = TypeTuple!();
}
else
{
import std.typecons : Rebindable;
static if (is(T[0] R: Rebindable!R))
{
alias Impl = Impl!(Impl!R, T[1 .. $]);
}
else static if (is(T[0] == struct) || is(T[0] == union))
{
// @@@BUG@@@ this should work
//alias .RepresentationTypes!(T[0].tupleof)
// RepresentationTypes;
alias Impl = Impl!(FieldTypeTuple!(T[0]), T[1 .. $]);
}
else static if (is(T[0] U == typedef))
{
alias Impl = Impl!(FieldTypeTuple!U, T[1 .. $]);
}
else
{
alias Impl = TypeTuple!(T[0], Impl!(T[1 .. $]));
}
}
}
static if (is(T == struct) || is(T == union) || is(T == class))
{
alias RepresentationTypeTuple = Impl!(FieldTypeTuple!T);
}
else static if (is(T U == typedef))
{
alias RepresentationTypeTuple = RepresentationTypeTuple!U;
}
else
{
alias RepresentationTypeTuple = Impl!T;
}
}
unittest
{
alias S1 = RepresentationTypeTuple!int;
static assert(is(S1 == TypeTuple!int));
struct S2 { int a; }
struct S3 { int a; char b; }
struct S4 { S1 a; int b; S3 c; }
static assert(is(RepresentationTypeTuple!S2 == TypeTuple!int));
static assert(is(RepresentationTypeTuple!S3 == TypeTuple!(int, char)));
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 R = RepresentationTypeTuple!S21;
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 R1 = RepresentationTypeTuple!C;
static assert(R1.length == 2 && is(R1[0] == int) && is(R1[1] == float));
/* Issue 6642 */
import std.typecons : Rebindable;
struct S5 { int a; Rebindable!(immutable Object) b; }
alias R2 = RepresentationTypeTuple!S5;
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);
// }
/*
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...)
{
template Impl(T...)
{
static if (T.length == 0)
{
enum Impl = false;
}
else
{
static if (is(T[0] foo : U*, U) && !isFunctionPointer!(T[0]))
enum has = !is(U == immutable);
else static if (is(T[0] foo : U[], U) && !isStaticArray!(T[0]))
enum has = !is(U == immutable);
else static if (isAssociativeArray!(T[0]))
enum has = !is(T[0] == immutable);
else
enum has = false;
enum Impl = has || Impl!(T[1 .. $]);
}
}
enum hasRawAliasing = Impl!(RepresentationTypeTuple!T);
}
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; }
struct S2 { int* z; }
static assert(!hasRawAliasing!S1);
static assert( hasRawAliasing!S2);
struct S3 { int a; int* z; int c; }
struct S4 { int a; int z; int c; }
struct S5 { int a; Object z; int c; }
static assert( hasRawAliasing!S3);
static assert(!hasRawAliasing!S4);
static assert(!hasRawAliasing!S5);
union S6 { int a; int b; }
union S7 { int a; int * b; }
static assert(!hasRawAliasing!S6);
static assert( hasRawAliasing!S7);
static assert(!hasRawAliasing!(void delegate()));
static assert(!hasRawAliasing!(void delegate() const));
static assert(!hasRawAliasing!(void delegate() immutable));
static assert(!hasRawAliasing!(void delegate() shared));
static assert(!hasRawAliasing!(void delegate() shared const));
static assert(!hasRawAliasing!(const(void delegate())));
static assert(!hasRawAliasing!(immutable(void delegate())));
struct S8 { void delegate() a; int b; Object c; }
class S12 { typeof(S8.tupleof) a; }
class S13 { typeof(S8.tupleof) a; int* b; }
static assert(!hasRawAliasing!S8);
static assert(!hasRawAliasing!S12);
static assert( hasRawAliasing!S13);
//typedef int* S8;
//static assert(hasRawAliasing!S8);
enum S9 { a }
static assert(!hasRawAliasing!S9);
// indirect members
struct S10 { S7 a; int b; }
struct S11 { S6 a; int b; }
static assert( hasRawAliasing!S10);
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(!hasRawUnsharedAliasing!int);
static assert( hasRawUnsharedAliasing!(char*));
static assert(!hasRawUnsharedAliasing!(shared char*));
// references aren't raw pointers
static assert(!hasRawUnsharedAliasing!Object);
// built-in arrays do contain raw pointers
static assert( hasRawUnsharedAliasing!(int[]));
static assert(!hasRawUnsharedAliasing!(shared int[]));
// aggregate of simple types
struct S1 { int a; double b; }
static assert(!hasRawUnsharedAliasing!S1);
// indirect aggregation
struct S2 { S1 a; double b; }
static assert(!hasRawUnsharedAliasing!S2);
// struct with a pointer member
struct S3 { int a; double * b; }
static assert( hasRawUnsharedAliasing!S3);
struct S4 { int a; shared double * b; }
static assert( hasRawUnsharedAliasing!S4);
// struct with an indirect pointer member
struct S5 { S3 a; double b; }
static assert( hasRawUnsharedAliasing!S5);
struct S6 { S4 a; double b; }
static assert(!hasRawUnsharedAliasing!S6);
----
*/
private template hasRawUnsharedAliasing(T...)
{
template Impl(T...)
{
static if (T.length == 0)
{
enum Impl = false;
}
else
{
static if (is(T[0] foo : U*, U) && !isFunctionPointer!(T[0]))
enum has = !is(U == immutable) && !is(U == shared);
else static if (is(T[0] foo : U[], U) && !isStaticArray!(T[0]))
enum has = !is(U == immutable) && !is(U == shared);
else static if (isAssociativeArray!(T[0]))
enum has = !is(T[0] == immutable) && !is(T[0] == shared);
else
enum has = false;
enum Impl = has || Impl!(T[1 .. $]);
}
}
enum hasRawUnsharedAliasing = Impl!(RepresentationTypeTuple!T);
}
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; }
struct S2 { int* z; }
static assert(!hasRawUnsharedAliasing!S1);
static assert( hasRawUnsharedAliasing!S2);
struct S3 { shared int* z; }
struct S4 { int a; int* z; int c; }
static assert(!hasRawUnsharedAliasing!S3);
static assert( hasRawUnsharedAliasing!S4);
struct S5 { int a; shared int* z; int c; }
struct S6 { int a; int z; int c; }
struct S7 { int a; Object z; int c; }
static assert(!hasRawUnsharedAliasing!S5);
static assert(!hasRawUnsharedAliasing!S6);
static assert(!hasRawUnsharedAliasing!S7);
union S8 { int a; int b; }
union S9 { int a; int* b; }
union S10 { int a; shared int* b; }
static assert(!hasRawUnsharedAliasing!S8);
static assert( hasRawUnsharedAliasing!S9);
static assert(!hasRawUnsharedAliasing!S10);
static assert(!hasRawUnsharedAliasing!(void delegate()));
static assert(!hasRawUnsharedAliasing!(void delegate() const));
static assert(!hasRawUnsharedAliasing!(void delegate() immutable));
static assert(!hasRawUnsharedAliasing!(void delegate() shared));
static assert(!hasRawUnsharedAliasing!(void delegate() shared const));
static assert(!hasRawUnsharedAliasing!(const(void delegate())));
static assert(!hasRawUnsharedAliasing!(const(void delegate() const)));
static assert(!hasRawUnsharedAliasing!(const(void delegate() immutable)));
static assert(!hasRawUnsharedAliasing!(const(void delegate() shared)));
static assert(!hasRawUnsharedAliasing!(const(void delegate() shared const)));
static assert(!hasRawUnsharedAliasing!(immutable(void delegate())));
static assert(!hasRawUnsharedAliasing!(immutable(void delegate() const)));
static assert(!hasRawUnsharedAliasing!(immutable(void delegate() immutable)));
static assert(!hasRawUnsharedAliasing!(immutable(void delegate() shared)));
static assert(!hasRawUnsharedAliasing!(immutable(void delegate() shared const)));
static assert(!hasRawUnsharedAliasing!(shared(void delegate())));
static assert(!hasRawUnsharedAliasing!(shared(void delegate() const)));
static assert(!hasRawUnsharedAliasing!(shared(void delegate() immutable)));
static assert(!hasRawUnsharedAliasing!(shared(void delegate() shared)));
static assert(!hasRawUnsharedAliasing!(shared(void delegate() shared const)));
static assert(!hasRawUnsharedAliasing!(shared(const(void delegate()))));
static assert(!hasRawUnsharedAliasing!(shared(const(void delegate() const))));
static assert(!hasRawUnsharedAliasing!(shared(const(void delegate() immutable))));
static assert(!hasRawUnsharedAliasing!(shared(const(void delegate() shared))));
static assert(!hasRawUnsharedAliasing!(shared(const(void delegate() shared const))));
static assert(!hasRawUnsharedAliasing!(void function()));
//typedef int* S11;
//typedef shared int* S12;
//static assert( hasRawUnsharedAliasing!S11);
//static assert( hasRawUnsharedAliasing!S12);
enum S13 { a }
static assert(!hasRawUnsharedAliasing!S13);
// indirect members
struct S14 { S9 a; int b; }
struct S15 { S10 a; int b; }
struct S16 { S6 a; int b; }
static assert( hasRawUnsharedAliasing!S14);
static assert(!hasRawUnsharedAliasing!S15);
static assert(!hasRawUnsharedAliasing!S16);
static assert( hasRawUnsharedAliasing!(int[string]));
static assert(!hasRawUnsharedAliasing!(shared(int[string])));
static assert(!hasRawUnsharedAliasing!(immutable(int[string])));
struct S17
{
void delegate() shared a;
void delegate() immutable b;
void delegate() shared const c;
shared(void delegate()) d;
shared(void delegate() shared) e;
shared(void delegate() immutable) f;
shared(void delegate() shared const) g;
immutable(void delegate()) h;
immutable(void delegate() shared) i;
immutable(void delegate() immutable) j;
immutable(void delegate() shared const) k;
shared(const(void delegate())) l;
shared(const(void delegate() shared)) m;
shared(const(void delegate() immutable)) n;
shared(const(void delegate() shared const)) o;
}
struct S18 { typeof(S17.tupleof) a; void delegate() p; }
struct S19 { typeof(S17.tupleof) a; Object p; }
struct S20 { typeof(S17.tupleof) a; int* p; }
class S21 { typeof(S17.tupleof) a; }
class S22 { typeof(S17.tupleof) a; void delegate() p; }
class S23 { typeof(S17.tupleof) a; Object p; }
class S24 { typeof(S17.tupleof) a; int* p; }
static assert(!hasRawUnsharedAliasing!S17);
static assert(!hasRawUnsharedAliasing!(immutable(S17)));
static assert(!hasRawUnsharedAliasing!(shared(S17)));
static assert(!hasRawUnsharedAliasing!S18);
static assert(!hasRawUnsharedAliasing!(immutable(S18)));
static assert(!hasRawUnsharedAliasing!(shared(S18)));
static assert(!hasRawUnsharedAliasing!S19);
static assert(!hasRawUnsharedAliasing!(immutable(S19)));
static assert(!hasRawUnsharedAliasing!(shared(S19)));
static assert( hasRawUnsharedAliasing!S20);
static assert(!hasRawUnsharedAliasing!(immutable(S20)));
static assert(!hasRawUnsharedAliasing!(shared(S20)));
static assert(!hasRawUnsharedAliasing!S21);
static assert(!hasRawUnsharedAliasing!(immutable(S21)));
static assert(!hasRawUnsharedAliasing!(shared(S21)));
static assert(!hasRawUnsharedAliasing!S22);
static assert(!hasRawUnsharedAliasing!(immutable(S22)));
static assert(!hasRawUnsharedAliasing!(shared(S22)));
static assert(!hasRawUnsharedAliasing!S23);
static assert(!hasRawUnsharedAliasing!(immutable(S23)));
static assert(!hasRawUnsharedAliasing!(shared(S23)));
static assert( hasRawUnsharedAliasing!S24);
static assert(!hasRawUnsharedAliasing!(immutable(S24)));
static assert(!hasRawUnsharedAliasing!(shared(S24)));
struct S25 {}
class S26 {}
interface S27 {}
union S28 {}
static assert(!hasRawUnsharedAliasing!S25);
static assert(!hasRawUnsharedAliasing!S26);
static assert(!hasRawUnsharedAliasing!S27);
static assert(!hasRawUnsharedAliasing!S28);
}
/*
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...)
{
import std.typecons : Rebindable;
static if (T.length && is(T[0] : Rebindable!R, R))
{
enum hasAliasing = hasAliasing!(R, T[1 .. $]);
}
else
{
template isAliasingDelegate(T)
{
enum isAliasingDelegate = isDelegate!T
&& !is(T == immutable)
&& !is(FunctionTypeOf!T == immutable);
}
enum hasAliasing = hasRawAliasing!T || hasObjects!T ||
anySatisfy!(isAliasingDelegate, T, RepresentationTypeTuple!T);
}
}
unittest
{
struct S1 { int a; Object b; }
struct S2 { string a; }
struct S3 { int a; immutable Object b; }
struct S4 { float[3] vals; }
static assert( hasAliasing!S1);
static assert(!hasAliasing!S2);
static assert(!hasAliasing!S3);
static assert(!hasAliasing!S4);
static assert( hasAliasing!(uint[uint]));
static assert(!hasAliasing!(immutable(uint[uint])));
static assert( hasAliasing!(void delegate()));
static assert( hasAliasing!(void delegate() const));
static assert(!hasAliasing!(void delegate() immutable));
static assert( hasAliasing!(void delegate() shared));
static assert( hasAliasing!(void delegate() shared const));
static assert( hasAliasing!(const(void delegate())));
static assert( hasAliasing!(const(void delegate() const)));
static assert(!hasAliasing!(const(void delegate() immutable)));
static assert( hasAliasing!(const(void delegate() shared)));
static assert( hasAliasing!(const(void delegate() shared const)));
static assert(!hasAliasing!(immutable(void delegate())));
static assert(!hasAliasing!(immutable(void delegate() const)));
static assert(!hasAliasing!(immutable(void delegate() immutable)));
static assert(!hasAliasing!(immutable(void delegate() shared)));
static assert(!hasAliasing!(immutable(void delegate() shared const)));
static assert( hasAliasing!(shared(const(void delegate()))));
static assert( hasAliasing!(shared(const(void delegate() const))));
static assert(!hasAliasing!(shared(const(void delegate() immutable))));
static assert( hasAliasing!(shared(const(void delegate() shared))));
static assert( hasAliasing!(shared(const(void delegate() shared const))));
static assert(!hasAliasing!(void function()));
interface I;
static assert( hasAliasing!I);
import std.typecons : Rebindable;
static assert( hasAliasing!(Rebindable!(const Object)));
static assert(!hasAliasing!(Rebindable!(immutable Object)));
static assert( hasAliasing!(Rebindable!(shared Object)));
static assert( hasAliasing!(Rebindable!Object));
struct S5
{
void delegate() immutable b;
shared(void delegate() immutable) f;
immutable(void delegate() immutable) j;
shared(const(void delegate() immutable)) n;
}
struct S6 { typeof(S5.tupleof) a; void delegate() p; }
static assert(!hasAliasing!S5);
static assert( hasAliasing!S6);
struct S7 { void delegate() a; int b; Object c; }
class S8 { int a; int b; }
class S9 { typeof(S8.tupleof) a; }
class S10 { typeof(S8.tupleof) a; int* b; }
static assert( hasAliasing!S7);
static assert( hasAliasing!S8);
static assert( hasAliasing!S9);
static assert( hasAliasing!S10);
struct S11 {}
class S12 {}
interface S13 {}
union S14 {}
static assert(!hasAliasing!S11);
static assert( hasAliasing!S12);
static assert( hasAliasing!S13);
static assert(!hasAliasing!S14);
}
/**
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)
{
static if (is(T == struct) || is(T == union))
enum hasIndirections = anySatisfy!(.hasIndirections, FieldTypeTuple!T);
else static if (isStaticArray!T && is(T : E[N], E, size_t N))
enum hasIndirections = is(E == void) ? true : hasIndirections!E;
else static if (isFunctionPointer!T)
enum hasIndirections = false;
else
enum hasIndirections = isPointer!T || isDelegate!T || isDynamicArray!T ||
isAssociativeArray!T || is (T == class) || is(T == interface);
}
unittest
{
static assert( hasIndirections!(int[string]));
static assert( hasIndirections!(void delegate()));
static assert( hasIndirections!(void delegate() immutable));
static assert( hasIndirections!(immutable(void delegate())));
static assert( hasIndirections!(immutable(void delegate() immutable)));
static assert(!hasIndirections!(void function()));
static assert( hasIndirections!(void*[1]));
static assert(!hasIndirections!(byte[1]));
// void static array hides actual type of bits, so "may have indirections".
static assert( hasIndirections!(void[1]));
interface I {}
struct S1 {}
struct S2 { int a; }
struct S3 { int a; int b; }
struct S4 { int a; int* b; }
struct S5 { int a; Object b; }
struct S6 { int a; string b; }
struct S7 { int a; immutable Object b; }
struct S8 { int a; immutable I b; }
struct S9 { int a; void delegate() b; }
struct S10 { int a; immutable(void delegate()) b; }
struct S11 { int a; void delegate() immutable b; }
struct S12 { int a; immutable(void delegate() immutable) b; }
class S13 {}
class S14 { int a; }
class S15 { int a; int b; }
class S16 { int a; Object b; }
class S17 { string a; }
class S18 { int a; immutable Object b; }
class S19 { int a; immutable(void delegate() immutable) b; }
union S20 {}
union S21 { int a; }
union S22 { int a; int b; }
union S23 { int a; Object b; }
union S24 { string a; }
union S25 { int a; immutable Object b; }
union S26 { int a; immutable(void delegate() immutable) b; }
static assert( hasIndirections!I);
static assert(!hasIndirections!S1);
static assert(!hasIndirections!S2);
static assert(!hasIndirections!S3);
static assert( hasIndirections!S4);
static assert( hasIndirections!S5);
static assert( hasIndirections!S6);
static assert( hasIndirections!S7);
static assert( hasIndirections!S8);
static assert( hasIndirections!S9);
static assert( hasIndirections!S10);
static assert( hasIndirections!S12);
static assert( hasIndirections!S13);
static assert( hasIndirections!S14);
static assert( hasIndirections!S15);
static assert( hasIndirections!S16);
static assert( hasIndirections!S17);
static assert( hasIndirections!S18);
static assert( hasIndirections!S19);
static assert(!hasIndirections!S20);
static assert(!hasIndirections!S21);
static assert(!hasIndirections!S22);
static assert( hasIndirections!S23);
static assert( hasIndirections!S24);
static assert( hasIndirections!S25);
static assert( hasIndirections!S26);
}
unittest //12000
{
static struct S(T)
{
static assert(hasIndirections!T);
}
static class A(T)
{
S!A a;
}
A!int dummy;
}
//Explicitly undocumented. They will be removed in December 2014.
deprecated("Please use hasLocalAliasing instead.") alias hasLocalAliasing = hasUnsharedAliasing;
deprecated("Please use hasRawLocalAliasing instead.") alias hasRawLocalAliasing = hasRawUnsharedAliasing;
deprecated("Please use hasLocalObjects instead.") alias hasLocalObjects = hasUnsharedObjects;
/**
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...)
{
import std.typecons : Rebindable;
static if (!T.length)
{
enum hasUnsharedAliasing = false;
}
else static if (is(T[0] R: Rebindable!R))
{
enum hasUnsharedAliasing = hasUnsharedAliasing!R;
}
else
{
template unsharedDelegate(T)
{
enum bool unsharedDelegate = isDelegate!T
&& !is(T == shared)
&& !is(T == shared)
&& !is(T == immutable)
&& !is(FunctionTypeOf!T == shared)
&& !is(FunctionTypeOf!T == immutable);
}
enum hasUnsharedAliasing =
hasRawUnsharedAliasing!(T[0]) ||
anySatisfy!(unsharedDelegate, RepresentationTypeTuple!(T[0])) ||
hasUnsharedObjects!(T[0]) ||
hasUnsharedAliasing!(T[1..$]);
}
}
unittest
{
struct S1 { int a; Object b; }
struct S2 { string a; }
struct S3 { int a; immutable Object b; }
static assert( hasUnsharedAliasing!S1);
static assert(!hasUnsharedAliasing!S2);
static assert(!hasUnsharedAliasing!S3);
struct S4 { int a; shared Object b; }
struct S5 { char[] a; }
struct S6 { shared char[] b; }
struct S7 { float[3] vals; }
static assert(!hasUnsharedAliasing!S4);
static assert( hasUnsharedAliasing!S5);
static assert(!hasUnsharedAliasing!S6);
static assert(!hasUnsharedAliasing!S7);
/* Issue 6642 */
import std.typecons : Rebindable;
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!(void delegate() const));
static assert(!hasUnsharedAliasing!(void delegate() immutable));
static assert(!hasUnsharedAliasing!(void delegate() shared));
static assert(!hasUnsharedAliasing!(void delegate() shared const));
static assert( hasUnsharedAliasing!(const(void delegate())));
static assert( hasUnsharedAliasing!(const(void delegate() const)));
static assert(!hasUnsharedAliasing!(const(void delegate() immutable)));
static assert(!hasUnsharedAliasing!(const(void delegate() shared)));
static assert(!hasUnsharedAliasing!(const(void delegate() shared const)));
static assert(!hasUnsharedAliasing!(immutable(void delegate())));
static assert(!hasUnsharedAliasing!(immutable(void delegate() const)));
static assert(!hasUnsharedAliasing!(immutable(void delegate() immutable)));
static assert(!hasUnsharedAliasing!(immutable(void delegate() shared)));
static assert(!hasUnsharedAliasing!(immutable(void delegate() shared const)));
static assert(!hasUnsharedAliasing!(shared(void delegate())));
static assert(!hasUnsharedAliasing!(shared(void delegate() const)));
static assert(!hasUnsharedAliasing!(shared(void delegate() immutable)));
static assert(!hasUnsharedAliasing!(shared(void delegate() shared)));
static assert(!hasUnsharedAliasing!(shared(void delegate() shared const)));
static assert(!hasUnsharedAliasing!(shared(const(void delegate()))));
static assert(!hasUnsharedAliasing!(shared(const(void delegate() const))));
static assert(!hasUnsharedAliasing!(shared(const(void delegate() immutable))));
static assert(!hasUnsharedAliasing!(shared(const(void delegate() shared))));
static assert(!hasUnsharedAliasing!(shared(const(void delegate() shared const))));
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!());
struct S9
{
void delegate() shared a;
void delegate() immutable b;
void delegate() shared const c;
shared(void delegate()) d;
shared(void delegate() shared) e;
shared(void delegate() immutable) f;
shared(void delegate() shared const) g;
immutable(void delegate()) h;
immutable(void delegate() shared) i;
immutable(void delegate() immutable) j;
immutable(void delegate() shared const) k;
shared(const(void delegate())) l;
shared(const(void delegate() shared)) m;
shared(const(void delegate() immutable)) n;
shared(const(void delegate() shared const)) o;
}
struct S10 { typeof(S9.tupleof) a; void delegate() p; }
struct S11 { typeof(S9.tupleof) a; Object p; }
struct S12 { typeof(S9.tupleof) a; int* p; }
class S13 { typeof(S9.tupleof) a; }
class S14 { typeof(S9.tupleof) a; void delegate() p; }
class S15 { typeof(S9.tupleof) a; Object p; }
class S16 { typeof(S9.tupleof) a; int* p; }
static assert(!hasUnsharedAliasing!S9);
static assert(!hasUnsharedAliasing!(immutable(S9)));
static assert(!hasUnsharedAliasing!(shared(S9)));
static assert( hasUnsharedAliasing!S10);
static assert(!hasUnsharedAliasing!(immutable(S10)));
static assert(!hasUnsharedAliasing!(shared(S10)));
static assert( hasUnsharedAliasing!S11);
static assert(!hasUnsharedAliasing!(immutable(S11)));
static assert(!hasUnsharedAliasing!(shared(S11)));
static assert( hasUnsharedAliasing!S12);
static assert(!hasUnsharedAliasing!(immutable(S12)));
static assert(!hasUnsharedAliasing!(shared(S12)));
static assert( hasUnsharedAliasing!S13);
static assert(!hasUnsharedAliasing!(immutable(S13)));
static assert(!hasUnsharedAliasing!(shared(S13)));
static assert( hasUnsharedAliasing!S14);
static assert(!hasUnsharedAliasing!(immutable(S14)));
static assert(!hasUnsharedAliasing!(shared(S14)));
static assert( hasUnsharedAliasing!S15);
static assert(!hasUnsharedAliasing!(immutable(S15)));
static assert(!hasUnsharedAliasing!(shared(S15)));
static assert( hasUnsharedAliasing!S16);
static assert(!hasUnsharedAliasing!(immutable(S16)));
static assert(!hasUnsharedAliasing!(shared(S16)));
struct S17 {}
class S18 {}
interface S19 {}
union S20 {}
static assert(!hasUnsharedAliasing!S17);
static assert( hasUnsharedAliasing!S18);
static assert( hasUnsharedAliasing!S19);
static assert(!hasUnsharedAliasing!S20);
}
/**
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).
Classes and unions never have elaborate copy constructors.
*/
template hasElaborateCopyConstructor(S)
{
static if(isStaticArray!S && S.length)
{
enum bool hasElaborateCopyConstructor = hasElaborateCopyConstructor!(typeof(S.init[0]));
}
else static if(is(S == struct))
{
enum hasElaborateCopyConstructor = hasMember!(S, "__postblit")
|| anySatisfy!(.hasElaborateCopyConstructor, FieldTypeTuple!S);
}
else
{
enum bool hasElaborateCopyConstructor = false;
}
}
unittest
{
static assert(!hasElaborateCopyConstructor!int);
static struct S1 { }
static struct S2 { this(this) {} }
static struct S3 { S2 field; }
static struct S4 { S3[1] field; }
static struct S5 { S3[] field; }
static struct S6 { S3[0] field; }
static struct S7 { @disable this(); S3 field; }
static assert(!hasElaborateCopyConstructor!S1);
static assert( hasElaborateCopyConstructor!S2);
static assert( hasElaborateCopyConstructor!(immutable S2));
static assert( hasElaborateCopyConstructor!S3);
static assert( hasElaborateCopyConstructor!(S3[1]));
static assert(!hasElaborateCopyConstructor!(S3[0]));
static assert( hasElaborateCopyConstructor!S4);
static assert(!hasElaborateCopyConstructor!S5);
static assert(!hasElaborateCopyConstructor!S6);
static assert( hasElaborateCopyConstructor!S7);
}
/**
True if $(D S) or any type directly embedded in the representation of $(D S)
defines an elaborate assignment. Elaborate assignments are introduced by
defining $(D opAssign(typeof(this))) or $(D opAssign(ref typeof(this)))
for a $(D struct) or when there is a compiler-generated $(D opAssign).
A type $(D S) gets compiler-generated $(D opAssign) in case it has
an elaborate copy constructor or elaborate destructor.
Classes and unions never have elaborate assignments.
Note: Structs with (possibly nested) postblit operator(s) will have a
hidden yet elaborate compiler generated assignment operator (unless
explicitly disabled).
*/
template hasElaborateAssign(S)
{
static if(isStaticArray!S && S.length)
{
enum bool hasElaborateAssign = hasElaborateAssign!(typeof(S.init[0]));
}
else static if(is(S == struct))
{
enum hasElaborateAssign = is(typeof(S.init.opAssign(rvalueOf!S))) ||
is(typeof(S.init.opAssign(lvalueOf!S))) ||
anySatisfy!(.hasElaborateAssign, FieldTypeTuple!S);
}
else
{
enum bool hasElaborateAssign = false;
}
}
unittest
{
static assert(!hasElaborateAssign!int);
static struct S { void opAssign(S) {} }
static assert( hasElaborateAssign!S);
static assert(!hasElaborateAssign!(const(S)));
static struct S1 { void opAssign(ref S1) {} }
static struct S2 { void opAssign(int) {} }
static struct S3 { S s; }
static assert( hasElaborateAssign!S1);
static assert(!hasElaborateAssign!S2);
static assert( hasElaborateAssign!S3);
static assert( hasElaborateAssign!(S3[1]));
static assert(!hasElaborateAssign!(S3[0]));
static struct S4
{
void opAssign(U)(U u) {}
@disable void opAssign(U)(ref U u);
}
static assert( hasElaborateAssign!S4);
static struct S41
{
void opAssign(U)(ref U u) {}
@disable void opAssign(U)(U u);
}
static assert( hasElaborateAssign!S41);
static struct S5 { @disable this(); this(int n){ s = S(); } S s; }
static assert( hasElaborateAssign!S5);
static struct S6 { this(this) {} }
static struct S7 { this(this) {} @disable void opAssign(S7); }
static struct S8 { this(this) {} @disable void opAssign(S8); void opAssign(int) {} }
static struct S9 { this(this) {} void opAssign(int) {} }
static struct S10 { ~this() { } }
static assert( hasElaborateAssign!S6);
static assert(!hasElaborateAssign!S7);
static assert(!hasElaborateAssign!S8);
static assert( hasElaborateAssign!S9);
static assert( hasElaborateAssign!S10);
static struct SS6 { S6 s; }
static struct SS7 { S7 s; }
static struct SS8 { S8 s; }
static struct SS9 { S9 s; }
static assert( hasElaborateAssign!SS6);
static assert( hasElaborateAssign!SS7);
static assert( hasElaborateAssign!SS8);
static assert( hasElaborateAssign!SS9);
}
/**
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).
Classes and unions never have elaborate destructors, even
though classes may define $(D ~this()).
*/
template hasElaborateDestructor(S)
{
static if(isStaticArray!S && S.length)
{
enum bool hasElaborateDestructor = hasElaborateDestructor!(typeof(S.init[0]));
}
else static if(is(S == struct))
{
enum hasElaborateDestructor = hasMember!(S, "__dtor")
|| anySatisfy!(.hasElaborateDestructor, FieldTypeTuple!S);
}
else
{
enum bool hasElaborateDestructor = false;
}
}
unittest
{
static assert(!hasElaborateDestructor!int);
static struct S1 { }
static struct S2 { ~this() {} }
static struct S3 { S2 field; }
static struct S4 { S3[1] field; }
static struct S5 { S3[] field; }
static struct S6 { S3[0] field; }
static struct S7 { @disable this(); S3 field; }
static assert(!hasElaborateDestructor!S1);
static assert( hasElaborateDestructor!S2);
static assert( hasElaborateDestructor!(immutable S2));
static assert( hasElaborateDestructor!S3);
static assert( hasElaborateDestructor!(S3[1]));
static assert(!hasElaborateDestructor!(S3[0]));
static assert( hasElaborateDestructor!S4);
static assert(!hasElaborateDestructor!S5);
static assert(!hasElaborateDestructor!S6);
static assert( hasElaborateDestructor!S7);
}
alias Identity(alias A) = A;
/**
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 ||
__traits(compiles, { mixin("alias Sym = Identity!(T."~name~");"); });
}
else
{
enum bool hasMember = false;
}
}
unittest
{
//pragma(msg, __traits(allMembers, void delegate()));
static assert(!hasMember!(int, "blah"));
struct S1 { int blah; }
struct S2 { int blah(){ return 0; } }
class C1 { int blah; }
class C2 { int blah(){ return 0; } }
static assert(hasMember!(S1, "blah"));
static assert(hasMember!(S2, "blah"));
static assert(hasMember!(C1, "blah"));
static assert(hasMember!(C2, "blah"));
}
unittest
{
// 8321
struct S {
int x;
void f(){}
void t()(){}
template T(){}
}
struct R1(T) {
T t;
alias t this;
}
struct R2(T) {
T t;
@property ref inout(T) payload() inout { return t; }
alias t this;
}
static assert(hasMember!(S, "x"));
static assert(hasMember!(S, "f"));
static assert(hasMember!(S, "t"));
static assert(hasMember!(S, "T"));
static assert(hasMember!(R1!S, "x"));
static assert(hasMember!(R1!S, "f"));
static assert(hasMember!(R1!S, "t"));
static assert(hasMember!(R1!S, "T"));
static assert(hasMember!(R2!S, "x"));
static assert(hasMember!(R2!S, "f"));
static assert(hasMember!(R2!S, "t"));
static assert(hasMember!(R2!S, "T"));
}
/**
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:
An enum can have multiple members which have the same value. If you want
to use EnumMembers to e.g. generate switch cases at compile-time,
you should use the $(XREF typetuple, NoDuplicates) template to avoid
generating duplicate switch cases.
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))
{
// Supply the specified identifier to an constant value.
template WithIdentifier(string ident)
{
static if (ident == "Symbolize")
{
template Symbolize(alias value)
{
enum Symbolize = value;
}
}
else
{
mixin("template Symbolize(alias "~ ident ~")"
~"{"
~"alias Symbolize = "~ ident ~";"
~"}");
}
}
template EnumSpecificMembers(names...)
{
static if (names.length > 0)
{
alias EnumSpecificMembers =
TypeTuple!(
WithIdentifier!(names[0])
.Symbolize!(__traits(getMember, E, names[0])),
EnumSpecificMembers!(names[1 .. $])
);
}
else
{
alias EnumSpecificMembers = TypeTuple!();
}
}
alias EnumMembers = EnumSpecificMembers!(__traits(allMembers, E));
}
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 ]);
}
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 TL = BaseTypeTuple!B;
* writeln(typeid(TL)); // prints: (A,I)
* }
* ---
*/
template BaseTypeTuple(A)
{
static if (is(A P == super))
alias BaseTypeTuple = P;
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 TL = BaseTypeTuple!C;
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 TL = BaseClassesTuple!C;
* writeln(typeid(TL)); // prints: (B,A,Object)
* }
* ---
*/
template BaseClassesTuple(T)
if (is(T == class))
{
static if (is(T == Object))
{
alias BaseClassesTuple = TypeTuple!();
}
else static if (is(BaseTypeTuple!T[0] == Object))
{
alias BaseClassesTuple = TypeTuple!Object;
}
else
{
alias BaseClassesTuple =
TypeTuple!(BaseTypeTuple!T[0],
BaseClassesTuple!(BaseTypeTuple!T[0]));
}
}
unittest
{
class C1 { }
class C2 : C1 { }
class C3 : C2 { }
static assert(!BaseClassesTuple!Object.length);
static assert(is(BaseClassesTuple!C1 == TypeTuple!(Object)));
static assert(is(BaseClassesTuple!C2 == TypeTuple!(C1, Object)));
static assert(is(BaseClassesTuple!C3 == TypeTuple!(C2, C1, Object)));
static assert(!BaseClassesTuple!Object.length);
struct S { }
static assert(!__traits(compiles, BaseClassesTuple!S));
interface I { }
static assert(!__traits(compiles, BaseClassesTuple!I));
class C4 : I { }
class C5 : C4, I { }
static assert(is(BaseClassesTuple!C5 == TypeTuple!(C4, Object)));
}
/**
* 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 TL = InterfacesTuple!C;
* writeln(typeid(TL)); // prints: (I1, I2)
* }
* ---
*/
template InterfacesTuple(T)
{
template Flatten(H, T...)
{
static if (T.length)
{
alias Flatten = TypeTuple!(Flatten!H, Flatten!T);
}
else
{
static if (is(H == interface))
alias Flatten = TypeTuple!(H, InterfacesTuple!H);
else
alias Flatten = InterfacesTuple!H;
}
}
static if (is(T S == super) && S.length)
alias InterfacesTuple = NoDuplicates!(Flatten!S);
else
alias InterfacesTuple = TypeTuple!();
}
unittest
{
{
// doc example
interface I1 {}
interface I2 {}
class A : I1, I2 { }
class B : A, I1 { }
class C : B { }
alias TL = InterfacesTuple!C;
static assert(is(TL[0] == I1) && is(TL[1] == I2));
}
{
interface Iaa {}
interface Iab {}
interface Iba {}
interface Ibb {}
interface Ia : Iaa, Iab {}
interface Ib : Iba, Ibb {}
interface I : Ia, Ib {}
interface J {}
class B2 : J {}
class C2 : B2, Ia, Ib {}
static assert(is(InterfacesTuple!I ==
TypeTuple!(Ia, Iaa, Iab, Ib, Iba, Ibb)));
static assert(is(InterfacesTuple!C2 ==
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 TL = TransitiveBaseTypeTuple!C;
* writeln(typeid(TL)); // prints: (B,A,Object,I)
* }
* ---
*/
template TransitiveBaseTypeTuple(T)
{
static if (is(T == Object))
alias TransitiveBaseTypeTuple = TypeTuple!();
else
alias TransitiveBaseTypeTuple =
TypeTuple!(BaseClassesTuple!T, InterfacesTuple!T);
}
unittest
{
interface J1 {}
interface J2 {}
class B1 {}
class B2 : B1, J1, J2 {}
class B3 : B2, J1 {}
alias TL = TransitiveBaseTypeTuple!B3;
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))
{
/*
* 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]),
walkThru!(Parents[1 .. $])
) walkThru;
else
alias TypeTuple!() walkThru;
}
static if (is(Node Parents == super))
alias TypeTuple!(inSight, walkThru!Parents) CollectOverloads;
else
alias TypeTuple!inSight CollectOverloads;
}
else
alias TypeTuple!() CollectOverloads; // no overloads in this hierarchy
}
// duplicates in this tuple will be removed by shrink()
alias CollectOverloads!C overloads;
// shrinkOne!args[0] = the most derived one in the covariant siblings of target
// shrinkOne!args[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 .. $]) shrinkOne;
else static if (isCovariantWith!(Rest0, Target))
// rest[0] overrides target -- erase target.
alias shrinkOne!(rest[0], rest[1 .. $]) shrinkOne;
else
// target and rest[0] are distinct.
alias TypeTuple!(
shrinkOne!(target, rest[1 .. $]),
rest[0] // keep
) shrinkOne;
}
else
alias TypeTuple!target shrinkOne; // done
}
/*
* Now shrink covariant overloads into one.
*/
template shrink(overloads...)
{
static if (overloads.length > 0)
{
alias shrinkOne!overloads temp;
alias TypeTuple!(temp[0], shrink!(temp[1 .. $])) shrink;
}
else
alias TypeTuple!() shrink; // done
}
// done.
alias shrink!overloads MemberFunctionsTuple;
}
else
alias TypeTuple!() MemberFunctionsTuple;
}
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 test =MemberFunctionsTuple!(C, "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 noexist = MemberFunctionsTuple!(C, "noexist");
static assert(noexist.length == 0);
interface L { int prop() @property; }
alias prop = MemberFunctionsTuple!(L, "prop");
static assert(prop.length == 1);
interface Test_I
{
void foo();
void foo(int);
void foo(int, int);
}
interface Test : Test_I {}
alias Test_foo = MemberFunctionsTuple!(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)));
}
/**
Returns an alias to the template that $(D T) is an instance of.
Example:
--------------------
struct Foo(T, U) {}
static assert(__traits(isSame, TemplateOf!(Foo!(int, real)), Foo));
--------------------
*/
template TemplateOf(alias T : Base!Args, alias Base, Args...)
{
alias TemplateOf = Base;
}
template TemplateOf(T : Base!Args, alias Base, Args...)
{
alias TemplateOf = Base;
}
unittest
{
template Foo1(A) {}
template Foo2(A, B) {}
template Foo3(alias A) {}
template Foo4(string A) {}
struct Foo5(A) {}
struct Foo6(A, B) {}
struct Foo7(alias A) {}
template Foo8(A) { template Foo9(B) {} }
template Foo10() {}
static assert(__traits(isSame, TemplateOf!(Foo1!(int)), Foo1));
static assert(__traits(isSame, TemplateOf!(Foo2!(int, int)), Foo2));
static assert(__traits(isSame, TemplateOf!(Foo3!(123)), Foo3));
static assert(__traits(isSame, TemplateOf!(Foo4!("123")), Foo4));
static assert(__traits(isSame, TemplateOf!(Foo5!(int)), Foo5));
static assert(__traits(isSame, TemplateOf!(Foo6!(int, int)), Foo6));
static assert(__traits(isSame, TemplateOf!(Foo7!(123)), Foo7));
static assert(__traits(isSame, TemplateOf!(Foo8!(int).Foo9!(real)), Foo8!(int).Foo9));
static assert(__traits(isSame, TemplateOf!(Foo10!()), Foo10));
}
/**
Returns a $(D TypeTuple) of the template arguments used to instantiate $(D T).
Example:
--------------------
struct Foo(T, U) {}
static assert(is(TemplateArgsOf!(Foo!(int, real)) == TypeTuple!(int, real)));
--------------------
*/
template TemplateArgsOf(alias T : Base!Args, alias Base, Args...)
{
alias TemplateArgsOf = Args;
}
template TemplateArgsOf(T : Base!Args, alias Base, Args...)
{
alias TemplateArgsOf = Args;
}
unittest
{
template Foo1(A) {}
template Foo2(A, B) {}
template Foo3(alias A) {}
template Foo4(string A) {}
struct Foo5(A) {}
struct Foo6(A, B) {}
struct Foo7(alias A) {}
template Foo8(A) { template Foo9(B) {} }
template Foo10() {}
enum x = 123;
enum y = "123";
static assert(is(TemplateArgsOf!(Foo1!(int)) == TypeTuple!(int)));
static assert(is(TemplateArgsOf!(Foo2!(int, int)) == TypeTuple!(int, int)));
static assert(__traits(isSame, TemplateArgsOf!(Foo3!(x)), TypeTuple!(x)));
static assert(TemplateArgsOf!(Foo4!(y)) == TypeTuple!(y));
static assert(is(TemplateArgsOf!(Foo5!(int)) == TypeTuple!(int)));
static assert(is(TemplateArgsOf!(Foo6!(int, int)) == TypeTuple!(int, int)));
static assert(__traits(isSame, TemplateArgsOf!(Foo7!(x)), TypeTuple!(x)));
static assert(is(TemplateArgsOf!(Foo8!(int).Foo9!(real)) == TypeTuple!(real)));
static assert(is(TemplateArgsOf!(Foo10!()) == TypeTuple!()));
}
private template maxAlignment(U...) if (isTypeTuple!U)
{
static if (U.length == 0)
static assert(0);
else static if (U.length == 1)
enum maxAlignment = U[0].alignof;
else
{
import std.algorithm : max;
enum maxAlignment = max(staticMap!(.maxAlignment, U));
}
}
/**
Returns class instance alignment.
*/
template classInstanceAlignment(T) if(is(T == class))
{
alias classInstanceAlignment = maxAlignment!(void*, typeof(T.tupleof));
}
///
unittest
{
class A { byte b; }
class B { long l; }
// As class instance always has a hidden pointer
static assert(classInstanceAlignment!A == (void*).alignof);
static assert(classInstanceAlignment!B == long.alignof);
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// 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.
*/
template CommonType(T...)
{
static if (!T.length)
{
alias CommonType = void;
}
else static if (T.length == 1)
{
static if(is(typeof(T[0])))
{
alias CommonType = typeof(T[0]);
}
else
{
alias CommonType = T[0];
}
}
else static if (is(typeof(true ? T[0].init : T[1].init) U))
{
alias CommonType = CommonType!(U, T[2 .. $]);
}
else
alias CommonType = void;
}
///
unittest
{
alias X = CommonType!(int, long, short);
assert(is(X == long));
alias Y = CommonType!(int, char[], short);
assert(is(Y == void));
}
unittest
{
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 ImplicitConversionTargets =
TypeTuple!(byte, ubyte, short, ushort, int, uint, long, ulong,
float, double, real, char, wchar, dchar);
else static if (is(T == byte))
alias ImplicitConversionTargets =
TypeTuple!(short, ushort, int, uint, long, ulong,
float, double, real, char, wchar, dchar);
else static if (is(T == ubyte))
alias ImplicitConversionTargets =
TypeTuple!(short, ushort, int, uint, long, ulong,
float, double, real, char, wchar, dchar);
else static if (is(T == short))
alias ImplicitConversionTargets =
TypeTuple!(int, uint, long, ulong, float, double, real);
else static if (is(T == ushort))
alias ImplicitConversionTargets =
TypeTuple!(int, uint, long, ulong, float, double, real);
else static if (is(T == int))
alias ImplicitConversionTargets =
TypeTuple!(long, ulong, float, double, real);
else static if (is(T == uint))
alias ImplicitConversionTargets =
TypeTuple!(long, ulong, float, double, real);
else static if (is(T == long))
alias ImplicitConversionTargets = TypeTuple!(float, double, real);
else static if (is(T == ulong))
alias ImplicitConversionTargets = TypeTuple!(float, double, real);
else static if (is(T == float))
alias ImplicitConversionTargets = TypeTuple!(double, real);
else static if (is(T == double))
alias ImplicitConversionTargets = TypeTuple!real;
else static if (is(T == char))
alias ImplicitConversionTargets =
TypeTuple!(wchar, dchar, byte, ubyte, short, ushort,
int, uint, long, ulong, float, double, real);
else static if (is(T == wchar))
alias ImplicitConversionTargets =
TypeTuple!(dchar, short, ushort, int, uint, long, ulong,
float, double, real);
else static if (is(T == dchar))
alias ImplicitConversionTargets =
TypeTuple!(int, uint, long, ulong, float, double, real);
else static if (is(T : typeof(null)))
alias ImplicitConversionTargets = TypeTuple!(typeof(null));
else static if(is(T : Object))
alias ImplicitConversionTargets = TransitiveBaseTypeTuple!(T);
else static if (isDynamicArray!T && !is(typeof(T.init[0]) == const))
alias ImplicitConversionTargets =
TypeTuple!(const(Unqual!(typeof(T.init[0])))[]);
else static if (is(T : void*))
alias ImplicitConversionTargets = TypeTuple!(void*);
else
alias ImplicitConversionTargets = TypeTuple!();
}
unittest
{
static assert(is(ImplicitConversionTargets!(double)[0] == real));
static assert(is(ImplicitConversionTargets!(string)[0] == const(char)[]));
}
/**
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).
$(D isAssignable) returns whether both an lvalue and rvalue can be assigned.
If you omit $(D Rhs), $(D isAssignable) will check identity assignable of $(D Lhs).
*/
enum isAssignable(Lhs, Rhs = Lhs) = isRvalueAssignable!(Lhs, Rhs) && isLvalueAssignable!(Lhs, Rhs);
///
unittest
{
static assert( isAssignable!(long, int));
static assert(!isAssignable!(int, long));
static assert( isAssignable!(const(char)[], string));
static assert(!isAssignable!(string, char[]));
// int is assignable to int
static assert( isAssignable!int);
// immutable int is not assignable to immutable int
static assert(!isAssignable!(immutable int));
}
// ditto
private enum isRvalueAssignable(Lhs, Rhs = Lhs) = __traits(compiles, lvalueOf!Lhs = rvalueOf!Rhs);
// ditto
private enum isLvalueAssignable(Lhs, Rhs = Lhs) = __traits(compiles, lvalueOf!Lhs = lvalueOf!Rhs);
unittest
{
static assert(!isAssignable!(immutable int, int));
static assert( isAssignable!(int, immutable int));
static assert(!isAssignable!(inout int, int));
static assert( isAssignable!(int, inout int));
static assert(!isAssignable!(inout int));
static assert( isAssignable!(shared int, int));
static assert( isAssignable!(int, shared int));
static assert( isAssignable!(shared int));
static assert( isAssignable!(void[1], void[1]));
struct S { @disable this(); this(int n){} }
static assert( isAssignable!(S, S));
struct S2 { this(int n){} }
static assert( isAssignable!(S2, S2));
static assert(!isAssignable!(S2, int));
struct S3 { @disable void opAssign(); }
static assert( isAssignable!(S3, S3));
struct S3X { @disable void opAssign(S3X); }
static assert(!isAssignable!(S3X, S3X));
struct S4 { void opAssign(int); }
static assert( isAssignable!(S4, S4));
static assert( isAssignable!(S4, int));
static assert( isAssignable!(S4, immutable int));
struct S5 { @disable this(); @disable this(this); }
struct S6 { void opAssign(in ref S5); }
static assert(!isAssignable!(S6, S5));
static assert(!isRvalueAssignable!(S6, S5));
static assert( isLvalueAssignable!(S6, S5));
static assert( isLvalueAssignable!(S6, immutable S5));
}
// Equivalent with TypeStruct::isAssignable in compiler code.
package template isBlitAssignable(T)
{
static if (is(OriginalType!T U) && !is(T == U))
{
enum isBlitAssignable = isBlitAssignable!U;
}
else static if (isStaticArray!T && is(T == E[n], E, size_t n))
// Workaround for issue 11499 : isStaticArray!T should not be necessary.
{
enum isBlitAssignable = isBlitAssignable!E;
}
else static if (is(T == struct) || is(T == union))
{
enum isBlitAssignable = isMutable!T &&
{
size_t offset = 0;
bool assignable = true;
foreach (i, F; FieldTypeTuple!T)
{
static if (i == 0)
{
}
else if (T.tupleof[i].offsetof == offset)
{
if (assignable)
continue;
}
else
{
if (!assignable)
return false;
}
assignable = isBlitAssignable!(typeof(T.tupleof[i]));
offset = T.tupleof[i].offsetof;
}
return assignable;
}();
}
else
enum isBlitAssignable = isMutable!T;
}
unittest
{
static assert( isBlitAssignable!int);
static assert(!isBlitAssignable!(const int));
class C{ const int i; }
static assert( isBlitAssignable!C);
struct S1{ int i; }
struct S2{ const int i; }
static assert( isBlitAssignable!S1);
static assert(!isBlitAssignable!S2);
struct S3X { union { int x; int y; } }
struct S3Y { union { int x; const int y; } }
struct S3Z { union { const int x; const int y; } }
static assert( isBlitAssignable!(S3X));
static assert( isBlitAssignable!(S3Y));
static assert(!isBlitAssignable!(S3Z));
static assert(!isBlitAssignable!(const S3X));
static assert(!isBlitAssignable!(inout S3Y));
static assert(!isBlitAssignable!(immutable S3Z));
static assert( isBlitAssignable!(S3X[3]));
static assert( isBlitAssignable!(S3Y[3]));
static assert(!isBlitAssignable!(S3Z[3]));
enum ES3X : S3X { a = S3X() }
enum ES3Y : S3Y { a = S3Y() }
enum ES3Z : S3Z { a = S3Z() }
static assert( isBlitAssignable!(ES3X));
static assert( isBlitAssignable!(ES3Y));
static assert(!isBlitAssignable!(ES3Z));
static assert(!isBlitAssignable!(const ES3X));
static assert(!isBlitAssignable!(inout ES3Y));
static assert(!isBlitAssignable!(immutable ES3Z));
static assert( isBlitAssignable!(ES3X[3]));
static assert( isBlitAssignable!(ES3Y[3]));
static assert(!isBlitAssignable!(ES3Z[3]));
union U1X { int x; int y; }
union U1Y { int x; const int y; }
union U1Z { const int x; const int y; }
static assert( isBlitAssignable!(U1X));
static assert( isBlitAssignable!(U1Y));
static assert(!isBlitAssignable!(U1Z));
static assert(!isBlitAssignable!(const U1X));
static assert(!isBlitAssignable!(inout U1Y));
static assert(!isBlitAssignable!(immutable U1Z));
static assert( isBlitAssignable!(U1X[3]));
static assert( isBlitAssignable!(U1Y[3]));
static assert(!isBlitAssignable!(U1Z[3]));
enum EU1X : U1X { a = U1X() }
enum EU1Y : U1Y { a = U1Y() }
enum EU1Z : U1Z { a = U1Z() }
static assert( isBlitAssignable!(EU1X));
static assert( isBlitAssignable!(EU1Y));
static assert(!isBlitAssignable!(EU1Z));
static assert(!isBlitAssignable!(const EU1X));
static assert(!isBlitAssignable!(inout EU1Y));
static assert(!isBlitAssignable!(immutable EU1Z));
static assert( isBlitAssignable!(EU1X[3]));
static assert( isBlitAssignable!(EU1Y[3]));
static assert(!isBlitAssignable!(EU1Z[3]));
struct SA
{
@property int[3] foo() { return [1,2,3]; }
alias foo this;
const int x; // SA is not blit assignable
}
static assert(!isStaticArray!SA);
static assert(!isBlitAssignable!(SA[3]));
}
/*
Works like $(D isImplicitlyConvertible), except this cares only about storage
classes of the arguments.
*/
private template isStorageClassImplicitlyConvertible(From, To)
{
alias Pointify(T) = void*;
enum isStorageClassImplicitlyConvertible = isImplicitlyConvertible!(
ModifyTypePreservingSTC!(Pointify, From),
ModifyTypePreservingSTC!(Pointify, To) );
}
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
{
alias Upr = F;
alias Lwr = G;
/*
* 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 FA = FunctionAttribute;
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 STC = ParameterStorageClass;
alias UprParams = ParameterTypeTuple!Upr;
alias LwrParams = ParameterTypeTuple!Lwr;
alias UprPSTCs = ParameterStorageClassTuple!Upr;
alias LwrPSTCs = ParameterStorageClassTuple!Lwr;
//
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 isCovariantWith =
checkLinkage !().ok &&
checkVariadicity!().ok &&
checkSTC !().ok &&
checkAttributes !().ok &&
checkReturnType !().ok &&
checkParameters !().ok ;
}
}
unittest
{
enum bool isCovariantWith(alias f, alias g) = .isCovariantWith!(typeof(f), typeof(g));
// 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));
}
// Needed for rvalueOf/lvalueOf because "inout on return means
// inout must be on a parameter as well"
private struct __InoutWorkaroundStruct{}
/**
Creates an lvalue or rvalue of type $(D T) for $(D typeof(...)) and
$(D __traits(compiles, ...)) purposes. No actual value is returned.
Note: Trying to use returned value will result in a
"Symbol Undefined" error at link time.
Examples:
---
// Note that `f` doesn't have to be implemented
// as is isn't called.
int f(int);
bool f(ref int);
static assert(is(typeof(f(rvalueOf!int)) == int));
static assert(is(typeof(f(lvalueOf!int)) == bool));
int i = rvalueOf!int; // error, no actual value is returned
---
*/
@property T rvalueOf(T)(inout __InoutWorkaroundStruct = __InoutWorkaroundStruct.init);
/// ditto
@property ref T lvalueOf(T)(inout __InoutWorkaroundStruct = __InoutWorkaroundStruct.init);
// Note: unittest can't be used as an example here as function overloads
// aren't allowed inside functions.
unittest
{
void needLvalue(T)(ref T);
static struct S { }
int i;
struct Nested { void f() { ++i; } }
foreach(T; TypeTuple!(int, immutable int, inout int, string, S, Nested, Object))
{
static assert(!__traits(compiles, needLvalue(rvalueOf!T)));
static assert( __traits(compiles, needLvalue(lvalueOf!T)));
static assert(is(typeof(rvalueOf!T) == T));
static assert(is(typeof(lvalueOf!T) == T));
}
static assert(!__traits(compiles, rvalueOf!int = 1));
static assert( __traits(compiles, lvalueOf!byte = 127));
static assert(!__traits(compiles, lvalueOf!byte = 128));
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// SomethingTypeOf
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
private template AliasThisTypeOf(T) if (isAggregateType!T)
{
alias members = TypeTuple!(__traits(getAliasThis, T));
static if (members.length == 1)
{
alias AliasThisTypeOf = typeof(__traits(getMember, T.init, members[0]));
}
else
static assert(0, T.stringof~" does not have alias this type");
}
/*
*/
template BooleanTypeOf(T)
{
static if (is(AliasThisTypeOf!T AT) && !is(AT[] == AT))
alias X = BooleanTypeOf!AT;
else
alias X = OriginalType!T;
static if (is(Unqual!X == bool))
{
alias BooleanTypeOf = X;
}
else
static assert(0, T.stringof~" is not boolean type");
}
unittest
{
// unexpected failure, maybe dmd type-merging bug
foreach (T; TypeTuple!bool)
foreach (Q; TypeQualifierList)
{
static assert( is(Q!T == BooleanTypeOf!( Q!T )));
static assert( is(Q!T == BooleanTypeOf!( SubTypeOf!(Q!T) )));
}
foreach (T; TypeTuple!(void, NumericTypeList, ImaginaryTypeList, ComplexTypeList, CharTypeList))
foreach (Q; TypeQualifierList)
{
static assert(!is(BooleanTypeOf!( Q!T )), Q!T.stringof);
static assert(!is(BooleanTypeOf!( SubTypeOf!(Q!T) )));
}
}
unittest
{
struct B
{
bool val;
alias val this;
}
struct S
{
B b;
alias b this;
}
static assert(is(BooleanTypeOf!B == bool));
static assert(is(BooleanTypeOf!S == bool));
}
/*
*/
template IntegralTypeOf(T)
{
static if (is(AliasThisTypeOf!T AT) && !is(AT[] == AT))
alias X = IntegralTypeOf!AT;
else
alias X = OriginalType!T;
static if (staticIndexOf!(Unqual!X, IntegralTypeList) >= 0)
{
alias IntegralTypeOf = X;
}
else
static assert(0, T.stringof~" is not an integral type");
}
unittest
{
foreach (T; IntegralTypeList)
foreach (Q; TypeQualifierList)
{
static assert( is(Q!T == IntegralTypeOf!( Q!T )));
static assert( is(Q!T == IntegralTypeOf!( SubTypeOf!(Q!T) )));
}
foreach (T; TypeTuple!(void, bool, FloatingPointTypeList, ImaginaryTypeList, ComplexTypeList, CharTypeList))
foreach (Q; TypeQualifierList)
{
static assert(!is(IntegralTypeOf!( Q!T )));
static assert(!is(IntegralTypeOf!( SubTypeOf!(Q!T) )));
}
}
/*
*/
template FloatingPointTypeOf(T)
{
static if (is(AliasThisTypeOf!T AT) && !is(AT[] == AT))
alias X = FloatingPointTypeOf!AT;
else
alias X = OriginalType!T;
static if (staticIndexOf!(Unqual!X, FloatingPointTypeList) >= 0)
{
alias FloatingPointTypeOf = X;
}
else
static assert(0, T.stringof~" is not a floating point type");
}
unittest
{
foreach (T; FloatingPointTypeList)
foreach (Q; TypeQualifierList)
{
static assert( is(Q!T == FloatingPointTypeOf!( Q!T )));
static assert( is(Q!T == FloatingPointTypeOf!( SubTypeOf!(Q!T) )));
}
foreach (T; TypeTuple!(void, bool, IntegralTypeList, ImaginaryTypeList, ComplexTypeList, CharTypeList))
foreach (Q; TypeQualifierList)
{
static assert(!is(FloatingPointTypeOf!( Q!T )));
static assert(!is(FloatingPointTypeOf!( SubTypeOf!(Q!T) )));
}
}
/*
*/
template NumericTypeOf(T)
{
static if (is(IntegralTypeOf!T X) || is(FloatingPointTypeOf!T X))
{
alias NumericTypeOf = X;
}
else
static assert(0, T.stringof~" is not a numeric type");
}
unittest
{
foreach (T; NumericTypeList)
foreach (Q; TypeQualifierList)
{
static assert( is(Q!T == NumericTypeOf!( Q!T )));
static assert( is(Q!T == NumericTypeOf!( SubTypeOf!(Q!T) )));
}
foreach (T; TypeTuple!(void, bool, CharTypeList, ImaginaryTypeList, ComplexTypeList))
foreach (Q; TypeQualifierList)
{
static assert(!is(NumericTypeOf!( Q!T )));
static assert(!is(NumericTypeOf!( SubTypeOf!(Q!T) )));
}
}
/*
*/
template UnsignedTypeOf(T)
{
static if (is(IntegralTypeOf!T X) &&
staticIndexOf!(Unqual!X, UnsignedIntTypeList) >= 0)
alias UnsignedTypeOf = X;
else
static assert(0, T.stringof~" is not an unsigned type.");
}
/*
*/
template SignedTypeOf(T)
{
static if (is(IntegralTypeOf!T X) &&
staticIndexOf!(Unqual!X, SignedIntTypeList) >= 0)
alias SignedTypeOf = X;
else static if (is(FloatingPointTypeOf!T X))
alias SignedTypeOf = X;
else
static assert(0, T.stringof~" is not an signed type.");
}
/*
*/
template CharTypeOf(T)
{
static if (is(AliasThisTypeOf!T AT) && !is(AT[] == AT))
alias X = CharTypeOf!AT;
else
alias X = OriginalType!T;
static if (staticIndexOf!(Unqual!X, CharTypeList) >= 0)
{
alias CharTypeOf = X;
}
else
static assert(0, T.stringof~" is not a character type");
}
unittest
{
foreach (T; CharTypeList)
foreach (Q; TypeQualifierList)
{
static assert( is(CharTypeOf!( Q!T )));
static assert( is(CharTypeOf!( SubTypeOf!(Q!T) )));
}
foreach (T; TypeTuple!(void, bool, NumericTypeList, ImaginaryTypeList, ComplexTypeList))
foreach (Q; TypeQualifierList)
{
static assert(!is(CharTypeOf!( Q!T )));
static assert(!is(CharTypeOf!( SubTypeOf!(Q!T) )));
}
foreach (T; TypeTuple!(string, wstring, dstring, char[4]))
foreach (Q; TypeQualifierList)
{
static assert(!is(CharTypeOf!( Q!T )));
static assert(!is(CharTypeOf!( SubTypeOf!(Q!T) )));
}
}
/*
*/
template StaticArrayTypeOf(T)
{
static if (is(AliasThisTypeOf!T AT) && !is(AT[] == AT))
alias X = StaticArrayTypeOf!AT;
else
alias X = OriginalType!T;
static if (is(X : E[n], E, size_t n))
alias StaticArrayTypeOf = X;
else
static assert(0, T.stringof~" is not a static array type");
}
unittest
{
foreach (T; TypeTuple!(bool, NumericTypeList, ImaginaryTypeList, ComplexTypeList))
foreach (Q; TypeTuple!(TypeQualifierList, InoutOf, SharedInoutOf))
{
static assert(is( Q!( T[1] ) == StaticArrayTypeOf!( Q!( T[1] ) ) ));
foreach (P; TypeQualifierList)
{ // SubTypeOf cannot have inout type
static assert(is( Q!(P!(T[1])) == StaticArrayTypeOf!( Q!(SubTypeOf!(P!(T[1]))) ) ));
}
}
foreach (T; TypeTuple!void)
foreach (Q; TypeTuple!TypeQualifierList)
{
static assert(is( StaticArrayTypeOf!( Q!(void[1]) ) == Q!(void[1]) ));
}
}
/*
*/
template DynamicArrayTypeOf(T)
{
static if (is(AliasThisTypeOf!T AT) && !is(AT[] == AT))
alias X = DynamicArrayTypeOf!AT;
else
alias X = OriginalType!T;
static if (is(Unqual!X : E[], E) && !is(typeof({ enum n = X.length; })))
{
alias DynamicArrayTypeOf = X;
}
else
static assert(0, T.stringof~" is not a dynamic array");
}
unittest
{
foreach (T; TypeTuple!(/*void, */bool, NumericTypeList, ImaginaryTypeList, ComplexTypeList))
foreach (Q; TypeTuple!(TypeQualifierList, InoutOf, SharedInoutOf))
{
static assert(is( Q!T[] == DynamicArrayTypeOf!( Q!T[] ) ));
static assert(is( Q!(T[]) == DynamicArrayTypeOf!( Q!(T[]) ) ));
foreach (P; TypeTuple!(MutableOf, ConstOf, ImmutableOf))
{
static assert(is( Q!(P!T[]) == DynamicArrayTypeOf!( Q!(SubTypeOf!(P!T[])) ) ));
static assert(is( Q!(P!(T[])) == DynamicArrayTypeOf!( Q!(SubTypeOf!(P!(T[]))) ) ));
}
}
static assert(!is(DynamicArrayTypeOf!(int[3])));
static assert(!is(DynamicArrayTypeOf!(void[3])));
static assert(!is(DynamicArrayTypeOf!(typeof(null))));
}
/*
*/
template ArrayTypeOf(T)
{
static if (is(StaticArrayTypeOf!T X) || is(DynamicArrayTypeOf!T X))
{
alias ArrayTypeOf = X;
}
else
static assert(0, T.stringof~" is not an array type");
}
/*
Always returns the Dynamic Array version.
*/
template StringTypeOf(T)
{
static if (is(T == typeof(null)))
{
// It is impossible to determine exact string type from typeof(null) -
// it means that StringTypeOf!(typeof(null)) is undefined.
// Then this behavior is convenient for template constraint.
static assert(0, T.stringof~" is not a string type");
}
else static if (is(T : const char[]) || is(T : const wchar[]) || is(T : const dchar[]))
{
static if (is(T : U[], U))
alias StringTypeOf = U[];
else
static assert(0);
}
else
static assert(0, T.stringof~" is not a string type");
}
unittest
{
foreach (T; CharTypeList)
foreach (Q; TypeTuple!(MutableOf, ConstOf, ImmutableOf, InoutOf))
{
static assert(is(Q!T[] == StringTypeOf!( Q!T[] )));
static if (!__traits(isSame, Q, InoutOf))
{
static assert(is(Q!T[] == StringTypeOf!( SubTypeOf!(Q!T[]) )));
alias Str = Q!T[];
class C(S) { S val; alias val this; }
static assert(is(StringTypeOf!(C!Str) == Str));
}
}
foreach (T; CharTypeList)
foreach (Q; TypeTuple!(SharedOf, SharedConstOf, SharedInoutOf))
{
static assert(!is(StringTypeOf!( Q!T[] )));
}
}
unittest
{
static assert(is(StringTypeOf!(char[4]) == char[]));
}
/*
*/
template AssocArrayTypeOf(T)
{
static if (is(AliasThisTypeOf!T AT) && !is(AT[] == AT))
alias X = AssocArrayTypeOf!AT;
else
alias X = OriginalType!T;
static if (is(Unqual!X : V[K], K, V))
{
alias AssocArrayTypeOf = X;
}
else
static assert(0, T.stringof~" is not an associative array type");
}
unittest
{
foreach (T; TypeTuple!(int/*bool, CharTypeList, NumericTypeList, ImaginaryTypeList, ComplexTypeList*/))
foreach (P; TypeTuple!(TypeQualifierList, InoutOf, SharedInoutOf))
foreach (Q; TypeTuple!(TypeQualifierList, InoutOf, SharedInoutOf))
foreach (R; TypeTuple!(TypeQualifierList, InoutOf, SharedInoutOf))
{
static assert(is( P!(Q!T[R!T]) == AssocArrayTypeOf!( P!(Q!T[R!T]) ) ));
}
foreach (T; TypeTuple!(int/*bool, CharTypeList, NumericTypeList, ImaginaryTypeList, ComplexTypeList*/))
foreach (O; TypeTuple!(TypeQualifierList, InoutOf, SharedInoutOf))
foreach (P; TypeTuple!TypeQualifierList)
foreach (Q; TypeTuple!TypeQualifierList)
foreach (R; TypeTuple!TypeQualifierList)
{
static assert(is( O!(P!(Q!T[R!T])) == AssocArrayTypeOf!( O!(SubTypeOf!(P!(Q!T[R!T]))) ) ));
}
}
/*
*/
template BuiltinTypeOf(T)
{
static if (is(T : void)) alias BuiltinTypeOf = void;
else static if (is(BooleanTypeOf!T X)) alias BuiltinTypeOf = X;
else static if (is(IntegralTypeOf!T X)) alias BuiltinTypeOf = X;
else static if (is(FloatingPointTypeOf!T X))alias BuiltinTypeOf = X;
else static if (is(T : const(ireal))) alias BuiltinTypeOf = ireal; //TODO
else static if (is(T : const(creal))) alias BuiltinTypeOf = creal; //TODO
else static if (is(CharTypeOf!T X)) alias BuiltinTypeOf = X;
else static if (is(ArrayTypeOf!T X)) alias BuiltinTypeOf = X;
else static if (is(AssocArrayTypeOf!T X)) alias BuiltinTypeOf = X;
else static assert(0);
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// isSomething
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
/**
* Detect whether $(D T) is a built-in boolean type.
*/
enum bool isBoolean(T) = is(BooleanTypeOf!T) && !isAggregateType!T;
unittest
{
static assert( isBoolean!bool);
enum EB : bool { a = true }
static assert( isBoolean!EB);
static assert(!isBoolean!(SubTypeOf!bool));
}
/**
* Detect whether $(D T) is a built-in integral type. Types $(D bool),
* $(D char), $(D wchar), and $(D dchar) are not considered integral.
*/
enum bool isIntegral(T) = is(IntegralTypeOf!T) && !isAggregateType!T;
unittest
{
foreach (T; IntegralTypeList)
{
foreach (Q; TypeQualifierList)
{
static assert( isIntegral!(Q!T));
static assert(!isIntegral!(SubTypeOf!(Q!T)));
}
}
static assert(!isIntegral!float);
enum EU : uint { a = 0, b = 1, c = 2 } // base type is unsigned
enum EI : int { a = -1, b = 0, c = 1 } // base type is signed (bug 7909)
static assert(isIntegral!EU && isUnsigned!EU && !isSigned!EU);
static assert(isIntegral!EI && !isUnsigned!EI && isSigned!EI);
}
/**
* Detect whether $(D T) is a built-in floating point type.
*/
enum bool isFloatingPoint(T) = is(FloatingPointTypeOf!T) && !isAggregateType!T;
unittest
{
enum EF : real { a = 1.414, b = 1.732, c = 2.236 }
foreach (T; TypeTuple!(FloatingPointTypeList, EF))
{
foreach (Q; TypeQualifierList)
{
static assert( isFloatingPoint!(Q!T));
static assert(!isFloatingPoint!(SubTypeOf!(Q!T)));
}
}
foreach (T; IntegralTypeList)
{
foreach (Q; TypeQualifierList)
{
static assert(!isFloatingPoint!(Q!T));
}
}
}
/**
Detect whether $(D T) is a built-in numeric type (integral or floating
point).
*/
enum bool isNumeric(T) = is(NumericTypeOf!T) && !isAggregateType!T;
unittest
{
foreach (T; TypeTuple!(NumericTypeList))
{
foreach (Q; TypeQualifierList)
{
static assert( isNumeric!(Q!T));
static assert(!isNumeric!(SubTypeOf!(Q!T)));
}
}
}
/**
Detect whether $(D T) is a scalar type (a built-in numeric, character or boolean type).
*/
enum bool isScalarType(T) = isNumeric!T || isSomeChar!T || isBoolean!T;
unittest
{
static assert(!isScalarType!void);
static assert( isScalarType!(immutable(int)));
static assert( isScalarType!(shared(float)));
static assert( isScalarType!(shared(const bool)));
static assert( isScalarType!(const(dchar)));
}
/**
Detect whether $(D T) is a basic type (scalar type or void).
*/
enum bool isBasicType(T) = isScalarType!T || is(T == void);
unittest
{
static assert(isBasicType!void);
static assert(isBasicType!(immutable(int)));
static assert(isBasicType!(shared(float)));
static assert(isBasicType!(shared(const bool)));
static assert(isBasicType!(const(dchar)));
}
/**
Detect whether $(D T) is a built-in unsigned numeric type.
*/
enum bool isUnsigned(T) = is(UnsignedTypeOf!T) && !isAggregateType!T;
unittest
{
foreach (T; TypeTuple!(UnsignedIntTypeList))
{
foreach (Q; TypeQualifierList)
{
static assert( isUnsigned!(Q!T));
static assert(!isUnsigned!(SubTypeOf!(Q!T)));
}
}
}
/**
Detect whether $(D T) is a built-in signed numeric type.
*/
enum bool isSigned(T) = is(SignedTypeOf!T) && !isAggregateType!T;
unittest
{
foreach (T; TypeTuple!(SignedIntTypeList))
{
foreach (Q; TypeQualifierList)
{
static assert( isSigned!(Q!T));
static assert(!isSigned!(SubTypeOf!(Q!T)));
}
}
}
/**
Detect whether $(D T) is one of the built-in character types.
*/
enum bool isSomeChar(T) = is(CharTypeOf!T) && !isAggregateType!T;
unittest
{
enum EC : char { a = 'x', b = 'y' }
foreach (T; TypeTuple!(CharTypeList, EC))
{
foreach (Q; TypeQualifierList)
{
static assert( isSomeChar!( Q!T ));
static assert(!isSomeChar!( SubTypeOf!(Q!T) ));
}
}
static assert(!isSomeChar!int);
static assert(!isSomeChar!byte);
static assert(!isSomeChar!string);
static assert(!isSomeChar!wstring);
static assert(!isSomeChar!dstring);
static assert(!isSomeChar!(char[4]));
}
/**
Detect whether $(D T) is one of the built-in string types.
The built-in string types are $(D Char[]), where $(D Char) is any of $(D char),
$(D wchar) or $(D dchar), with or without qualifiers.
Static arrays of characters (like $(D char[80]) are not considered
built-in string types.
*/
enum bool isSomeString(T) = is(StringTypeOf!T) && !isAggregateType!T && !isStaticArray!T;
unittest
{
foreach (T; TypeTuple!(char[], dchar[], string, wstring, dstring))
{
static assert( isSomeString!( T ));
static assert(!isSomeString!(SubTypeOf!(T)));
}
static assert(!isSomeString!int);
static assert(!isSomeString!(int[]));
static assert(!isSomeString!(byte[]));
static assert(!isSomeString!(typeof(null)));
static assert(!isSomeString!(char[4]));
enum ES : string { a = "aaa", b = "bbb" }
static assert( isSomeString!ES);
}
enum bool isNarrowString(T) = (is(T : const char[]) || is(T : const wchar[])) && !isAggregateType!T && !isStaticArray!T;
unittest
{
foreach (T; TypeTuple!(char[], string, wstring))
{
foreach (Q; TypeTuple!(MutableOf, ConstOf, ImmutableOf)/*TypeQualifierList*/)
{
static assert( isNarrowString!( Q!T ));
static assert(!isNarrowString!( SubTypeOf!(Q!T) ));
}
}
foreach (T; TypeTuple!(int, int[], byte[], dchar[], dstring, char[4]))
{
foreach (Q; TypeQualifierList)
{
static assert(!isNarrowString!( Q!T ));
static assert(!isNarrowString!( SubTypeOf!(Q!T) ));
}
}
}
/**
* Detect whether type $(D T) is a static array.
*/
enum bool isStaticArray(T) = is(StaticArrayTypeOf!T) && !isAggregateType!T;
unittest
{
foreach (T; TypeTuple!(int[51], int[][2],
char[][int][11], immutable char[13u],
const(real)[1], const(real)[1][1], void[0]))
{
foreach (Q; TypeQualifierList)
{
static assert( isStaticArray!( Q!T ));
static assert(!isStaticArray!( SubTypeOf!(Q!T) ));
}
}
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!(int[int]));
static assert(!isStaticArray!int);
//enum ESA : int[1] { a = [1], b = [2] }
//static assert( isStaticArray!ESA);
}
/**
* Detect whether type $(D T) is a dynamic array.
*/
enum bool isDynamicArray(T) = is(DynamicArrayTypeOf!T) && !isAggregateType!T;
unittest
{
foreach (T; TypeTuple!(int[], char[], string, long[3][], double[string][]))
{
foreach (Q; TypeQualifierList)
{
static assert( isDynamicArray!( Q!T ));
static assert(!isDynamicArray!( SubTypeOf!(Q!T) ));
}
}
static assert(!isDynamicArray!(int[5]));
static assert(!isDynamicArray!(typeof(null)));
//enum EDA : int[] { a = [1], b = [2] }
//static assert( isDynamicArray!EDA);
}
/**
* Detect whether type $(D T) is an array (static or dynamic; for associative
* arrays see $(LREF isAssociativeArray)).
*/
enum bool isArray(T) = isStaticArray!T || isDynamicArray!T;
unittest
{
foreach (T; TypeTuple!(int[], int[5], void[]))
{
foreach (Q; TypeQualifierList)
{
static assert( isArray!(Q!T));
static assert(!isArray!(SubTypeOf!(Q!T)));
}
}
static assert(!isArray!uint);
static assert(!isArray!(uint[uint]));
static assert(!isArray!(typeof(null)));
}
/**
* Detect whether $(D T) is an associative array type
*/
enum bool isAssociativeArray(T) = is(AssocArrayTypeOf!T) && !isAggregateType!T;
unittest
{
struct Foo
{
@property uint[] keys() { return null; }
@property uint[] values() { return null; }
}
foreach (T; TypeTuple!(int[int], int[string], immutable(char[5])[int]))
{
foreach (Q; TypeQualifierList)
{
static assert( isAssociativeArray!(Q!T));
static assert(!isAssociativeArray!(SubTypeOf!(Q!T)));
}
}
static assert(!isAssociativeArray!Foo);
static assert(!isAssociativeArray!int);
static assert(!isAssociativeArray!(int[]));
static assert(!isAssociativeArray!(typeof(null)));
//enum EAA : int[int] { a = [1:1], b = [2:2] }
//static assert( isAssociativeArray!EAA);
}
/**
* Detect whether type $(D T) is a builtin type.
*/
enum bool isBuiltinType(T) = is(BuiltinTypeOf!T) && !isAggregateType!T;
/**
* Detect whether type $(D T) is a SIMD vector type.
*/
enum bool isSIMDVector(T) = is(T : __vector(V[N]), V, size_t N);
unittest
{
alias __vector(float[4]) SimdVec;
static assert(isSIMDVector!(__vector(float[4])));
static assert(isSIMDVector!SimdVec);
static assert(!isSIMDVector!uint);
static assert(!isSIMDVector!(float[4]));
}
/**
* Detect whether type $(D T) is a pointer.
*/
enum bool isPointer(T) = is(T == U*, U) && !isAggregateType!T;
unittest
{
foreach (T; TypeTuple!(int*, void*, char[]*))
{
foreach (Q; TypeQualifierList)
{
static assert( isPointer!(Q!T));
static assert(!isPointer!(SubTypeOf!(Q!T)));
}
}
static assert(!isPointer!uint);
static assert(!isPointer!(uint[uint]));
static assert(!isPointer!(char[]));
static assert(!isPointer!(typeof(null)));
}
/**
Returns the target type of a pointer.
*/
alias PointerTarget(T : T*) = T;
/// $(RED Scheduled for deprecation. Please use $(LREF PointerTarget) instead.)
alias pointerTarget = PointerTarget;
unittest
{
static assert( is(PointerTarget!(int*) == int));
static assert( is(PointerTarget!(long*) == long));
static assert(!is(PointerTarget!int));
}
/**
* Detect whether type $(D T) is an aggregate type.
*/
enum bool isAggregateType(T) = is(T == struct) || is(T == union) ||
is(T == class) || is(T == interface);
/**
* 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.
*/
enum bool isIterable(T) = is(typeof({ foreach(elem; T.init) {} }));
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!OpApply);
static assert( isIterable!(uint[string]));
static assert( isIterable!Range);
static assert(!isIterable!uint);
}
/**
* Returns true if T is not const or immutable. Note that isMutable is true for
* string, or immutable(char)[], because the 'head' is mutable.
*/
enum bool isMutable(T) = !is(T == const) && !is(T == immutable) && !is(T == inout);
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!(inout int));
static assert(!isMutable!(shared(const int)));
static assert(!isMutable!(shared(inout int)));
static assert(!isMutable!(immutable string));
}
/**
* Returns true if T is an instance of the template S.
*/
enum bool isInstanceOf(alias S, T) = is(T == S!Args, Args...);
unittest
{
static struct Foo(T...) { }
static struct Bar(T...) { }
static struct Doo(T) { }
static struct ABC(int x) { }
static assert(isInstanceOf!(Foo, Foo!int));
static assert(!isInstanceOf!(Foo, Bar!int));
static assert(!isInstanceOf!(Foo, int));
static assert(isInstanceOf!(Doo, Doo!int));
static assert(isInstanceOf!(ABC, ABC!1));
static assert(!__traits(compiles, isInstanceOf!(Foo, Foo)));
}
/**
* Check whether the tuple T is an expression tuple.
* An expression tuple only contains expressions. See also $(LREF isTypeTuple).
*/
template isExpressionTuple(T ...)
{
static if (T.length >= 2)
enum bool isExpressionTuple =
isExpressionTuple!(T[0 .. $/2]) &&
isExpressionTuple!(T[$/2 .. $]);
else static if (T.length == 1)
enum bool isExpressionTuple =
!is(T[0]) && __traits(compiles, { auto ex = T[0]; });
else
enum bool isExpressionTuple = true; // default
}
///
unittest
{
static assert(isExpressionTuple!(1, 2.0, "a"));
static assert(!isExpressionTuple!(int, double, string));
static assert(!isExpressionTuple!(int, 2.0, "a"));
}
unittest
{
void foo();
static int bar() { return 42; }
enum aa = [ 1: -1 ];
alias myint = int;
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);
}
/**
* Check whether the tuple $(D T) is a type tuple.
* A type tuple only contains types. See also $(LREF isExpressionTuple).
*/
template isTypeTuple(T...)
{
static if (T.length >= 2)
enum bool isTypeTuple = isTypeTuple!(T[0 .. $/2]) && isTypeTuple!(T[$/2 .. $]);
else static if (T.length == 1)
enum bool isTypeTuple = is(T[0]);
else
enum bool isTypeTuple = true; // default
}
///
unittest
{
static assert(isTypeTuple!(int, float, string));
static assert(!isTypeTuple!(1, 2.0, "a"));
static assert(!isTypeTuple!(1, double, string));
}
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 symbol or type $(D T) is a delegate.
*/
template isDelegate(T...)
if (T.length == 1)
{
static if (is(typeof(& T[0]) U : U*) && is(typeof(& T[0]) U == delegate))
{
// T is a (nested) function symbol.
enum bool isDelegate = 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.
enum bool isDelegate = is(W == delegate);
}
else
enum bool isDelegate = false;
}
unittest
{
static void sfunc() { }
int x;
void func() { x++; }
int delegate() dg;
assert(isDelegate!dg);
assert(isDelegate!(int delegate()));
assert(isDelegate!(typeof(&func)));
int function() fp;
assert(!isDelegate!fp);
assert(!isDelegate!(int function()));
assert(!isDelegate!(typeof(&sfunc)));
}
/**
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 a) { return a; }));
static assert(!isSomeFunction!int);
static assert(!isSomeFunction!val);
static assert(!isSomeFunction!isSomeFunction);
}
/**
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!((int a) { return a; }));
static assert(!isCallable!I);
}
/**
* Detect whether $(D T) is a an abstract function.
*/
template isAbstractFunction(T...)
if (T.length == 1)
{
enum bool isAbstractFunction = __traits(isAbstractFunction, T[0]);
}
unittest
{
struct S { void foo() { } }
class C { void foo() { } }
class AC { abstract void foo(); }
static assert(!isAbstractFunction!(S.foo));
static assert(!isAbstractFunction!(C.foo));
static assert(isAbstractFunction!(AC.foo));
}
/**
* Detect whether $(D T) is a a final function.
*/
template isFinalFunction(T...)
if (T.length == 1)
{
enum bool isFinalFunction = __traits(isFinalFunction, T[0]);
}
unittest
{
struct S { void bar() { } }
final class FC { void foo(); }
class C
{
void bar() { }
final void foo();
}
static assert(!isFinalFunction!(S.bar));
static assert(isFinalFunction!(FC.foo));
static assert(!isFinalFunction!(C.bar));
static assert(isFinalFunction!(C.foo));
}
/**
Determines whether function $(D f) requires a context pointer.
*/
template isNestedFunction(alias f)
{
enum isNestedFunction = __traits(isNested, f);
}
unittest
{
static void f() { }
void g() { }
static assert(!isNestedFunction!f);
static assert( isNestedFunction!g);
}
/**
* Detect whether $(D T) is a an abstract class.
*/
template isAbstractClass(T...)
if (T.length == 1)
{
enum bool isAbstractClass = __traits(isAbstractClass, T[0]);
}
unittest
{
struct S { }
class C { }
abstract class AC { }
static assert(!isAbstractClass!S);
static assert(!isAbstractClass!C);
static assert(isAbstractClass!AC);
}
/**
* Detect whether $(D T) is a a final class.
*/
template isFinalClass(T...)
if (T.length == 1)
{
enum bool isFinalClass = __traits(isFinalClass, T[0]);
}
unittest
{
class C { }
abstract class AC { }
final class FC1 : C { }
final class FC2 { }
static assert(!isFinalClass!C);
static assert(!isFinalClass!AC);
static assert(isFinalClass!FC1);
static assert(isFinalClass!FC2);
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// 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 = Unqual!U;
else static if (is(T U == immutable U)) alias Unqual = Unqual!U;
else static if (is(T U == inout U)) alias Unqual = Unqual!U;
else static if (is(T U == shared U)) alias Unqual = Unqual!U;
else alias Unqual = T;
}
else // workaround
{
static if (is(T U == immutable U)) alias Unqual = U;
else static if (is(T U == shared inout const U)) alias Unqual = U;
else static if (is(T U == shared inout U)) alias Unqual = U;
else static if (is(T U == shared const U)) alias Unqual = U;
else static if (is(T U == shared U)) alias Unqual = U;
else static if (is(T U == inout const U)) alias Unqual = U;
else static if (is(T U == inout U)) alias Unqual = U;
else static if (is(T U == const U)) alias Unqual = U;
else alias Unqual = T;
}
}
unittest
{
static assert(is(Unqual!( int) == int));
static assert(is(Unqual!( const int) == int));
static assert(is(Unqual!( inout int) == int));
static assert(is(Unqual!( inout const int) == int));
static assert(is(Unqual!(shared int) == int));
static assert(is(Unqual!(shared const int) == int));
static assert(is(Unqual!(shared inout int) == int));
static assert(is(Unqual!(shared inout const int) == int));
static assert(is(Unqual!( immutable int) == int));
alias ImmIntArr = immutable(int[]);
static assert(is(Unqual!ImmIntArr == immutable(int)[]));
}
// [For internal use]
private template ModifyTypePreservingSTC(alias Modifier, T)
{
static if (is(T U == immutable U)) alias ModifyTypePreservingSTC = immutable Modifier!U;
else static if (is(T U == shared inout const U)) alias ModifyTypePreservingSTC = shared inout const Modifier!U;
else static if (is(T U == shared inout U)) alias ModifyTypePreservingSTC = shared inout Modifier!U;
else static if (is(T U == shared const U)) alias ModifyTypePreservingSTC = shared const Modifier!U;
else static if (is(T U == shared U)) alias ModifyTypePreservingSTC = shared Modifier!U;
else static if (is(T U == inout const U)) alias ModifyTypePreservingSTC = inout const Modifier!U;
else static if (is(T U == inout U)) alias ModifyTypePreservingSTC = inout Modifier!U;
else static if (is(T U == const U)) alias ModifyTypePreservingSTC = const Modifier!U;
else alias ModifyTypePreservingSTC = Modifier!T;
}
unittest
{
alias Intify(T) = int;
static assert(is(ModifyTypePreservingSTC!(Intify, real) == int));
static assert(is(ModifyTypePreservingSTC!(Intify, const real) == const int));
static assert(is(ModifyTypePreservingSTC!(Intify, inout real) == inout int));
static assert(is(ModifyTypePreservingSTC!(Intify, inout const real) == inout const int));
static assert(is(ModifyTypePreservingSTC!(Intify, shared real) == shared int));
static assert(is(ModifyTypePreservingSTC!(Intify, shared const real) == shared const int));
static assert(is(ModifyTypePreservingSTC!(Intify, shared inout real) == shared inout int));
static assert(is(ModifyTypePreservingSTC!(Intify, shared inout const real) == shared inout const int));
static assert(is(ModifyTypePreservingSTC!(Intify, immutable real) == immutable int));
}
/**
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 ForeachType = ReturnType!(typeof(
(inout int x = 0)
{
foreach(elem; T.init)
{
return elem;
}
assert(0);
}));
}
unittest
{
static assert(is(ForeachType!(uint[]) == uint));
static assert(is(ForeachType!string == immutable(char)));
static assert(is(ForeachType!(string[string]) == string));
static assert(is(ForeachType!(inout(int)[]) == inout(int)));
}
/**
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)
{
template Impl(T)
{
static if (is(T U == typedef)) alias Impl = OriginalType!U;
else static if (is(T U == enum)) alias Impl = OriginalType!U;
else alias Impl = T;
}
alias OriginalType = ModifyTypePreservingSTC!(Impl, T);
}
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));
}
/**
* Get the Key type of an Associative Array.
*/
alias KeyType(V : V[K], K) = K;
///
unittest
{
import std.traits;
alias Hash = int[string];
static assert(is(KeyType!Hash == string));
static assert(is(ValueType!Hash == int));
KeyType!Hash str = "a"; // str is declared as string
ValueType!Hash num = 1; // num is declared as int
}
/**
* Get the Value type of an Associative Array.
*/
alias ValueType(V : V[K], K) = V;
///
unittest
{
import std.traits;
alias Hash = int[string];
static assert(is(KeyType!Hash == string));
static assert(is(ValueType!Hash == int));
KeyType!Hash str = "a"; // str is declared as string
ValueType!Hash num = 1; // num is declared as int
}
/**
* Returns the corresponding unsigned type for T. T must be a numeric
* integral type, otherwise a compile-time error occurs.
*/
template Unsigned(T)
{
template Impl(T)
{
static if (is(T : __vector(V[N]), V, size_t N))
alias Impl = __vector(Impl!V[N]);
else static if (isUnsigned!T)
alias Impl = T;
else static if (isSigned!T && !isFloatingPoint!T)
{
static if (is(T == byte )) alias Impl = ubyte;
static if (is(T == short)) alias Impl = ushort;
static if (is(T == int )) alias Impl = uint;
static if (is(T == long )) alias Impl = ulong;
}
else
static assert(false, "Type " ~ T.stringof ~
" does not have an Unsigned counterpart");
}
alias Unsigned = ModifyTypePreservingSTC!(Impl, OriginalType!T);
}
unittest
{
alias U1 = Unsigned!int;
alias U2 = Unsigned!(const(int));
alias U3 = Unsigned!(immutable(int));
static assert(is(U1 == uint));
static assert(is(U2 == const(uint)));
static assert(is(U3 == immutable(uint)));
static if (is(__vector(int[4])) && is(__vector(uint[4])))
{
alias Unsigned!(__vector(int[4])) UV1;
alias Unsigned!(const(__vector(int[4]))) UV2;
static assert(is(UV1 == __vector(uint[4])));
static assert(is(UV2 == const(__vector(uint[4]))));
}
//struct S {}
//alias U2 = Unsigned!S;
//alias U3 = Unsigned!double;
}
/**
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 Largest = T[0];
}
else static if (T.length == 2)
{
static if(T[0].sizeof >= T[1].sizeof)
{
alias Largest = T[0];
}
else
{
alias Largest = T[1];
}
}
else
{
alias Largest = Largest!(Largest!(T[0 .. $/2]), Largest!(T[$/2 .. $]));
}
}
unittest
{
static assert(is(Largest!(uint, ubyte, ushort, 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)
{
template Impl(T)
{
static if (is(T : __vector(V[N]), V, size_t N))
alias Impl = __vector(Impl!V[N]);
else static if (isSigned!T)
alias Impl = T;
else static if (isUnsigned!T)
{
static if (is(T == ubyte )) alias Impl = byte;
static if (is(T == ushort)) alias Impl = short;
static if (is(T == uint )) alias Impl = int;
static if (is(T == ulong )) alias Impl = long;
}
else
static assert(false, "Type " ~ T.stringof ~
" does not have an Signed counterpart");
}
alias Signed = ModifyTypePreservingSTC!(Impl, OriginalType!T);
}
unittest
{
alias S1 = Signed!uint;
alias S2 = Signed!(const(uint));
alias S3 = Signed!(immutable(uint));
static assert(is(S1 == int));
static assert(is(S2 == const(int)));
static assert(is(S3 == immutable(int)));
static assert(is(Signed!float == float));
static if (is(__vector(int[4])) && is(__vector(uint[4])))
{
alias Signed!(__vector(uint[4])) SV1;
alias Signed!(const(__vector(uint[4]))) SV2;
static assert(is(SV1 == __vector(int[4])));
static assert(is(SV2 == const(__vector(int[4]))));
}
}
// Remove import when unsigned is removed.
import std.conv;
// Purposefully undocumented. Will be removed in June 2014.
deprecated("unsigned has been moved to std.conv. Please adjust your imports accordingly.")
alias unsigned = std.conv.unsigned;
/**
Returns the most negative value of the numeric type T.
*/
template mostNegative(T)
if(isNumeric!T || isSomeChar!T || isBoolean!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!double == -double.max);
static assert(mostNegative!real == -real.max);
static assert(mostNegative!bool == false);
foreach(T; TypeTuple!(bool, byte, short, int, long))
static assert(mostNegative!T == T.min);
foreach(T; TypeTuple!(ubyte, ushort, uint, ulong, char, wchar, dchar))
static assert(mostNegative!T == 0);
}
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
// 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)
{
static if (is(typeof(sth[0]) X) && is(X == void))
{
// sth[0] is a template symbol
enum string mangledName = removeDummyEnvelope(Dummy!sth.Hook.mangleof);
}
else
{
enum string mangledName = sth[0].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; }
//static assert(mangledName!MyInt[$ - 7 .. $] == "T5MyInt"); // XXX depends on bug 4237
//static assert(mangledName!test[$ - 7 .. $] == "T5MyInt");
class C { int value() @property { return 0; } }
static assert(mangledName!int == int.mangleof);
static assert(mangledName!C == C.mangleof);
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; }) == "DFNbNiNfiZi"); // nothrow @safe @nnogc
}
unittest
{
// Test for bug 5718
import std.demangle;
int foo;
auto foo_demangled = demangle(mangledName!foo);
assert(foo_demangled[0 .. 4] == "int " && foo_demangled[$-3 .. $] == "foo");
void bar(){}
auto bar_demangled = demangle(mangledName!bar);
assert(bar_demangled[0 .. 5] == "void " && bar_demangled[$-5 .. $] == "bar()");
}
// XXX Select & select should go to another module. (functional or algorithm?)
/**
Aliases itself to $(D T[0]) if the boolean $(D condition) is $(D true)
and to $(D T[1]) otherwise.
*/
template Select(bool condition, T...) if (T.length == 2)
{
alias Select = T[!condition];
}
///
unittest
{
// can select types
static assert(is(Select!(true, int, long) == int));
static assert(is(Select!(false, int, long) == long));
// can select symbols
int a = 1;
int b = 2;
alias selA = Select!(true, a, b);
alias selB = Select!(false, a, b);
assert(selA == 1);
assert(selB == 2);
}
/**
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
|
/Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.build/Objects-normal/x86_64/ShareReplayScope.o : /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Amb.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Deferred.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Deprecated.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Enumerated.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/Maybe.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Sequence.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Debounce.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Reduce.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Range.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Merge.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Take.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Cancelable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/Completable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/GroupedObservable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/Single.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/AsSingle.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Sample.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Throttle.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ObservableType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ConnectableObservableType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/SchedulerType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ObserverType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Create.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Generate.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DataStructures/Queue.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Reactive.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Materialize.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/AddRef.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DataStructures/Bag.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Using.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Debug.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Catch.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Switch.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/StartWith.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/Lock.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/RecursiveLock.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Sink.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Optional.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Scan.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/Platform.Darwin.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Do.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Map.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Zip.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Skip.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Producer.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Buffer.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Timer.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DeprecationWarner.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Filter.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Never.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/AnyObserver.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Error.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/Disposables.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Errors.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/ElementAt.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Concat.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Repeat.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Event.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/TakeLast.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Multicast.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/First.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Just.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Timeout.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Window.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Rx.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/RxMutableBox.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/Platform.Linux.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/GroupBy.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Delay.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/ToArray.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Empty.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.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/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/Target\ Support\ Files/RxSwift/RxSwift-umbrella.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.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/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.build/Objects-normal/x86_64/ShareReplayScope~partial.swiftmodule : /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Amb.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Deferred.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Deprecated.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Enumerated.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/Maybe.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Sequence.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Debounce.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Reduce.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Range.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Merge.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Take.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Cancelable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/Completable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/GroupedObservable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/Single.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/AsSingle.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Sample.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Throttle.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ObservableType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ConnectableObservableType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/SchedulerType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ObserverType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Create.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Generate.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DataStructures/Queue.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Reactive.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Materialize.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/AddRef.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DataStructures/Bag.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Using.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Debug.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Catch.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Switch.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/StartWith.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/Lock.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/RecursiveLock.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Sink.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Optional.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Scan.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/Platform.Darwin.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Do.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Map.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Zip.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Skip.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Producer.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Buffer.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Timer.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DeprecationWarner.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Filter.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Never.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/AnyObserver.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Error.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/Disposables.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Errors.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/ElementAt.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Concat.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Repeat.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Event.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/TakeLast.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Multicast.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/First.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Just.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Timeout.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Window.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Rx.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/RxMutableBox.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/Platform.Linux.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/GroupBy.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Delay.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/ToArray.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Empty.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.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/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/Target\ Support\ Files/RxSwift/RxSwift-umbrella.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.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/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.build/Objects-normal/x86_64/ShareReplayScope~partial.swiftdoc : /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Amb.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Deferred.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Deprecated.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Enumerated.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/Maybe.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Sequence.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Debounce.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Reduce.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Range.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Merge.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Take.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Cancelable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/Completable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/GroupedObservable.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/Single.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/AsSingle.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Sample.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Throttle.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ObservableType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ConnectableObservableType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/SchedulerType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ObserverType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Create.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Generate.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DataStructures/Queue.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Reactive.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Materialize.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/AddRef.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DataStructures/Bag.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Using.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Debug.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Catch.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Switch.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/StartWith.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/Lock.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/RecursiveLock.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Sink.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Optional.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Scan.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/Platform.Darwin.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Do.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Map.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Zip.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Skip.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Producer.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Buffer.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Timer.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DeprecationWarner.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Filter.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Never.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/AnyObserver.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Error.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Disposables/Disposables.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Errors.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/ElementAt.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Concat.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Repeat.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Event.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/TakeLast.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Multicast.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/First.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Just.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Timeout.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Window.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Rx.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/RxMutableBox.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/Platform/Platform.Linux.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/GroupBy.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Delay.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/ToArray.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/Empty.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.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/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Pods/Target\ Support\ Files/RxSwift/RxSwift-umbrella.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.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
|
module test.http.router;
import hunt.http.server.router.Matcher;
import hunt.http.server.router.Router;
import hunt.http.server.router.RouterManager;
import hunt.http.server.router.impl.RouterManagerImpl;
import hunt.Assert;
import hunt.util.Test;
import java.util.NavigableSet;
/**
*
*/
public class TestMatcher {
public void testFindRouter() {
RouterManager routerManager = new RouterManagerImpl();
Router router0 = routerManager.register().get("/hello/get").produces("application/json");
Router router1 = routerManager.register().get("/hello/:testParam0").produces("application/json");
Router router2 = routerManager.register().get("/hello/:testParam1").produces("application/json");
Router router3 = routerManager.register().post("/book/update/:id").consumes("*/json");
Router router4 = routerManager.register().post("/book/update/:id").consumes("application/json");
NavigableSet<RouterManager.RouterMatchResult> result = routerManager.findRouter("GET", "/hello/get", null,
"application/json,text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.size(), is(3));
Assert.assertThat(result.first().getRouter(), is(router0));
Assert.assertThat(result.lower(result.last()).getRouter(), is(router1));
Assert.assertThat(result.last().getRouter(), is(router2));
Assert.assertThat(result.last().getParameters().get("testParam1"), is("get"));
result = routerManager.findRouter("GET", "/hello/get", null, "application/*,*/*;q=0.8");
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.size(), is(3));
Assert.assertThat(result.first().getRouter(), is(router0));
Assert.assertThat(result.lower(result.last()).getRouter(), is(router1));
Assert.assertThat(result.last().getRouter(), is(router2));
Assert.assertThat(result.last().getParameters().get("testParam1"), is("get"));
result = routerManager.findRouter("GET", "/hello/get", null, "*/json,*/*;q=0.8");
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.size(), is(3));
Assert.assertThat(result.first().getRouter(), is(router0));
Assert.assertThat(result.lower(result.last()).getRouter(), is(router1));
Assert.assertThat(result.last().getRouter(), is(router2));
Assert.assertThat(result.last().getParameters().get("testParam1"), is("get"));
result = routerManager.findRouter("GET", "/hello/get", null, "*/*");
Assert.assertThat(result.size(), is(3));
result = routerManager.findRouter("GET", "/hello/get", null, null);
Assert.assertThat(result, empty());
result = routerManager.findRouter("POST", "/book/update/3", null, null);
Assert.assertThat(result, empty());
result = routerManager.findRouter("POST", "/book/update/3", "application/json;charset=UTF-8", null);
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.size(), is(2));
Assert.assertThat(result.first().getRouter(), is(router3));
Assert.assertThat(result.last().getRouter(), is(router4));
Assert.assertThat(result.last().getParameters().get("id"), is("3"));
Assert.assertThat(result.first().getParameters().get("param0"), is("application"));
}
public void testProduces() {
RouterManager routerManager = new RouterManagerImpl();
Router router0 = routerManager.register().get("/hello/get").produces("application/json");
Router router1 = routerManager.register().get("/hello/:testParam0").produces("text/html");
NavigableSet<RouterManager.RouterMatchResult> result = routerManager.findRouter("GET", "/hello/get", null,
"text/html,application/xml;q=0.9,application/json;q=0.8");
Assert.assertThat(result.size(), is(1));
Assert.assertThat(result.first().getRouter(), is(router1));
result = routerManager.findRouter("GET", "/hello/get", null,
"text/html;q=0.6,application/xml;q=0.7,application/json;q=0.8");
Assert.assertThat(result.size(), is(1));
Assert.assertThat(result.first().getRouter(), is(router0));
result = routerManager.findRouter("GET", "/hello/get", null,
"text/html,application/xml,application/json");
Assert.assertThat(result.size(), is(1));
Assert.assertThat(result.first().getRouter(), is(router1));
}
public void testMIMETypeMatcher() {
RouterManagerImpl routerManager = new RouterManagerImpl();
Router router0 = routerManager.register().consumes("text/html");
Router router1 = routerManager.register().consumes("*/json");
Matcher.MatchResult result = routerManager.getContentTypePreciseMatcher().match("text/html");
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.getRouters().size(), is(1));
Assert.assertThat(result.getRouters().contains(router0), is(true));
result = routerManager.getContentTypePatternMatcher().match("application/json");
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.getRouters().size(), is(1));
Assert.assertThat(result.getRouters().contains(router1), is(true));
Assert.assertThat(result.getParameters().get(router1).get("param0"), is("application"));
}
public void testMethodMatcher() {
RouterManagerImpl routerManager = new RouterManagerImpl();
Router router0 = routerManager.register().post("/food/update");
Matcher.MatchResult result = routerManager.getHttpMethodMatcher().match("POST");
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.getRouters().size(), is(1));
Assert.assertThat(result.getRouters().contains(router0), is(true));
result = routerManager.getPrecisePathMather().match("/food/update");
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.getRouters().size(), is(1));
Assert.assertThat(result.getRouters().contains(router0), is(true));
result = routerManager.getHttpMethodMatcher().match("GET");
Assert.assertThat(result, nullValue());
}
public void testPathMatcher() {
RouterManagerImpl routerManager = new RouterManagerImpl();
Router router0 = routerManager.register().path("/hello/foo");
Router router1 = routerManager.register().path("/");
Router router2 = routerManager.register().path("/hello*");
Router router3 = routerManager.register().path("*");
Router router4 = routerManager.register().path("/*");
Router router5 = routerManager.register().path("/he*/*");
Router router6 = routerManager.register().path("/hello/:foo");
Router router7 = routerManager.register().path("/:hello/:foo/");
Router router8 = routerManager.register().path("/hello/:foo/:bar");
Router router9 = routerManager.register().pathRegex("/hello(\\d*)");
Matcher.MatchResult result = routerManager.getPrecisePathMather().match("/hello/foo");
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.getRouters().size(), is(1));
Assert.assertThat(result.getRouters().contains(router0), is(true));
result = routerManager.getPrecisePathMather().match("/");
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.getRouters().size(), is(1));
Assert.assertThat(result.getRouters().contains(router1), is(true));
result = routerManager.getPatternPathMatcher().match("/hello/foo");
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.getRouters().size(), is(4));
Assert.assertThat(result.getRouters().contains(router2), is(true));
Assert.assertThat(result.getParameters().get(router2).get("param0"), is("/foo"));
Assert.assertThat(result.getRouters().contains(router3), is(true));
Assert.assertThat(result.getParameters().get(router3).get("param0"), is("/hello/foo"));
Assert.assertThat(result.getRouters().contains(router4), is(true));
Assert.assertThat(result.getParameters().get(router4).get("param0"), is("hello/foo"));
Assert.assertThat(result.getRouters().contains(router5), is(true));
Assert.assertThat(result.getParameters().get(router5).get("param0"), is("llo"));
Assert.assertThat(result.getParameters().get(router5).get("param1"), is("foo"));
result = routerManager.getParameterPathMatcher().match("/hello/foooo");
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.getRouters().size(), is(2));
Assert.assertThat(result.getRouters().contains(router6), is(true));
Assert.assertThat(result.getRouters().contains(router7), is(true));
Assert.assertThat(result.getParameters().get(router6).get("foo"), is("foooo"));
Assert.assertThat(result.getParameters().get(router7).get("foo"), is("foooo"));
Assert.assertThat(result.getParameters().get(router7).get("hello"), is("hello"));
result = routerManager.getParameterPathMatcher().match("/");
Assert.assertThat(result, nullValue());
result = routerManager.getParameterPathMatcher().match("/hello/11/2333");
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.getRouters().size(), is(1));
Assert.assertThat(result.getRouters().contains(router8), is(true));
result = routerManager.getRegexPathMatcher().match("/hello113");
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.getRouters().size(), is(1));
Assert.assertThat(result.getRouters().contains(router9), is(true));
Assert.assertThat(result.getParameters().get(router9).get("group1"), is("113"));
}
public void testPathMatcher2() {
RouterManagerImpl routerManager = new RouterManagerImpl();
Router router0 = routerManager.register().path("/test/*");
Matcher.MatchResult result = routerManager.getPatternPathMatcher().match("/test/x");
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.getRouters().size(), is(1));
Assert.assertThat(result.getRouters().contains(router0), is(true));
Router router1 = routerManager.register().path("/*create*");
result = routerManager.getPatternPathMatcher().match("/fruit/apple/create");
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.getRouters().size(), is(1));
Assert.assertThat(result.getRouters().contains(router1), is(true));
Assert.assertThat(result.getParameters().get(router1).get("param0"), is("fruit/apple/"));
Assert.assertThat(result.getParameters().get(router1).get("param1"), is(""));
}
}
|
D
|
/**
Copyright: Copyright (c) 2017-2018 Andrey Penechko.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: Andrey Penechko.
*/
module voxelman.container.hash.set;
import std.experimental.allocator.gc_allocator;
import voxelman.container.hash.hashtableparts;
import voxelman.container.hash.keybucket;
struct HashSet(Key, Key emptyKey, Key deletedKey, Alloc = GCAllocator)
{
mixin HashTablePart!(KeyBucket!(Key, emptyKey, deletedKey), false);
}
struct HashSet(Key, Alloc = GCAllocator)
{
mixin HashTablePart!(MetaKeyBucket!(Key), false);
}
unittest {
void test(M)()
{
M map;
map.put(2); // placed in bucket 0
map.reserve(1); // capacity 2 -> 4, must be placed in bucket 2
assert(map[2]);
}
test!(HashSet!(ushort, ushort.max, ushort.max-1));
test!(HashSet!(ushort));
}
unittest {
import std.string;
void test(M)()
{
M map;
ushort[] keys = [140,268,396,524,652,780,908,28,156,284,
412,540,668,796,924,920,792,664,536,408,280,152,24];
foreach (i, ushort key; keys) {
assert(map.length == i);
map.put(key);
}
foreach (i, ushort key; keys) {
assert(map.length == keys.length - i);
map.remove(key);
}
foreach (i, ushort key; keys) {
assert(map.length == i);
map.put(key);
}
}
import std.stdio;
test!(HashSet!(ushort, ushort.max, ushort.max-1));
test!(HashSet!(ushort));
}
|
D
|
module java.util.MissingResourceException;
import java.lang.all;
class MissingResourceException : Exception {
String classname;
String key;
this( String msg, String classname, String key ){
super(msg);
this.classname = classname;
this.key = key;
}
}
|
D
|
/Users/hernaniruegasvillarreal/Documents/github/swift/Tinder/dragging-objects/Build/Intermediates/Swipe\ Demo.build/Debug-iphonesimulator/Swipe\ Demo.build/Objects-normal/x86_64/AppDelegate.o : /Users/hernaniruegasvillarreal/Documents/github/swift/Tinder/dragging-objects/Swipe\ Demo/ViewController.swift /Users/hernaniruegasvillarreal/Documents/github/swift/Tinder/dragging-objects/Swipe\ Demo/AppDelegate.swift /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/SwiftOnoneSupport.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/Foundation.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/Dispatch.swiftmodule /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/CoreGraphics.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/CoreImage.swiftmodule
/Users/hernaniruegasvillarreal/Documents/github/swift/Tinder/dragging-objects/Build/Intermediates/Swipe\ Demo.build/Debug-iphonesimulator/Swipe\ Demo.build/Objects-normal/x86_64/AppDelegate~partial.swiftmodule : /Users/hernaniruegasvillarreal/Documents/github/swift/Tinder/dragging-objects/Swipe\ Demo/ViewController.swift /Users/hernaniruegasvillarreal/Documents/github/swift/Tinder/dragging-objects/Swipe\ Demo/AppDelegate.swift /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/SwiftOnoneSupport.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/Foundation.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/Dispatch.swiftmodule /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/CoreGraphics.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/CoreImage.swiftmodule
/Users/hernaniruegasvillarreal/Documents/github/swift/Tinder/dragging-objects/Build/Intermediates/Swipe\ Demo.build/Debug-iphonesimulator/Swipe\ Demo.build/Objects-normal/x86_64/AppDelegate~partial.swiftdoc : /Users/hernaniruegasvillarreal/Documents/github/swift/Tinder/dragging-objects/Swipe\ Demo/ViewController.swift /Users/hernaniruegasvillarreal/Documents/github/swift/Tinder/dragging-objects/Swipe\ Demo/AppDelegate.swift /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/SwiftOnoneSupport.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/Foundation.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/Dispatch.swiftmodule /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/CoreGraphics.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/CoreImage.swiftmodule
|
D
|
module org.eclipse.swt.internal.mozilla.nsEmbedString;
import java.lang.all;
import org.eclipse.swt.internal.mozilla.Common;
import org.eclipse.swt.internal.mozilla.nsStringAPI;
import XPCOM = org.eclipse.swt.internal.mozilla.XPCOM;
scope class nsEmbedString
{
this(String16 s)
{
nsresult result;
result = NS_StringContainerInit2(&str, cast(wchar*)s.ptr, s.length, 0);
if (XPCOM.NS_FAILED(result))
throw new Exception("Init string container fail");
}
this()
{
nsresult result;
result = NS_StringContainerInit(&str);
if (XPCOM.NS_FAILED(result))
throw new Exception("Init string container fail");
}
nsAString* opCast()
{
return cast(nsAString*)&str;
}
String16 toString16()
{
wchar* buffer = null;
PRBool terminated;
uint len = NS_StringGetData(cast(nsAString*)&str, &buffer, &terminated);
return buffer[0 .. len]._idup();
}
override String toString()
{
return String_valueOf(this.toString16());
}
~this()
{
NS_StringContainerFinish(&str);
}
private:
nsStringContainer str;
}
scope class nsEmbedCString
{
this(String s)
{
nsresult result;
result = NS_CStringContainerInit2(&str, s.ptr, s.length, 0);
if (XPCOM.NS_FAILED(result))
throw new Exception("Init string container fail");
}
this()
{
nsresult result;
result = NS_CStringContainerInit(&str);
if (XPCOM.NS_FAILED(result))
throw new Exception("Init string container fail");
}
nsACString* opCast()
{
return cast(nsACString*)&str;
}
String toString()
{
char* buffer = null;
PRBool terminated;
uint len = NS_CStringGetData(cast(nsACString*)&str, &buffer, &terminated);
return buffer[0 .. len]._idup();
}
~this()
{
NS_CStringContainerFinish(&str);
}
private:
nsCStringContainer str;
}
|
D
|
instance Mod_4044_UntoterNovize_27_MT (Npc_Default)
{
//-------- primary data --------
name = "Untoter Novize";
Npctype = Npctype_UNTOTERNOVIZE;
guild = GIL_STRF;
level = 20;
voice = 2;
id = 4044;
//-------- abilities --------
B_SetAttributesToChapter (self, 4);
EquipItem (self, ItMw_1h_Nov_Mace);
//-------- visuals --------
// animations
Mdl_SetVisual (self,"HUMANS.MDS");
Mdl_ApplyOverlayMds (self,"Humans_Relaxed.mds");
// body mesh ,bdytex,skin,head mesh ,headtex,teethtex,ruestung
Mdl_SetVisualBody (self,"hum_body_Naked0", 15, 0,"Hum_Head_FatBald", 199, 1, ITAR_UntoterNovize);
Mdl_SetModelFatness(self,0);
B_SetFightSkills (self, 65);
B_CreateAmbientInv (self);
fight_tactic = FAI_HUMAN_STRONG;
//-------- Talente --------
//-------- inventory --------
//-------------Daily Routine-------------
daily_routine = Rtn_start_4044;
//------------- //MISSIONs-------------
};
FUNC VOID Rtn_start_4044 ()
{
TA_Stand_WP (02,00,08,00,"PALTO_12");
TA_Stand_WP (08,00,02,00,"PALTO_12");
};
|
D
|
/**
Copyright: Copyright (c) 2016-2017 Andrey Penechko.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: Andrey Penechko.
*/
module voxelman.utils.mapping;
struct Mapping(InfoType, bool withTypeMap = false)
{
static assert(__traits(compiles, {InfoType info; info.id=1; info.name="str";}),
"InfoType is required to have size_t id; and string name; properties");
InfoType[] infoArray;
size_t[string] nameToIndexMap;
static if (withTypeMap)
size_t[TypeInfo] typeToIndexMap;
size_t length() @property
{
return infoArray.length;
}
ref InfoType opIndex(size_t id)
{
return infoArray[id];
}
static if (withTypeMap)
{
size_t put(T)(InfoType info)
{
size_t newId = putImpl(info);
assert(typeid(T) !in typeToIndexMap, "Type "~T.stringof~" was already registered");
typeToIndexMap[typeid(T)] = newId;
return newId;
}
bool contains(T)()
{
return typeid(T) in typeToIndexMap;
}
size_t id(T)()
{
return typeToIndexMap.get(typeid(T), size_t.max);
}
} else {
size_t put(InfoType info)
{
return putImpl(info);
}
}
private size_t putImpl(InfoType info)
{
size_t newId = infoArray.length;
nameToIndexMap[info.name] = newId;
info.id = newId;
infoArray ~= info;
return newId;
}
auto nameRange() @property
{
import std.algorithm : map;
return infoArray.map!(a => a.name);
}
size_t id(string name)
{
return nameToIndexMap.get(name, size_t.max);
}
string name(size_t id)
{
import std.string : format;
if (id >= infoArray.length) return format("|Unknown %s %s|", InfoType.stringof, id);
return infoArray[id].name;
}
void setMapping(R)(R names)
{
import std.range : isInputRange, hasLength;
static assert(isInputRange!R, "names should be InputRange of strings");
InfoType[] newArray;
static if (hasLength!R)
{
if (names.length == 0)
{
return;
}
newArray.reserve(names.length);
}
foreach(i, name; names)
{
size_t index = nameToIndexMap.get(name, size_t.max);
size_t newId = newArray.length;
if (index == size_t.max)
{
InfoType info;
info.name = name;
newArray ~= info;
}
else
{
newArray ~= infoArray[index];
infoArray[index].id = size_t.max; // Mark as removed
}
newArray[$-1].id = newId;
}
foreach(oldItem; infoArray)
if (oldItem.id != size_t.max)
{
size_t newId = newArray.length;
newArray ~= oldItem;
newArray[$-1].id = newId;
}
infoArray = newArray;
size_t[string] newMap;
foreach(ref info; infoArray)
{
newMap[info.name] = info.id;
}
nameToIndexMap = newMap;
}
}
//static assert(__traits(compiles, {struct ValidInfo {size_t id; string name;} Mapping!ValidInfo m;}));
//static assert(!is(typeof({struct InvalidInfo {} Mapping!InvalidInfo invmapping;})));
//static assert(!is(typeof({struct InvalidInfo {size_t id;} Mapping!InvalidInfo invmapping;})));
//static assert(!is(typeof({struct InvalidInfo {string name;} Mapping!InvalidInfo invmapping;})));
unittest
{
//import std.stdio;
struct Info
{
string name;
size_t id;
}
Mapping!(Info) mapping;
mapping.setMapping(["first", "second"]);
mapping.put(Info("third"));
assert(mapping[0].name == "first");
assert(mapping[1].name == "second");
assert(mapping[2].name == "third");
Mapping!(Info, true) mappingTyped;
mappingTyped.setMapping(["first", "second"]);
mappingTyped.put!int(Info("third"));
assert(mappingTyped[0].name == "first");
assert(mappingTyped[1].name == "second");
assert(mappingTyped[2].name == "third");
assert(mappingTyped.id!int == 2);
assert(mappingTyped.id!bool == size_t.max);
}
|
D
|
module roaring.roaring;
import roaring.c;
Bitmap bitmapOf(const uint[] args ...)
{
return Bitmap.fromArray(args);
}
Bitmap bitmapOf(const uint[] bits)
{
return Bitmap.fromArray(bits);
}
Bitmap bitmapOf(T)(T rng)
{
auto r = new Bitmap;
foreach (bit; rng) r.add(bit);
return r;
}
unittest
{
import std.range : iota;
import std.conv : to;
const r1 = bitmapOf(0, 1, 2, 3, 4);
const r2 = bitmapOf([0, 1, 2, 3, 4]);
const r3 = bitmapOf(5.iota);
assert("{0, 1, 2, 3, 4}" == to!string(r1));
assert((r1 == r2) && (r1 == r3));
}
Bitmap readBitmap(const char[] buf)
{
return Bitmap.read(buf);
}
char[] writeBitmap(const Bitmap r)
{
return r.write();
}
unittest
{
import core.exception : OutOfMemoryError;
const r1 = bitmapOf(5, 1, 2, 3, 5, 6);
char[] buf = writeBitmap(r1);
const r2 = readBitmap(buf);
assert(r1 == r2);
try {
buf.length = 0;
readBitmap(buf) || assert(false);
}
catch (OutOfMemoryError e) {
// pass
}
}
BitRange range(const Bitmap r)
{
return new BitRange(r.bitmap);
}
class BitRange
{
@nogc @property @safe
bool empty() const pure
{
return !this.it.has_value;
}
@nogc @property @safe
uint front() const pure
{
return this.it.current_value;
}
@nogc
void popFront()
{
if (it.has_value) roaring_advance_uint32_iterator(this.it);
}
@nogc
private this(const roaring_bitmap_t *bmp)
{
this.it = roaring_create_iterator(bmp);
}
@nogc
private ~this()
{
if (this.it) roaring_free_uint32_iterator(this.it);
}
private roaring_uint32_iterator_t *it;
}
unittest
{
import std.algorithm : filter, sum;
assert(6 == bitmapOf(1, 2, 3, 4, 5).range.filter!(a => a % 2 == 0).sum);
}
class Bitmap
{
/// Creates an empty bitmap
this()
{
this(roaring_bitmap_create());
}
~this()
{
roaring_bitmap_free(this.bitmap);
this.bitmap = null;
}
/** Creates an empty bitmap with a predefined capacity
PARAMS
uint cap: The predefined capacity
*/
this(const uint cap)
{
this(roaring_bitmap_create_with_capacity(cap));
}
private this(roaring_bitmap_t *r)
{
this.bitmap = r;
}
private static Bitmap fromArray(const uint[] bits)
{
Bitmap r = new Bitmap(cast(uint)bits.length);
roaring_bitmap_add_many(r.bitmap, bits.length, bits.ptr);
return r;
}
private static Bitmap fromRange(const ulong min, const ulong max, const uint step)
{
auto rr = roaring_bitmap_from_range(min, max, step);
return new Bitmap(rr);
}
private static Bitmap read(const char[] buf)
{
import core.exception : OutOfMemoryError;
auto rr = roaring_bitmap_portable_deserialize_safe(buf.ptr, buf.length);
if (!rr) {
throw new OutOfMemoryError;
}
return new Bitmap(rr);
}
private char[] write() const
{
char[] buf = new char[sizeInBytes];
const size = roaring_bitmap_portable_serialize(this.bitmap, buf.ptr);
return buf[0..size];
}
@nogc @property @safe
uint length() const pure
{
return cast(uint)roaring_bitmap_get_cardinality(this.bitmap);
}
@nogc @property @safe
void copyOnWrite(bool enable) pure
{
this.bitmap.copy_on_write = enable;
}
@nogc @property @safe
bool copyOnWrite() const pure
{
return this.bitmap.copy_on_write;
}
unittest
{
Bitmap r = new Bitmap;
r.copyOnWrite = true;
assert(r.copyOnWrite == true);
}
uint[] toArray() const
{
uint[] a = new uint[length];
roaring_bitmap_to_uint32_array(this.bitmap, a.ptr);
return a[];
}
unittest
{
const r = bitmapOf(5, 1, 2, 3, 5, 6);
uint[] a = r.toArray;
assert(a.length == 5);
}
@nogc @safe
void add(const uint x)
{
roaring_bitmap_add(this.bitmap, x);
}
unittest
{
Bitmap r = new Bitmap;
r.add(5);
assert(5 in r);
}
/**
* Remove value x
*
*/
@nogc @safe
void remove(const uint x)
{
roaring_bitmap_remove(this.bitmap, x);
}
unittest
{
Bitmap r = bitmapOf(5);
r.remove(5);
assert(5 !in r);
}
/**
* Check if value x is present
*/
@nogc @safe
bool contains(const uint x) const pure
{
return roaring_bitmap_contains(this.bitmap, x);
}
/**
* Return the largest value (if not empty)
*
*/
@nogc @property @safe
uint maximum() const pure
{
return roaring_bitmap_maximum(this.bitmap);
}
/**
* Return the smallest value (if not empty)
*
*/
@nogc @property @safe
uint minimum() const pure
{
return roaring_bitmap_minimum(this.bitmap);
}
unittest
{
const r2 = bitmapOf(100, 10, uint.max);
assert(r2.minimum == 10);
assert(r2.maximum == uint.max);
}
@nogc @property @safe
size_t sizeInBytes() const pure
{
return roaring_bitmap_portable_size_in_bytes(this.bitmap);
}
unittest
{
assert(bitmapOf(5).sizeInBytes > 4);
}
/**
* Returns the number of integers that are smaller or equal to x.
*/
@nogc @safe
ulong rank(const uint rank) const pure
{
return roaring_bitmap_rank(this.bitmap, rank);
}
unittest
{
const r = bitmapOf(5, 1, 2, 3, 5, 6);
assert(r.rank(4) == 3);
}
@nogc @safe
bool optimize()
{
return roaring_bitmap_run_optimize(this.bitmap);
}
unittest
{
auto r1 = bitmapOf(5, 1, 2, 3, 5, 6);
r1.copyOnWrite = true;
//check optimization
auto size1 = r1.sizeInBytes;
r1.optimize;
assert(r1.sizeInBytes < size1);
}
int opApply(int delegate(ref uint value) dg) const
{
const bmp = this.bitmap;
auto it = roaring_create_iterator(bmp);
int dgReturn = 0;
while (it.has_value) {
dgReturn = dg(it.current_value);
if (dgReturn) break;
roaring_advance_uint32_iterator(it);
}
roaring_free_uint32_iterator(it);
return dgReturn;
}
unittest
{
const bitmap = bitmapOf(5, 1, 2, 3, 5, 6);
ulong sum;
foreach (bit; bitmap) {
sum += bit;
}
assert(sum == 17);
}
// TODO: un-duplicate this method with ^^^
int opApply(int delegate(ref uint index, ref uint value) dg) const
{
const bmp = this.bitmap;
auto it = roaring_create_iterator(bmp);
int dgReturn = 0;
uint index = 0;
while (it.has_value) {
dgReturn = dg(index, it.current_value);
if (dgReturn) break;
index += 1;
roaring_advance_uint32_iterator(it);
}
roaring_free_uint32_iterator(it);
return dgReturn;
}
unittest
{
const bitmap = bitmapOf(5, 1, 2, 3, 5, 6);
ulong bitSum;
int iSum;
foreach (i, bit; bitmap) {
bitSum += bit;
iSum += i;
}
assert(bitSum == 17);
assert(iSum == 10);
}
Bitmap opBinary(const string op)(const Bitmap b) const
if (op == "&" || op == "|" || op == "^")
{
roaring_bitmap_t *result;
static if (op == "&") result = roaring_bitmap_and(this.bitmap, b.bitmap);
else static if (op == "|") result = roaring_bitmap_or(this.bitmap, b.bitmap);
else static if (op == "^") result = roaring_bitmap_xor(this.bitmap, b.bitmap);
else static assert(0, "Operator " ~ op ~ " not implemented.");
return new Bitmap(result);
}
unittest
{
const r1 = bitmapOf(5, 1, 2, 3, 5, 6);
const r2 = bitmapOf(6, 7, 8);
assert((r1 | r2) == bitmapOf(1, 2, 3, 5, 6, 7, 8));
assert((r1 & r2) == bitmapOf(6));
assert((r1 ^ r2) == bitmapOf(1, 2, 3, 5, 7, 8));
}
@nogc
void opOpAssign(const string op)(const Bitmap b)
if (op == "&" || op == "|" || op == "^")
{
static if (op == "&") roaring_bitmap_and_inplace(this.bitmap, b.bitmap);
else static if (op == "|") roaring_bitmap_or_inplace(this.bitmap, b.bitmap);
else static if (op == "^") roaring_bitmap_xor_inplace(this.bitmap, b.bitmap);
else static assert(0, "Operator " ~ op ~ " not implemented.");
}
unittest
{
auto r1 = bitmapOf(5, 1, 2, 3, 5, 6);
const r2 = bitmapOf(6, 7, 8);
r1 |= r2;
assert(r1 == bitmapOf(1, 2, 3, 5, 6, 7, 8));
r1 = bitmapOf(5, 1, 2, 3, 5, 6);
r1 &= r2;
assert(r1 == bitmapOf(6));
r1 = bitmapOf(5, 1, 2, 3, 5, 6);
r1 ^= r2;
assert(r1 == bitmapOf(1, 2, 3, 5, 7, 8));
}
/**
* Computes the difference of this bitmap and `b`; that is returns the
* elements of `this` that are not in `b`.
*/
Bitmap andNot(const Bitmap b) const
{
return new Bitmap(roaring_bitmap_andnot(bitmap, b.bitmap));
}
unittest
{
const a = bitmapOf(1, 2, 4, 5);
const b = bitmapOf(2, 3, 5);
assert(a.andNot(b) == bitmapOf(1, 4));
assert(b.andNot(a) == bitmapOf(3));
}
/**
* Performs the andNot operation in place.
*/
void andNotInPlace(const Bitmap b)
{
roaring_bitmap_andnot_inplace(bitmap, b.bitmap);
}
unittest
{
auto a = bitmapOf(1, 2, 4, 5);
const b = bitmapOf(2, 3, 5);
a.andNotInPlace(b);
assert(a == bitmapOf(1, 4));
}
@nogc @safe
bool opBinaryRight(const string op)(const uint x) const
if (op == "in")
{
static if (op == "in") return roaring_bitmap_contains(this.bitmap, x);
else static assert(0, "Operator " ~ op ~ " not implemented.");
}
unittest
{
import std.range : iota;
Bitmap r1 = bitmapOf(iota(100, 1000));
assert(500 in r1);
}
bool opBinaryRight(const string op)(const Bitmap b) const
if (op == "in")
{
static if (op == "in") return roaring_bitmap_is_subset(b.bitmap, this.bitmap);
else static assert(0, "Operator " ~ op ~ " not implemented.");
}
unittest
{
import std.range : iota;
Bitmap r1 = bitmapOf(iota(100, 1000));
Bitmap r2 = bitmapOf(iota(200, 400));
assert(r2 in r1);
}
uint opIndex(uint rank) const
{
import core.exception : RangeError;
uint v;
if (!roaring_bitmap_select(this.bitmap, rank, &v)) {
throw new RangeError;
}
return v;
}
unittest
{
import core.exception : RangeError;
const bitmap = bitmapOf(5, 1, 2, 3, 5, 6);
assert(5 == bitmap[3]);
// accessing an index > cardinality(set) throws a RangeError
try {
bitmap[999] || assert(false);
}
catch (RangeError e) {
// pass
}
}
Bitmap opSlice(int start, int end) const
{
import core.exception : RangeError;
if (start < 0 || start >= opDollar) {
throw new RangeError;
}
Bitmap r = new Bitmap;
foreach (i, bit; this) {
if (i < start) continue;
if (i >= end) break;
r.add(this[i]);
}
return r;
}
@nogc @property @safe
uint opDollar() const pure
{
return length;
}
unittest
{
import core.exception : RangeError;
const bitmap = bitmapOf(5, 1, 2, 3, 5, 6);
assert(bitmapOf(3, 5, 6) == bitmap[2..$]);
import core.exception : RangeError;
// accessing an index < 0 throws a RangeError
try {
bitmap[-1..$] || assert(false);
}
catch (RangeError e) {
// pass
}
import core.exception : RangeError;
// accessing an index > $ throws a RangeError
try {
bitmap[$..$] || assert(false);
}
catch (RangeError e) {
// pass
}
}
override bool opEquals(Object b) const
{
import std.stdio : writeln;
if (this is b) return true;
if (b is null) return false;
if (typeid(this) == typeid(b)) {
return roaring_bitmap_equals(this.bitmap, (cast(Bitmap)b).bitmap);
}
return false;
}
unittest
{
const r1 = Bitmap.fromRange(10, 20, 3);
const r2 = Bitmap.fromArray([10, 13, 16, 19]);
assert(r1 == r2);
const r3 = Bitmap.fromArray([10]);
assert(r1 != r3);
assert(r1 != new Object);
}
void opOpAssign(const string op)(const uint x)
if (op == "|" || op == "-")
{
static if (op == "|") roaring_bitmap_add(this.bitmap, x);
else static if (op == "-") roaring_bitmap_remove(this.bitmap, x);
}
unittest
{
Bitmap r1 = new Bitmap;
r1 |= 500;
assert(500 in r1);
}
void toString(scope void delegate(const(char)[]) sink) const
{
import std.format : format;
import std.range : enumerate;
sink("{");
foreach (i, bit; this) {
if (i == 0) sink(format("%d", bit));
else sink(format(", %d", bit));
}
sink("}");
}
unittest
{
import std.conv : to;
const bitmap = bitmapOf(5, 1, 2, 3, 5, 6);
assert("{1, 2, 3, 5, 6}" == to!string(bitmap));
}
Bitmap dup() const @property
{
return new Bitmap(roaring_bitmap_copy(bitmap));
}
unittest
{
const original = bitmapOf(1, 2, 3, 4);
auto copy = original.dup;
// Copy is editable whereas original is const
copy.add(5);
assert(5 !in original);
assert(5 in copy);
}
private roaring_bitmap_t* bitmap;
}
unittest
{
import std.stdio : writefln, writeln;
import roaring.roaring : Bitmap, bitmapOf;
// create a new roaring bitmap instance
auto r1 = new Bitmap;
// add some bits to the bitmap
r1.add(5);
// create from an array
auto ra = bitmapOf([1, 2, 3]);
// create from a range
import std.range : iota;
assert(bitmapOf(0, 1, 2, 3) == bitmapOf(4.iota));
// create a new roaring bitmap instance from some numbers
auto r2 = bitmapOf(1, 3, 5, 15);
// check whether a value is contained
assert(r2.contains(5));
assert(5 in r2); // r2 contains 5
assert(99 !in r2); // r2 does not contain 99
// get minimum and maximum values in a bitmap
assert(r2.minimum == 1);
assert(r2.maximum == 15);
// remove a value from the bitmap
r2.remove(5);
assert(!r2.contains(5));
// compute how many bits there are:
assert(3 == r2.length);
// check whether a bitmap is subset of another
const sub = bitmapOf(1, 5);
const sup = bitmapOf(1, 2, 3, 4, 5, 6);
assert(sub in sup);
// iterate on a bitmap
const r3 = bitmapOf(1, 5, 10, 20);
ulong s = 0;
foreach (bit; r3) {
s += bit;
}
assert(s == 36);
// iterate on a bitmap and index
foreach(i, bit; r3) {
writefln("%d: %d", i, bit);
}
import roaring.roaring : readBitmap, writeBitmap;
// serialize the bitmap
char[] buf = writeBitmap(r3);
// deserialize from a char array
const r3Copy = readBitmap(buf);
assert(r3 == r3Copy);
// find the intersection of bitmaps
const r4 = bitmapOf(1, 5, 6);
const r5 = bitmapOf(1, 2, 3, 4, 5);
assert((r4 & r5) == bitmapOf(1, 5));
// find the union of bitmaps
assert((r4 | r5) == bitmapOf(1, 2, 3, 4, 5, 6));
const r6 = bitmapOf(0, 10, 20, 30, 40, 50);
// get the bit for the index
assert(20 == r6[2]);
// slice a bitmap
assert(bitmapOf(30, 40, 50) == r6[3..$]);
// convert the bitmap to a string
writeln("Bitmap: ", r6);
import std.conv : to;
assert("{0, 10, 20, 30, 40, 50}" == to!string(r6));
// the bit range!
import std.algorithm : filter, sum;
import roaring.roaring : range, BitRange;
// sum of bits in r6 which are bit % 20==0
assert(60 == r6.range.filter!(b => b % 20 == 0).sum);
// if your bitmaps have long runs, you can compress them
auto r7 = bitmapOf(1000.iota);
writeln("size before optimize = ", r7.sizeInBytes);
r7.optimize();
writeln("size after optimize = ", r7.sizeInBytes);
// copy a bitmap (uses copy-on-write under the hood)
const r8 = r7.dup;
assert(r8 == r7);
}
|
D
|
/**
* Contains the external GC interface.
*
* Copyright: Copyright Digital Mars 2005 - 2013.
* License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
* Authors: Walter Bright, Sean Kelly
*/
/* Copyright Digital Mars 2005 - 2013.
* 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 gc.proxy;
import gc.gc;
import gc.stats;
import core.stdc.stdlib;
private
{
version = GCCLASS;
version( GCCLASS )
alias GC gc_t;
else
alias GC* gc_t;
__gshared gc_t _gc;
extern (C) void thread_init();
extern (C) void thread_term();
struct Proxy
{
extern (C)
{
void function() gc_enable;
void function() gc_disable;
void function() gc_collect;
void function() gc_minimize;
uint function(void*) gc_getAttr;
uint function(void*, uint) gc_setAttr;
uint function(void*, uint) gc_clrAttr;
void* function(size_t, uint, const TypeInfo) gc_malloc;
BlkInfo function(size_t, uint, const TypeInfo) gc_qalloc;
void* function(size_t, uint, const TypeInfo) gc_calloc;
void* function(void*, size_t, uint ba, const TypeInfo) gc_realloc;
size_t function(void*, size_t, size_t, const TypeInfo) gc_extend;
size_t function(size_t) gc_reserve;
void function(void*) gc_free;
bool function(void*, size_t, const TypeInfo) gc_emplace;
void* function(void*) gc_addrOf;
size_t function(void*) gc_sizeOf;
BlkInfo function(void*) gc_query;
void function(void*) gc_addRoot;
void function(void*, size_t) gc_addRange;
void function(void*, size_t, bool) gc_addRange_hp;
void function(void*) gc_removeRoot;
void function(void*) gc_removeRange;
}
}
__gshared Proxy pthis;
__gshared Proxy* proxy;
void initProxy()
{
pthis.gc_enable = &gc_enable;
pthis.gc_disable = &gc_disable;
pthis.gc_collect = &gc_collect;
pthis.gc_minimize = &gc_minimize;
pthis.gc_getAttr = &gc_getAttr;
pthis.gc_setAttr = &gc_setAttr;
pthis.gc_clrAttr = &gc_clrAttr;
pthis.gc_malloc = &gc_malloc;
pthis.gc_qalloc = &gc_qalloc;
pthis.gc_calloc = &gc_calloc;
pthis.gc_realloc = &gc_realloc;
pthis.gc_extend = &gc_extend;
pthis.gc_reserve = &gc_reserve;
pthis.gc_free = &gc_free;
pthis.gc_emplace = &gc_emplace;
pthis.gc_addrOf = &gc_addrOf;
pthis.gc_sizeOf = &gc_sizeOf;
pthis.gc_query = &gc_query;
pthis.gc_addRoot = &gc_addRoot;
pthis.gc_addRange = &gc_addRange;
pthis.gc_addRange_hp = &gc_addRange_hp;
pthis.gc_removeRoot = &gc_removeRoot;
pthis.gc_removeRange = &gc_removeRange;
}
}
extern (C)
{
void gc_init()
{
version (GCCLASS)
{ void* p;
ClassInfo ci = typeid(GC);
p = malloc(ci.init.length);
(cast(byte*)p)[0 .. ci.init.length] = ci.init[];
_gc = cast(GC)p;
}
else
{
_gc = cast(GC*) calloc(1, GC.sizeof);
}
_gc.initialize();
// NOTE: The GC must initialize the thread library
// before its first collection.
thread_init();
initProxy();
}
void gc_term()
{
// NOTE: There may be daemons threads still running when this routine is
// called. If so, cleaning memory out from under then is a good
// way to make them crash horribly. This probably doesn't matter
// much since the app is supposed to be shutting down anyway, but
// I'm disabling cleanup for now until I can think about it some
// more.
//
// NOTE: Due to popular demand, this has been re-enabled. It still has
// the problems mentioned above though, so I guess we'll see.
_gc.fullCollectNoStack(); // not really a 'collect all' -- still scans
// static data area, roots, and ranges.
thread_term();
_gc.Dtor();
free(cast(void*)_gc);
_gc = null;
}
void gc_enable()
{
if( proxy is null )
return _gc.enable();
return proxy.gc_enable();
}
void gc_disable()
{
if( proxy is null )
return _gc.disable();
return proxy.gc_disable();
}
void gc_collect()
{
if( proxy is null )
{
_gc.fullCollect();
return;
}
return proxy.gc_collect();
}
void gc_minimize()
{
if( proxy is null )
return _gc.minimize();
return proxy.gc_minimize();
}
uint gc_getAttr( void* p )
{
if( proxy is null )
return _gc.getAttr( p );
return proxy.gc_getAttr( p );
}
uint gc_setAttr( void* p, uint a )
{
if( proxy is null )
return _gc.setAttr( p, a );
return proxy.gc_setAttr( p, a );
}
uint gc_clrAttr( void* p, uint a )
{
if( proxy is null )
return _gc.clrAttr( p, a );
return proxy.gc_clrAttr( p, a );
}
void* gc_malloc( size_t sz, uint ba = 0, const TypeInfo ti = null )
{
if( proxy is null )
return _gc.malloc( sz, ba, null, ti );
return proxy.gc_malloc( sz, ba, ti );
}
BlkInfo gc_qalloc( size_t sz, uint ba = 0, const TypeInfo ti = null )
{
if( proxy is null )
{
BlkInfo retval;
retval.base = _gc.malloc( sz, ba, &retval.size, ti );
retval.attr = ba;
return retval;
}
return proxy.gc_qalloc( sz, ba, ti );
}
void* gc_calloc( size_t sz, uint ba = 0, const TypeInfo ti = null )
{
if( proxy is null )
return _gc.calloc( sz, ba, null, ti );
return proxy.gc_calloc( sz, ba, ti );
}
void* gc_realloc( void* p, size_t sz, uint ba = 0, const TypeInfo ti = null )
{
if( proxy is null )
return _gc.realloc( p, sz, ba, null, ti );
return proxy.gc_realloc( p, sz, ba, ti );
}
size_t gc_extend( void* p, size_t mx, size_t sz, const TypeInfo ti = null )
{
if( proxy is null )
return _gc.extend( p, mx, sz, ti );
return proxy.gc_extend( p, mx, sz,ti );
}
size_t gc_reserve( size_t sz )
{
if( proxy is null )
return _gc.reserve( sz );
return proxy.gc_reserve( sz );
}
void gc_free( void* p )
{
if( proxy is null )
return _gc.free( p );
return proxy.gc_free( p );
}
bool gc_emplace( void* p, size_t len, const TypeInfo ti )
{
if( proxy is null )
return _gc.emplace( p, len, ti );
return proxy.gc_emplace( p, len, ti );
}
void* gc_addrOf( void* p )
{
if( proxy is null )
return _gc.addrOf( p );
return proxy.gc_addrOf( p );
}
size_t gc_sizeOf( void* p )
{
if( proxy is null )
return _gc.sizeOf( p );
return proxy.gc_sizeOf( p );
}
BlkInfo gc_query( void* p )
{
if( proxy is null )
return _gc.query( p );
return proxy.gc_query( p );
}
// NOTE: This routine is experimental. The stats or function name may change
// before it is made officially available.
GCStats gc_stats()
{
if( proxy is null )
{
GCStats stats = void;
_gc.getStats( stats );
return stats;
}
// TODO: Add proxy support for this once the layout of GCStats is
// finalized.
//return proxy.gc_stats();
return GCStats.init;
}
void gc_addRoot( void* p )
{
if( proxy is null )
return _gc.addRoot( p );
return proxy.gc_addRoot( p );
}
void gc_addRange( void* p, size_t sz )
{
if( proxy is null )
return _gc.addRange( p, sz );
return proxy.gc_addRange( p, sz );
}
void gc_addRange_hp( void* p, size_t sz, bool tls )
{
if( proxy is null )
return _gc.addRange_hp( p, sz, tls );
return proxy.gc_addRange_hp( p, sz, tls );
}
void gc_removeRoot( void* p )
{
if( proxy is null )
return _gc.removeRoot( p );
return proxy.gc_removeRoot( p );
}
void gc_removeRange( void* p )
{
if( proxy is null )
return _gc.removeRange( p );
return proxy.gc_removeRange( p );
}
Proxy* gc_getProxy()
{
return &pthis;
}
export
{
void gc_setProxy( Proxy* p )
{
if( proxy !is null )
{
// TODO: Decide if this is an error condition.
}
proxy = p;
foreach( r; _gc.rootIter )
proxy.gc_addRoot( r );
foreach( r; _gc.rangeIter )
proxy.gc_addRange( r.pbot, r.ptop - r.pbot );
}
void gc_clrProxy()
{
foreach( r; _gc.rangeIter )
proxy.gc_removeRange( r.pbot );
foreach( r; _gc.rootIter )
proxy.gc_removeRoot( r );
proxy = null;
}
}
}
|
D
|
a water solution of ammonia
a pungent gas compounded of nitrogen and hydrogen (NH3)
|
D
|
module d.llvm.intrinsic;
import d.llvm.local;
import source.name;
import d.ir.expression;
import llvm.c.core;
struct IntrinsicGenData {
private:
LLVMValueRef[Name] cache;
}
struct IntrinsicGen {
private LocalPass pass;
alias pass this;
this(LocalPass pass) {
this.pass = pass;
}
private @property ref LLVMValueRef[Name] cache() {
return intrinsicGenData.cache;
}
LLVMValueRef build(Intrinsic i, Expression[] args) {
import d.llvm.expression, std.algorithm, std.range;
return build(i, args.map!(a => ExpressionGen(pass).visit(a)).array());
}
LLVMValueRef build(Intrinsic i, LLVMValueRef[] args) {
final switch (i) with (Intrinsic) {
case None:
assert(0, "invalid intrinsic");
case Expect:
return expect(args);
case FetchAdd:
return fetchAdd(args);
case CompareAndSwap:
return cas(false, args);
case CompareAndSwapWeak:
return cas(true, args);
case PopCount:
return ctpop(args);
case CountLeadingZeros:
return ctlz(args);
case CountTrailingZeros:
return cttz(args);
case ByteSwap:
return bswap(args);
case ReadCycleCounter:
return readCycleCounter(args);
}
}
LLVMValueRef expect(LLVMValueRef[] args)
in(args.length == 2, "Invalid argument count") {
return expect(args[0], args[1]);
}
LLVMValueRef expect(LLVMValueRef v, LLVMValueRef e) {
LLVMValueRef[2] args = [v, e];
auto fun = getExpect();
auto t = LLVMGlobalGetValueType(fun);
return LLVMBuildCall2(builder, t, fun, args.ptr, args.length, "");
}
auto getExpect() {
auto name = context.getName("llvm.expect.i1");
if (auto fPtr = name in cache) {
return *fPtr;
}
auto i1 = LLVMInt1TypeInContext(llvmCtx);
LLVMTypeRef[2] params = [i1, i1];
auto type = LLVMFunctionType(i1, params.ptr, params.length, false);
return cache[name] =
LLVMAddFunction(dmodule, name.toStringz(context), type);
}
LLVMValueRef fetchAdd(LLVMValueRef[] args)
in(args.length == 2, "Invalid argument count") {
return fetchAdd(args[0], args[1],
LLVMAtomicOrdering.SequentiallyConsistent);
}
LLVMValueRef fetchAdd(LLVMValueRef ptr, LLVMValueRef increment,
LLVMAtomicOrdering ordering) {
return buildAtomicRMW(LLVMAtomicRMWBinOp.Add, ptr, increment, ordering);
}
LLVMValueRef buildAtomicRMW(
LLVMAtomicRMWBinOp op,
LLVMValueRef ptr,
LLVMValueRef increment,
LLVMAtomicOrdering ordering,
) {
return LLVMBuildAtomicRMW(builder, op, ptr, increment, ordering, false);
}
LLVMValueRef cas(bool weak, LLVMValueRef[] args)
in(args.length == 3, "Invalid argument count") {
return cas(weak, args[0], args[1], args[2],
LLVMAtomicOrdering.SequentiallyConsistent);
}
LLVMValueRef cas(bool weak, LLVMValueRef ptr, LLVMValueRef old,
LLVMValueRef val, LLVMAtomicOrdering ordering) {
auto i = LLVMBuildAtomicCmpXchg(builder, ptr, old, val, ordering,
ordering, false);
LLVMSetWeak(i, weak);
return i;
}
LLVMValueRef ctpop(LLVMValueRef[] args)
in(args.length == 1, "Invalid argument count") {
return ctpop(args[0]);
}
LLVMValueRef ctpop(LLVMValueRef n) {
auto bits = LLVMGetIntTypeWidth(LLVMTypeOf(n));
auto fun = getCtpop(bits);
auto t = LLVMGlobalGetValueType(fun);
return LLVMBuildCall2(builder, t, fun, &n, 1, "");
}
auto getCtpop(uint bits) {
import std.conv;
auto name = context.getName("llvm.ctpop.i" ~ to!string(bits));
if (auto fPtr = name in cache) {
return *fPtr;
}
return cache[name] = LLVMAddFunction(dmodule, name.toStringz(context),
getFunctionType(bits));
}
LLVMValueRef ctlz(LLVMValueRef[] args)
in(args.length == 1, "Invalid argument count") {
return ctlz(args[0]);
}
LLVMValueRef ctlz(LLVMValueRef n) {
LLVMValueRef[2] args =
[n, LLVMConstInt(LLVMInt1TypeInContext(llvmCtx), false, false)];
auto bits = LLVMGetIntTypeWidth(LLVMTypeOf(n));
auto fun = getCtlz(bits);
auto t = LLVMGlobalGetValueType(fun);
return LLVMBuildCall2(builder, t, fun, args.ptr, args.length, "");
}
auto getCtlz(uint bits) {
import std.conv;
auto name = context.getName("llvm.ctlz.i" ~ to!string(bits));
if (auto fPtr = name in cache) {
return *fPtr;
}
return cache[name] = LLVMAddFunction(dmodule, name.toStringz(context),
getFunctionTypeWithBool(bits));
}
LLVMValueRef cttz(LLVMValueRef[] args)
in(args.length == 1, "Invalid argument count") {
return cttz(args[0]);
}
LLVMValueRef cttz(LLVMValueRef n) {
LLVMValueRef[2] args =
[n, LLVMConstInt(LLVMInt1TypeInContext(llvmCtx), false, false)];
auto bits = LLVMGetIntTypeWidth(LLVMTypeOf(n));
auto fun = getCttz(bits);
auto t = LLVMGlobalGetValueType(fun);
return LLVMBuildCall2(builder, t, fun, args.ptr, args.length, "");
}
auto getCttz(uint bits) {
import std.conv;
auto name = context.getName("llvm.cttz.i" ~ to!string(bits));
if (auto fPtr = name in cache) {
return *fPtr;
}
return cache[name] = LLVMAddFunction(dmodule, name.toStringz(context),
getFunctionTypeWithBool(bits));
}
LLVMValueRef bswap(LLVMValueRef[] args)
in(args.length == 1, "Invalid argument count") {
return bswap(args[0]);
}
LLVMValueRef bswap(LLVMValueRef n) {
auto bits = LLVMGetIntTypeWidth(LLVMTypeOf(n));
auto fun = getBswap(bits);
auto t = LLVMGlobalGetValueType(fun);
return LLVMBuildCall2(builder, t, fun, &n, 1, "");
}
auto getBswap(uint bits) {
import std.conv;
auto name = context.getName("llvm.bswap.i" ~ to!string(bits));
if (auto fPtr = name in cache) {
return *fPtr;
}
return cache[name] = LLVMAddFunction(dmodule, name.toStringz(context),
getFunctionType(bits));
}
LLVMValueRef readCycleCounter(LLVMValueRef[] args)
in(args.length == 0, "Invalid argument count") {
auto fun = getReadCycleCounter();
auto t = LLVMGlobalGetValueType(fun);
return LLVMBuildCall2(builder, t, fun, null, 0, "");
}
auto getReadCycleCounter() {
auto name = context.getName("llvm.readcyclecounter");
if (auto fPtr = name in cache) {
return *fPtr;
}
auto i64 = LLVMInt64TypeInContext(llvmCtx);
auto type = LLVMFunctionType(i64, null, 0, false);
return cache[name] =
LLVMAddFunction(dmodule, name.toStringz(context), type);
}
private:
auto getFunctionType(uint bits) {
auto t = LLVMIntTypeInContext(llvmCtx, bits);
return LLVMFunctionType(t, &t, 1, false);
}
auto getFunctionTypeWithBool(uint bits) {
auto t = LLVMIntTypeInContext(llvmCtx, bits);
LLVMTypeRef[2] params = [t, LLVMInt1TypeInContext(llvmCtx)];
return LLVMFunctionType(t, params.ptr, params.length, false);
}
}
|
D
|
/Users/mli/Desktop/Develope/Swift/LBE_Demo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/Objects-normal/x86_64/IBarChartDataSet.o : /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Filters/DataApproximator+N.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CombinedChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/ViewPortJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedViewPortJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/MoveViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedMoveViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/ZoomViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedZoomViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/Legend.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/MarkerImage.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/Range.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/ChartLimitLine.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/ChartDataRendererBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/AxisRendererBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/AxisBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/ComponentBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/ChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BarLineChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/PieRadarChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntryBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Animation/ChartAnimationEasing.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Fill.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Platform.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/Description.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/ChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/CombinedChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BubbleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BarLineScatterCandleBubbleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/CandleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/LineChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BarChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/ScatterChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/IMarker.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ViewPortHandler.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Transformer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Renderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LegendRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BarLineScatterCandleBubbleRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/IShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/XShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/CircleShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/TriangleShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/SquareShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronDownShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronUpShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/CrossShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineScatterCandleRadarRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineRadarRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/CombinedChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/PieChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BubbleChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/CandleStickChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/HorizontalBarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/RadarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/ScatterChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/IHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/CombinedHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/PieHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/BarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/HorizontalBarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/RadarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/PieRadarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/ChartHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IndexAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IFillFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultFillFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Animation/Animator.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Filters/DataApproximator.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ChartColorTemplates.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/XAxis.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/YAxis.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ChartUtils.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/ChartBaseDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IPieChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBarLineScatterCandleBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ICandleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineScatterCandleRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineScatterCandleRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IScatterChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/Highlight.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/TransformerHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRendererHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRendererHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRendererRadarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRendererRadarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/MarkerView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/CombinedChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/PieChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BubbleChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/LineChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/CandleStickChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/HorizontalBarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/RadarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/ScatterChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/LegendEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Platform+Accessibility.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/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Target\ Support\ Files/Charts/Charts-umbrella.h /Users/mli/Desktop/Develope/VLogVideo/Pods/Headers/Public/RxAtomic/RxAtomic.modulemap /Users/mli/Desktop/Develope/Swift/LBE_Demo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/unextended-module.modulemap /Users/mli/Desktop/Develope/VLogVideo/Pods/Headers/Public/RxSwift/RxSwift.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/mli/Desktop/Develope/Swift/LBE_Demo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/Objects-normal/x86_64/IBarChartDataSet~partial.swiftmodule : /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Filters/DataApproximator+N.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CombinedChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/ViewPortJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedViewPortJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/MoveViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedMoveViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/ZoomViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedZoomViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/Legend.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/MarkerImage.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/Range.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/ChartLimitLine.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/ChartDataRendererBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/AxisRendererBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/AxisBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/ComponentBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/ChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BarLineChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/PieRadarChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntryBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Animation/ChartAnimationEasing.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Fill.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Platform.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/Description.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/ChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/CombinedChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BubbleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BarLineScatterCandleBubbleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/CandleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/LineChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BarChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/ScatterChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/IMarker.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ViewPortHandler.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Transformer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Renderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LegendRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BarLineScatterCandleBubbleRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/IShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/XShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/CircleShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/TriangleShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/SquareShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronDownShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronUpShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/CrossShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineScatterCandleRadarRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineRadarRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/CombinedChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/PieChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BubbleChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/CandleStickChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/HorizontalBarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/RadarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/ScatterChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/IHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/CombinedHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/PieHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/BarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/HorizontalBarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/RadarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/PieRadarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/ChartHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IndexAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IFillFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultFillFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Animation/Animator.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Filters/DataApproximator.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ChartColorTemplates.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/XAxis.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/YAxis.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ChartUtils.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/ChartBaseDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IPieChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBarLineScatterCandleBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ICandleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineScatterCandleRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineScatterCandleRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IScatterChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/Highlight.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/TransformerHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRendererHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRendererHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRendererRadarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRendererRadarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/MarkerView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/CombinedChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/PieChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BubbleChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/LineChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/CandleStickChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/HorizontalBarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/RadarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/ScatterChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/LegendEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Platform+Accessibility.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/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Target\ Support\ Files/Charts/Charts-umbrella.h /Users/mli/Desktop/Develope/VLogVideo/Pods/Headers/Public/RxAtomic/RxAtomic.modulemap /Users/mli/Desktop/Develope/Swift/LBE_Demo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/unextended-module.modulemap /Users/mli/Desktop/Develope/VLogVideo/Pods/Headers/Public/RxSwift/RxSwift.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/mli/Desktop/Develope/Swift/LBE_Demo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/Objects-normal/x86_64/IBarChartDataSet~partial.swiftdoc : /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Filters/DataApproximator+N.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CombinedChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/ViewPortJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedViewPortJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/MoveViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedMoveViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/ZoomViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedZoomViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/Legend.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/MarkerImage.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/Range.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/ChartLimitLine.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/ChartDataRendererBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/AxisRendererBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/AxisBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/ComponentBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/ChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BarLineChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/PieRadarChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntryBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Animation/ChartAnimationEasing.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Fill.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Platform.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/Description.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/ChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/CombinedChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BubbleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BarLineScatterCandleBubbleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/CandleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/LineChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BarChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/ScatterChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/IMarker.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ViewPortHandler.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Transformer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Renderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LegendRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BarLineScatterCandleBubbleRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/IShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/XShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/CircleShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/TriangleShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/SquareShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronDownShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronUpShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/CrossShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineScatterCandleRadarRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineRadarRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/CombinedChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/PieChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BubbleChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/CandleStickChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/HorizontalBarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/RadarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/ScatterChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/IHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/CombinedHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/PieHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/BarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/HorizontalBarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/RadarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/PieRadarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/ChartHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IndexAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IFillFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultFillFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Animation/Animator.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Filters/DataApproximator.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ChartColorTemplates.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/XAxis.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/YAxis.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ChartUtils.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/ChartBaseDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IPieChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBarLineScatterCandleBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ICandleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineScatterCandleRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineScatterCandleRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IScatterChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/Highlight.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/TransformerHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRendererHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRendererHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRendererRadarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRendererRadarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/MarkerView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/CombinedChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/PieChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BubbleChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/LineChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/CandleStickChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/HorizontalBarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/RadarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/ScatterChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/LegendEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Platform+Accessibility.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/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Target\ Support\ Files/Charts/Charts-umbrella.h /Users/mli/Desktop/Develope/VLogVideo/Pods/Headers/Public/RxAtomic/RxAtomic.modulemap /Users/mli/Desktop/Develope/Swift/LBE_Demo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/unextended-module.modulemap /Users/mli/Desktop/Develope/VLogVideo/Pods/Headers/Public/RxSwift/RxSwift.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
|
D
|
module java.lang.util;
public import java.lang.wrappers;
public import java.lang.String;
public import java.lang.interfaces;
version(Tango){
static import tango.text.convert.Format;
static import tango.core.Exception;
static import tango.util.log.Log;
static import tango.util.log.Config;
static import tango.stdc.stdlib;
alias tango.stdc.stdlib.exit exit;
} else { // Phobos
static import core.exception;
static import std.c.stdlib;
static import std.stdio;
static import std.ascii;
static import std.array;
static import std.format;
static import std.typetuple;
static import std.traits;
static import std.exception;
alias std.c.stdlib.exit exit;
}
interface IDwtLogger {
void trace( String file, ulong line, String fmt, ... );
void info( String file, ulong line, String fmt, ... );
void warn( String file, ulong line, String fmt, ... );
void error( String file, ulong line, String fmt, ... );
void fatal( String file, ulong line, String fmt, ... );
}
version(Tango){
class DwtLogger : IDwtLogger {
tango.util.log.Log.Logger logger;
private this( char[] name ){
logger = tango.util.log.Log.Log.lookup( name );
}
private char[] format( String file, ulong line, String fmt, TypeInfo[] types, void* argptr ){
auto msg = Format.convert( types, argptr, fmt );
auto text = Format( "{} {}: {}", file, line, msg );
return text;
}
void trace( String file, ulong line, String fmt, ... ){
if( logger.trace ){
logger.trace( format( file, line, fmt, _arguments, _argptr ));
}
}
void info( String file, ulong line, String fmt, ... ){
if( logger.info ){
logger.info( format( file, line, fmt, _arguments, _argptr ));
}
}
void warn( String file, ulong line, String fmt, ... ){
if( logger.warn ){
logger.warn( format( file, line, fmt, _arguments, _argptr ));
}
}
void error( String file, ulong line, String fmt, ... ){
if( logger.error ){
logger.error( format( file, line, fmt, _arguments, _argptr ));
}
}
void fatal( String file, ulong line, String fmt, ... ){
if( logger.fatal ){
logger.fatal( format( file, line, fmt, _arguments, _argptr ));
}
}
}
} else { // Phobos
import core.vararg;
class DwtLogger : IDwtLogger {
private this( String name ) {
}
void trace( String file, ulong line, String fmt, ... ){
fmt = fmtFromTangoFmt(fmt);
std.stdio.writefln( "TRC %s %s: %s", file, line, doVarArgFormat(typeid(fmt) ~ _arguments, cast(core.vararg.va_list)&fmt) );
}
void info( String file, ulong line, String fmt, ... ){
fmt = fmtFromTangoFmt(fmt);
std.stdio.writefln( "INF %s %s: %s", file, line, doVarArgFormat(typeid(fmt) ~ _arguments, cast(core.vararg.va_list)&fmt) );
}
void warn( String file, ulong line, String fmt, ... ){
fmt = fmtFromTangoFmt(fmt);
std.stdio.writefln( "WRN %s %s: %s", file, line, doVarArgFormat(typeid(fmt) ~ _arguments, cast(core.vararg.va_list)&fmt) );
}
void error( String file, ulong line, String fmt, ... ){
fmt = fmtFromTangoFmt(fmt);
std.stdio.writefln( "ERR %s %s: %s", file, line, doVarArgFormat(typeid(fmt) ~ _arguments, cast(core.vararg.va_list)&fmt) );
}
void fatal( String file, ulong line, String fmt, ... ){
fmt = fmtFromTangoFmt(fmt);
std.stdio.writefln( "FAT %s %s: %s", file, line, doVarArgFormat(typeid(fmt) ~ _arguments, cast(core.vararg.va_list)&fmt) );
}
}
}
private DwtLogger dwtLoggerInstance;
IDwtLogger getDwtLogger(){
if( dwtLoggerInstance is null ){
synchronized{
if( dwtLoggerInstance is null ){
dwtLoggerInstance = new DwtLogger( "dwt" );
}
}
}
return dwtLoggerInstance;
}
void implMissing( String file, uint line ){
getDwtLogger().fatal( file, line, "implementation missing in file {} line {}", file, line );
getDwtLogger().fatal( file, line, "Please create a bug report at http://www.dsource.org/projects/dwt" );
throw new core.exception.AssertError("Implementation missing", file, line);
}
void implMissingInTango(T = void)( String file, uint line ) {
version(Tango) {} else static assert(0, "For Tango implMissings only");
getDwtLogger().fatal( file, line, "implementation missing in Tango version" );
implMissing( file, line );
}
void implMissingInPhobos( String file = __FILE__, uint line = __LINE__ )() {
version(Tango) static assert(0, "For Phobos implMissings only");
getDwtLogger().fatal( file, line, "implementation missing in Phobos version" );
implMissing( file, line );
}
version(Tango){
alias implMissing implMissingSafe;
} else { // Phobos
mixin(`@safe nothrow
void implMissingSafe( String file, uint line ) {
// impossible processing
}`);
}
version(Tango){
public alias tango.text.convert.Format.Format Format;
} else { // Phobos
private string fmtFromTangoFmt(string tangoFmt) {
auto app = std.array.appender!(string)();
app.reserve(tangoFmt.length);
L: for(int i = 0; i < tangoFmt.length; ++i) {
char c = tangoFmt[i];
if(c == '%')
app.put("%%");
else if(c == '{') {
if(i + 1 < tangoFmt.length && tangoFmt[i + 1] == '{') {
app.put('{');
++i;
} else {
int j = i;
do {
++j;
if(j == tangoFmt.length) {
app.put("{malformed format}");
break L;
}
} while(tangoFmt[j] != '}');
string f = tangoFmt[i + 1 .. j];
i = j;
if(f.length) {
string fres = "%";
try {
if(std.ascii.isDigit(f[0])) {
int n = std.conv.parse!(int)(f);
fres ~= std.conv.to!(string)(n + 1) ~ '$';
}
if(f.length) {
std.exception.enforce(f[0] == ':' && f.length > 1);
c = f[1];
if(f.length == 2 && "bodxXeEfFgG".indexOf(c) != -1)
fres ~= c;
else
fres = null;
} else
fres ~= 's';
} catch {
fres = "{malformed format}";
}
if(fres)
app.put(fres);
else
implMissingInPhobos();
} else
app.put("%s");
}
} else
app.put(c);
}
return app.data();
}
unittest
{
alias Format Formatter;
// basic layout tests
assert( Formatter( "abc" ) == "abc" );
assert( Formatter( "{0}", 1 ) == "1" );
assert( Formatter( "{0}", -1 ) == "-1" );
assert( Formatter( "{}", 1 ) == "1" );
assert( Formatter( "{} {}", 1, 2) == "1 2" );
// assert( Formatter( "{} {0} {}", 1, 3) == "1 1 3" );
// assert( Formatter( "{} {0} {} {}", 1, 3) == "1 1 3 {invalid index}" );
// assert( Formatter( "{} {0} {} {:x}", 1, 3) == "1 1 3 {invalid index}" );
assert( Formatter( "{0} {0} {1}", 1, 3) == "1 1 3" );
assert( Formatter( "{0} {0} {1} {0}", 1, 3) == "1 1 3 1" );
assert( Formatter( "{0}", true ) == "true" , Formatter( "{0}", true ));
assert( Formatter( "{0}", false ) == "false" );
assert( Formatter( "{0}", cast(byte)-128 ) == "-128" );
assert( Formatter( "{0}", cast(byte)127 ) == "127" );
assert( Formatter( "{0}", cast(ubyte)255 ) == "255" );
assert( Formatter( "{0}", cast(short)-32768 ) == "-32768" );
assert( Formatter( "{0}", cast(short)32767 ) == "32767" );
assert( Formatter( "{0}", cast(ushort)65535 ) == "65535" );
// assert( Formatter( "{0:x4}", cast(ushort)0xafe ) == "0afe" );
// assert( Formatter( "{0:X4}", cast(ushort)0xafe ) == "0AFE" );
assert( Formatter( "{0}", -2147483648 ) == "-2147483648" );
assert( Formatter( "{0}", 2147483647 ) == "2147483647" );
assert( Formatter( "{0}", 4294967295 ) == "4294967295" );
// large integers
assert( Formatter( "{0}", -9223372036854775807L) == "-9223372036854775807" );
assert( Formatter( "{0}", 0x8000_0000_0000_0000L) == "9223372036854775808" );
assert( Formatter( "{0}", 9223372036854775807L ) == "9223372036854775807" );
assert( Formatter( "{0:X}", 0xFFFF_FFFF_FFFF_FFFF) == "FFFFFFFFFFFFFFFF" );
assert( Formatter( "{0:x}", 0xFFFF_FFFF_FFFF_FFFF) == "ffffffffffffffff" );
assert( Formatter( "{0:x}", 0xFFFF_1234_FFFF_FFFF) == "ffff1234ffffffff" );
// assert( Formatter( "{0:x19}", 0x1234_FFFF_FFFF) == "00000001234ffffffff" );
assert( Formatter( "{0}", 18446744073709551615UL ) == "18446744073709551615" );
assert( Formatter( "{0}", 18446744073709551615UL ) == "18446744073709551615" );
// fragments before and after
assert( Formatter( "d{0}d", "s" ) == "dsd" );
assert( Formatter( "d{0}d", "1234567890" ) == "d1234567890d" );
// brace escaping
assert( Formatter( "d{0}d", "<string>" ) == "d<string>d");
assert( Formatter( "d{{0}d", "<string>" ) == "d{0}d");
assert( Formatter( "d{{{0}d", "<string>" ) == "d{<string>d");
assert( Formatter( "d{0}}d", "<string>" ) == "d<string>}d");
// hex conversions, where width indicates leading zeroes
assert( Formatter( "{0:x}", 0xafe0000 ) == "afe0000" );
// assert( Formatter( "{0:x7}", 0xafe0000 ) == "afe0000" );
// assert( Formatter( "{0:x8}", 0xafe0000 ) == "0afe0000" );
// assert( Formatter( "{0:X8}", 0xafe0000 ) == "0AFE0000" );
// assert( Formatter( "{0:X9}", 0xafe0000 ) == "00AFE0000" );
// assert( Formatter( "{0:X13}", 0xafe0000 ) == "000000AFE0000" );
// assert( Formatter( "{0:x13}", 0xafe0000 ) == "000000afe0000" );
// decimal width
// assert( Formatter( "{0:d6}", 123 ) == "000123" );
// assert( Formatter( "{0,7:d6}", 123 ) == " 000123" );
// assert( Formatter( "{0,-7:d6}", 123 ) == "000123 " );
// width & sign combinations
// assert( Formatter( "{0:d7}", -123 ) == "-0000123" );
// assert( Formatter( "{0,7:d6}", 123 ) == " 000123" );
// assert( Formatter( "{0,7:d7}", -123 ) == "-0000123" );
// assert( Formatter( "{0,8:d7}", -123 ) == "-0000123" );
// assert( Formatter( "{0,5:d7}", -123 ) == "-0000123" );
// Negative numbers in various bases
assert( Formatter( "{:b}", cast(byte) -1 ) == "11111111" );
assert( Formatter( "{:b}", cast(short) -1 ) == "1111111111111111" );
assert( Formatter( "{:b}", cast(int) -1 )
== "11111111111111111111111111111111" );
assert( Formatter( "{:b}", cast(long) -1 )
== "1111111111111111111111111111111111111111111111111111111111111111" );
assert( Formatter( "{:o}", cast(byte) -1 ) == "377" );
assert( Formatter( "{:o}", cast(short) -1 ) == "177777" );
assert( Formatter( "{:o}", cast(int) -1 ) == "37777777777" );
assert( Formatter( "{:o}", cast(long) -1 ) == "1777777777777777777777" );
assert( Formatter( "{:d}", cast(byte) -1 ) == "-1" );
assert( Formatter( "{:d}", cast(short) -1 ) == "-1" );
assert( Formatter( "{:d}", cast(int) -1 ) == "-1" );
assert( Formatter( "{:d}", cast(long) -1 ) == "-1" );
assert( Formatter( "{:x}", cast(byte) -1 ) == "ff" );
assert( Formatter( "{:x}", cast(short) -1 ) == "ffff" );
assert( Formatter( "{:x}", cast(int) -1 ) == "ffffffff" );
assert( Formatter( "{:x}", cast(long) -1 ) == "ffffffffffffffff" );
// argument index
assert( Formatter( "a{0}b{1}c{2}", "x", "y", "z" ) == "axbycz" );
assert( Formatter( "a{2}b{1}c{0}", "x", "y", "z" ) == "azbycx" );
assert( Formatter( "a{1}b{1}c{1}", "x", "y", "z" ) == "aybycy" );
// alignment does not restrict the length
// assert( Formatter( "{0,5}", "hellohello" ) == "hellohello" );
// alignment fills with spaces
// assert( Formatter( "->{0,-10}<-", "hello" ) == "->hello <-" );
// assert( Formatter( "->{0,10}<-", "hello" ) == "-> hello<-" );
// assert( Formatter( "->{0,-10}<-", 12345 ) == "->12345 <-" );
// assert( Formatter( "->{0,10}<-", 12345 ) == "-> 12345<-" );
// chop at maximum specified length; insert ellipses when chopped
// assert( Formatter( "->{.5}<-", "hello" ) == "->hello<-" );
// assert( Formatter( "->{.4}<-", "hello" ) == "->hell...<-" );
// assert( Formatter( "->{.-3}<-", "hello" ) == "->...llo<-" );
// width specifier indicates number of decimal places
assert( Formatter( "{0:f}", 1.23f ) == "1.230000" );
// assert( Formatter( "{0:f4}", 1.23456789L ) == "1.2346" );
// assert( Formatter( "{0:e4}", 0.0001) == "1.0000e-04");
assert( Formatter( "{0:f}", 1.23f*1i ) == "1.230000i");
// assert( Formatter( "{0:f4}", 1.23456789L*1i ) == "1.2346*1i" );
// assert( Formatter( "{0:e4}", 0.0001*1i) == "1.0000e-04*1i");
assert( Formatter( "{0:f}", 1.23f+1i ) == "1.230000+1.000000i" );
// assert( Formatter( "{0:f4}", 1.23456789L+1i ) == "1.2346+1.0000*1i" );
// assert( Formatter( "{0:e4}", 0.0001+1i) == "1.0000e-04+1.0000e+00*1i");
assert( Formatter( "{0:f}", 1.23f-1i ) == "1.230000+-1.000000i" );
// assert( Formatter( "{0:f4}", 1.23456789L-1i ) == "1.2346-1.0000*1i" );
// assert( Formatter( "{0:e4}", 0.0001-1i) == "1.0000e-04-1.0000e+00*1i");
// 'f.' & 'e.' format truncates zeroes from floating decimals
// assert( Formatter( "{:f4.}", 1.230 ) == "1.23" );
// assert( Formatter( "{:f6.}", 1.230 ) == "1.23" );
// assert( Formatter( "{:f1.}", 1.230 ) == "1.2" );
// assert( Formatter( "{:f.}", 1.233 ) == "1.23" );
// assert( Formatter( "{:f.}", 1.237 ) == "1.24" );
// assert( Formatter( "{:f.}", 1.000 ) == "1" );
// assert( Formatter( "{:f2.}", 200.001 ) == "200");
// array output
int[] a = [ 51, 52, 53, 54, 55 ];
assert( Formatter( "{}", a ) == "[51, 52, 53, 54, 55]" );
assert( Formatter( "{:x}", a ) == "[33, 34, 35, 36, 37]" );
// assert( Formatter( "{,-4}", a ) == "[51 , 52 , 53 , 54 , 55 ]" );
// assert( Formatter( "{,4}", a ) == "[ 51, 52, 53, 54, 55]" );
int[][] b = [ [ 51, 52 ], [ 53, 54, 55 ] ];
assert( Formatter( "{}", b ) == "[[51, 52], [53, 54, 55]]" );
char[1024] static_buffer;
static_buffer[0..10] = "1234567890";
assert (Formatter( "{}", static_buffer[0..10]) == "1234567890");
version(X86)
{
ushort[3] c = [ cast(ushort)51, 52, 53 ];
assert( Formatter( "{}", c ) == "[51, 52, 53]" );
}
/*// integer AA
ushort[long] d;
d[234] = 2;
d[345] = 3;
assert( Formatter( "{}", d ) == "{234 => 2, 345 => 3}" ||
Formatter( "{}", d ) == "{345 => 3, 234 => 2}");
// bool/string AA
bool[char[]] e;
e[ "key".dup ] = true;
e[ "value".dup ] = false;
assert( Formatter( "{}", e ) == "{key => true, value => false}" ||
Formatter( "{}", e ) == "{value => false, key => true}");
// string/double AA
char[][ double ] f;
f[ 1.0 ] = "one".dup;
f[ 3.14 ] = "PI".dup;
assert( Formatter( "{}", f ) == "{1.00 => one, 3.14 => PI}" ||
Formatter( "{}", f ) == "{3.14 => PI, 1.00 => one}");*/
}
private String doVarArgFormat(TypeInfo[] _arguments, core.vararg.va_list _argptr) {
char[] res;
void putc(dchar c) {
std.utf.encode(res, c);
}
std.format.doFormat(&putc, _arguments, _argptr);
return std.exception.assumeUnique(res);
}
class Format{
template UnTypedef(T) {
static if (is(T U == typedef))
alias std.traits.Unqual!(U) UnTypedef;
else
alias std.traits.Unqual!(T) UnTypedef;
}
static String opCall(A...)( String _fmt, A _args ){
//Formatting a typedef is deprecated
std.typetuple.staticMap!(UnTypedef, A) args;
foreach(i, _a; _args)
static if (is(T U == typedef))
args[i] = cast(U) _a;
else
args[i] = _a;
auto writer = std.array.appender!(String)();
std.format.formattedWrite(writer, fmtFromTangoFmt(_fmt), args);
auto res = writer.data();
return std.exception.assumeUnique(res);
}
}
}
version( D_Version2 ) {
//dmd v2.052 bug: mixin("alias const(Type) Name;"); will be unvisible outside it's module => we should write alias Const!(Type) Name;
template Immutable(T) {
mixin("alias immutable(T) Immutable;");
}
template Const(T) {
mixin("alias const(T) Const;");
}
template Shared(T) {
mixin("alias shared(T) Shared;");
}
alias Immutable TryImmutable;
alias Const TryConst;
alias Shared TryShared;
//e.g. for passing strings to com.ibm.icu: *.text.* modules assepts String,
//but internal *.mangoicu.* modules work with char[] even if they don't modify it
std.traits.Unqual!(T)[] Unqual(T)(T[] t) {
return cast(std.traits.Unqual!(T)[])t;
}
Immutable!(T)[] _idup(T)( T[] str ){ return str.idup; }
template prefixedIfD2(String prefix, String content) {
const prefixedIfD2 = prefix ~ " " ~ content;
}
} else { // D1
template AliasT(T) { alias T AliasT; }
alias AliasT TryImmutable;
alias AliasT TryConst;
alias AliasT TryShared;
T Unqual(T)(T t) { return t; }
String16 _idup( String16 str ){
return str.dup;
}
String _idup( String str ){
return str.dup;
}
template prefixedIfD2(String prefix, String content) {
const prefixedIfD2 = content;
}
}
template sharedStaticThis(String content) {
const sharedStaticThis = prefixedIfD2!("shared", "static this()" ~ content);
}
template sharedStatic_This(String content) {
const sharedStatic_This = prefixedIfD2!("shared", "private static void static_this()" ~ content);
}
template gshared(String content) {
const gshared = prefixedIfD2!("__gshared:", content);
}
template constFuncs(String content) {
const constFuncs = prefixedIfD2!("const:", content);
}
private struct GCStats {
size_t poolsize; // total size of pool
size_t usedsize; // bytes allocated
size_t freeblocks; // number of blocks marked FREE
size_t freelistsize; // total of memory on free lists
size_t pageblocks; // number of blocks marked PAGE
}
private extern(C) GCStats gc_stats();
size_t RuntimeTotalMemory(){
GCStats s = gc_stats();
return s.poolsize;
}
template arraycast(T) {
T[] arraycast(U) (U[] u) {
static if (
(is (T == interface ) && is (U == interface )) ||
(is (T == class ) && is (U == class ))) {
return(cast(T[])u);
}
else {
int l = u.length;
T[] res;
res.length = l;
for (int i = 0; i < l; i++) {
res[i] = cast(T)u[i];
}
return(res);
}
}
}
bool ArrayEquals(T)( T[] a, T[] b ){
if( a.length !is b.length ){
return false;
}
for( int i = 0; i < a.length; i++ ){
static if( is( T==class) || is(T==interface)){
if( a[i] !is null && b[i] !is null ){
if( a[i] != b[i] ){
return false;
}
}
else if( a[i] is null && b[i] is null ){
}
else{
return false;
}
}
else{
if( a[i] != b[i] ){
return false;
}
}
}
return true;
}
int arrayIndexOf(T)( T[] arr, T v ){
int res = -1;
int idx = 0;
static if (is(T == interface))
{
Object[] array = cast(Object[]) arr;
Object value = cast(Object) v;
}
else
{
auto array = arr;
auto value = v;
}
foreach( p; array ){
if( p == value){
res = idx;
break;
}
idx++;
}
return res;
}
T[] arrayIndexRemove(T)(T[] arr, uint n) {
if (n is 0)
return arr[1..$];
if (n > arr.length)
return arr;
if (n is arr.length-1)
return arr[0..n-1];
// else
return arr[0..n] ~ arr[n+1..$];
}
struct ImportData{
TryImmutable!(void)[] data;
String name;
//empty () is just a hack to force opCall to be included in full in the .di file
public static ImportData opCall()( TryImmutable!(void)[] data, String name ){
ImportData res;
res.data = data;
res.name = name;
return res;
}
}
template getImportData(String name) {
const ImportData getImportData = ImportData( cast(TryImmutable!(void)[]) import(name), name );
}
|
D
|
/Users/developer/Documents/GitRepo/forks/sift-ios/.build/x86_64-apple-macosx/debug/sift_ios.build/sift_ios.swift.o : /Users/developer/Documents/GitRepo/forks/sift-ios/Sources/sift-ios/sift_ios.swift /Users/developer/Documents/GitRepo/forks/sift-ios/.build/x86_64-apple-macosx/debug/sift_ios.build/module.modulemap
/Users/developer/Documents/GitRepo/forks/sift-ios/.build/x86_64-apple-macosx/debug/sift_ios.build/sift_ios~partial.swiftmodule : /Users/developer/Documents/GitRepo/forks/sift-ios/Sources/sift-ios/sift_ios.swift /Users/developer/Documents/GitRepo/forks/sift-ios/.build/x86_64-apple-macosx/debug/sift_ios.build/module.modulemap
/Users/developer/Documents/GitRepo/forks/sift-ios/.build/x86_64-apple-macosx/debug/sift_ios.build/sift_ios~partial.swiftdoc : /Users/developer/Documents/GitRepo/forks/sift-ios/Sources/sift-ios/sift_ios.swift /Users/developer/Documents/GitRepo/forks/sift-ios/.build/x86_64-apple-macosx/debug/sift_ios.build/module.modulemap
/Users/developer/Documents/GitRepo/forks/sift-ios/.build/x86_64-apple-macosx/debug/sift_ios.build/sift_ios~partial.swiftsourceinfo : /Users/developer/Documents/GitRepo/forks/sift-ios/Sources/sift-ios/sift_ios.swift /Users/developer/Documents/GitRepo/forks/sift-ios/.build/x86_64-apple-macosx/debug/sift_ios.build/module.modulemap
|
D
|
/*******************************************************************************
Abstract base class for DLS node step-by-step iterators. An iterator
class must be implemented for each storage engine.
A step iterator is distinguished from an opApply style iterator in that it
has explicit methods to get the current key / value, and to advance the
iterator to the next key. This type of iterator is essential for an
asynchronous storage engine, as multiple iterations could be occurring in
parallel (asynchronously), and each one needs to be able to remember its own
state (ie which record it's up to, and which is next). This class provides
the interface for that kind of iterator.
This abstract iterator class has no methods to begin an iteration. As
various different types of iteration are possible, it is left to derived
classes to implement suitable methods to start iterations.
copyright:
Copyright (c) 2011-2017 dunnhumby Germany GmbH. All rights reserved
License:
Boost Software License Version 1.0. See LICENSE.txt for details.
*******************************************************************************/
module dlsnode.storage.iterator.model.IStorageEngineStepIterator;
import dlsnode.util.aio.JobNotification;
import ocean.transition;
interface IStorageEngineStepIterator
{
/***************************************************************************
Initialises the iterator to iterate over all records in the
storage engine. The first key is queued up, ready to be fetched
with the methods below.
Params:
suspended_job = JobNotification instance to block the caller on.
***************************************************************************/
public void getAll ( JobNotification suspended_job );
/***************************************************************************
Initialises the iterator to iterate over all records in the
storage engine within the specified range of keys. The first key
in the specified range is queued up, ready to be fetched with
the methods below.
Params:
suspended_job = JobNotification instance to block the caller on.
min = string containing the hexadecimal key of the first
record to iterate
max = string containing the hexadecimal key of the last
record to iterate
***************************************************************************/
public void getRange ( JobNotification suspended_job, cstring min, cstring max );
/***************************************************************************
Gets the key of the current record the iterator is pointing to.
Returns:
current key
***************************************************************************/
public cstring key ( );
/***************************************************************************
Gets the value of the current record the iterator is pointing
to.
Params:
event = JobNotification to block the fiber on until read is completed
Returns:
current value
***************************************************************************/
public cstring value ( JobNotification suspended_job );
/***************************************************************************
Advances the iterator to the next record or to the first record in
the storage engine, if this.started is false.
Params:
event = JobNotification to block the fiber on until read is completed
***************************************************************************/
public void next ( JobNotification suspended_job );
/***************************************************************************
Tells whether the current record pointed to by the iterator is the last
in the iteration.
This method may be overridden, but the default definition of the
iteration end is that the current key is empty.
Returns:
true if the current record is the last in the iteration
***************************************************************************/
public bool lastKey ( );
/***************************************************************************
Aborts the current iteration. Causes lastKey() (the usual condition
which is checked to indicate the end of the iteration) to always return
true, until the iteration is restarted.
***************************************************************************/
public void abort ( );
}
|
D
|
module util;
import std.conv;
import std.range;
import std.algorithm;
import std.functional;
import std.traits;
import std.stdio;
public import util.LookaheadRange;
public import util.ResetRange;
public import util.visit;
public import util.meta;
/* Utility Functions */
public auto ariaticMap(alias fn, R)(auto ref R range)
if(isCallable!fn)
{
return range.chunk!(arity!fn).map!(x => fn(x.expand));
}
public auto chunk(size_t n, R)(auto ref R range)
{
import std.typecons;
import std.meta : Repeat;
alias TupleType = Tuple!(Repeat!(n, ElementType!R));
/* string mixins, amirite? */
mixin("return range.chunks(n).map!(x => TupleType(" ~ expandArray!("x", n) ~ "));");
}
unittest
{
auto testRange = [1, 2, 3, 4];
int plus(int a, int b)
{
return a + b;
}
import std.stdio;
assert(testRange.ariaticMap!plus.array == [3, 7]);
}
/* evaluate pred with the front of range and the value as arguments,
* throwing an instance of E on failure, and popping and returning the
* front of the range on success */
public auto matchOn(
alias pred = (x, y) => x == y,
Err = Exception,
R,
E)(auto ref R range, auto ref E elem)
if(isInputRange!R)
{
import std.string;
enforce(!range.empty, "empty range, could not match");
if(!pred(range.front, elem)){
throw new Err("mismatch: expected %s, got %s".format(elem, range.front));
}
return range.popNext;
}
/* pops a value and returns it */
auto ref popNext(R)(auto ref R range)
if(isInputRange!R)
{
import std.exception;
import std.stdio;
enforce(!range.empty, "unable to popNext from emtpy range");
auto ret = range.front;
range.popFront;
return ret;
}
auto fastCast(T, F)(auto ref F f)
// if(is(F == class) && is(T == class))
{
return *cast(T*)&f;
}
/* Creates Json-like strings */
mixin template fancyToString(alias conv = to!string)
{
import std.string;
import std.range;
import std.algorithm;
import std.traits;
alias thisType = Unqual!(typeof(this));
enum toStringBody = `
{
auto s = Unqual!(typeof(this)).stringof ~ " { ";
alias fields = FieldNameTuple!(typeof(this));
foreach(field; fields){
alias valueType = Unqual!(typeof(mixin("this." ~ field)));
auto fieldVal = mixin(field);
static if(is(valueType == string)){
s ~= "%s: \"%s\"".format(field, conv(fieldVal));
}else{
s ~= "%s: %s".format(field, conv(fieldVal));
}
s ~= " ";
}
s ~= "}";
return s;
}
`;
static if(is(thisType == class)){
mixin("override string toString() const" ~ toStringBody);
}else{
mixin("string toString() const" ~ toStringBody);
}
};
/* Create a struct-like class
* this entails a static constructor
* (not requiring new), as well as
* a constructor that initializes
* all members */
mixin template classStruct()
{
import std.meta;
import std.traits;
alias ThisType = typeof(this);
alias FieldTypes = Fields!ThisType;
alias FieldNames = FieldNameTuple!ThisType;
this(inout(FieldTypes) args)
{
foreach(i, x; FieldNames){
mixin("this." ~ x ~ " = args[i];");
}
}
mixin fancyToString;
mixin simpleConstructor;
}
/* Dont need a 'new' to create a class
* e.g struct allocation, but for classes */
mixin template simpleConstructor()
{
import std.algorithm;
alias ThisType = typeof(this);
static auto opCall(Args...)(in inout(Args) args)
{
return new ThisType(args);
}
};
|
D
|
/*****************************************************************************
* Solver of Quadratic equations
*
* Authors: 新井 浩平 (Kohei ARAI), arai-kohei-xg@ynu.jp
* Version: 1.0
*****************************************************************************/
module mathematic.equations;
import std.math;
import std.complex;
import std.traits: isFloatingPoint;
import numeric.pseudocmplx: isComplex;
/*************************************************************
* y= ax^2 +bx +c
*************************************************************/
enum SolutionType: ubyte{OneR, RepeatedR, TwoR, OneC, RepeatedC, TwoC}
class QuadraticEq(T, real threshold) if(isFloatingPoint!T || isComplex!T){
import std.traits: TemplateArgsOf;
import numeric.pseudocmplx: BaseRealType;
static if(isFloatingPoint!T){
alias CT= Complex!T;
}
else{
alias CT= T;
}
alias BT= BaseRealType!T;
enum BT MAX_DIFF_ABS= cast(BT)threshold;
this(in T a, in T b, in T c) @safe pure nothrow @nogc{
import numeric.approx: approxEqualZero;
coeff[2]= a;
coeff[1]= b;
coeff[0]= c;
if(approxEqualZero!(T, MAX_DIFF_ABS)(coeff[2])){ // a=0
static if(is(T == BT)) sol_typ= SolutionType.OneR;
else sol_typ= SolutionType.OneC;
}
else{
T d= discriminant;
static if(is(T == BT)){
if(approxEqualZero!(BT, MAX_DIFF_ABS)(d)) sol_typ= SolutionType.RepeatedR;
else if(d > 0.0) sol_typ= SolutionType.TwoR;
else sol_typ= SolutionType.TwoC;
}
else{
if(approxEqualZero!(CT, MAX_DIFF_ABS)(d)) sol_typ= SolutionType.RepeatedC;
else sol_typ= SolutionType.TwoC;
}
}
}
@safe pure nothrow @nogc const{
T value(in T x){return coeff[2]*x^^2 +coeff[1]*x +coeff[0];}
CT[2] solve() @property{
typeof(return) result= void;
final switch(sol_typ){
case SolutionType.OneR, SolutionType.OneC:
static if(is(T == BT)) result[0]= complex(-coeff[0]/coeff[1]);
else result[0]= -coeff[0]/coeff[1];
result[1]= complex(BT.nan, BT.nan);
break;
case SolutionType.RepeatedR, SolutionType.RepeatedC:
static if(is(T == BT)) result[0]= complex!BT(-0.5*coeff[1]/coeff[2]);
else result[0]= -0.5*coeff[1]/coeff[2];
result[1]= result[0];
break;
case SolutionType.TwoR:
static if(is(T == BT)){
immutable string eq0= "0.5*(-coeff[1] ", eq1= "d_sqrt)/coeff[2]";
T d_sqrt= sqrt(discriminant);
mixin("result[0]= complex!BT(" ~eq0 ~"-" ~eq1 ~");");
mixin("result[1]= complex!BT(" ~eq0 ~"+" ~eq1 ~");");
}
else assert(0);
break;
case SolutionType.TwoC:
static if(is(T == BT)){
BT d_sqrt= sqrt(-discriminant); // std.math.sqrt
result[0]= complex!(BT, BT)(-coeff[1], -d_sqrt);
result[1]= complex!(BT, BT)(-coeff[1], d_sqrt);
foreach(ref num; result) num /= 2.0*coeff[2];
}
else{
immutable string eq0= "0.5*(-coeff[1] ", eq1= "d_sqrt)/coeff[2];";
CT d_sqrt= sqrt(discriminant); // std.complex.sqrt
mixin("result[0]= " ~eq0 ~"-" ~eq1);
mixin("result[1]= " ~eq0 ~"+" ~eq1);
}
}
return result;
}
}
private:
T discriminant() @safe pure nothrow @nogc @property const{
return coeff[1]^^2 -4.0*coeff[2]*coeff[0];
}
T[3] coeff;
SolutionType sol_typ;
}
//@safe pure nothrow
unittest{
Test_R: {
Complex!double[2] result= void;
QuadraticEq!double eq;
import std.math: sqrt, approxEqual;
// P(x)= x^2-1/2x-5/2
eq= new QuadraticEq!double(1.0, -0.5, -2.5);
result= eq.solve;
assert(approxEqual(result[0].re, 0.25-sqrt(41.0)/4.0) &&
approxEqual(result[1].re, 0.25+sqrt(41.0)/4.0));
// P(x)= x^2-2\sqrt{2}x +2
eq= new QuadraticEq!double(1.0, -2.0*sqrt(2.0), 2.0);
result= eq.solve;
assert(approxEqual(result[0].re, sqrt(2.0)) && result[0].im == 0.0 &&
result[1] == result[0]);
// P(x)= 2x^2 +3x +4
eq= new QuadraticEq!double(2.0, 3.0, 4.0);
result= eq.solve;
assert(approxEqual(result[0].re, -3.0/4.0) && approxEqual(result[0].im, -sqrt(23.0)/4.0));
assert(approxEqual(result[1].re, -3.0/4.0) && approxEqual(result[1].im, sqrt(23.0)/4.0));
}
Test_C: {
// P(z)= (1+i)z^2 +(-2+i)z +(-1+2i)
Complex!double[2] results;
Complex!double a, b, c;
a= Complex!double(1.0, 1.0);
b= Complex!double(-2.0, 1.0);
c= Complex!double(-1.0, 2.0);
auto eq= new QuadraticEq!(Complex!double)(a, b, c);
results= eq.solve;
assert(approxEqual(results[0].re, -0.5) && approxEqual(results[0].im, 0.5));
assert(approxEqual(results[1].re, 1.0) && approxEqual(results[1].im, -2.0));
}
}
/*************************************************************
* y= ax +b
*************************************************************/
class LinearEq(T) if(isFloatingPoint!T || isComplex!T){
this(in T a, in T b) @safe pure nothrow @nogc{
coeff[0]= b;
coeff[1]= a;
}
@safe pure nothrow @nogc const{
T value(in T x){return coeff[1]*x +coeff[0];}
T solve() @property{return -coeff[0]/coeff[1];}
}
private:
T[2] coeff;
}
|
D
|
module ui.ProgressBar;
import ui.Control;
class ProgressBar : Control {
protected uiProgressBar* _progressBar;
this() {
_progressBar = uiNewProgressBar();
super(cast(uiControl*) _progressBar);
}
int value() {
return uiProgressBarValue(_progressBar);
}
ProgressBar setValue(int value) {
uiProgressBarSetValue(_progressBar, value);
return this;
}
}
|
D
|
module collision;
public import collision.collision;
public import collision.hitbox;
import gfm.math;
package nothrow pure @nogc box2i normalize_aabb(box2f aabb, vec2f stepv) {
auto min = aabb.min / stepv;
auto max = aabb.max / stepv;
return box2i(
vec2i(cast(int)min.x, cast(int)min.y),
vec2i(cast(int)max.x+1, cast(int)max.y+1)
);
}
class CollisionRange {
import dioni.opaque;
bool empty() { return true; }
dioniParticle* front() { return null; }
void popFront() { }
}
|
D
|
module kerisy.controller;
public import kerisy.controller.Controller;
public import kerisy.controller.RestController;
|
D
|
module UnrealScript.TribesGame.TrDevice_PlasmaGun;
import ScriptClasses;
import UnrealScript.Helpers;
import UnrealScript.TribesGame.TrDevice_ConstantFire;
extern(C++) interface TrDevice_PlasmaGun : TrDevice_ConstantFire
{
public extern(D):
private static __gshared ScriptClass mStaticClass;
@property final static ScriptClass StaticClass() { mixin(MGSCC("Class TribesGame.TrDevice_PlasmaGun")); }
private static __gshared TrDevice_PlasmaGun mDefaultProperties;
@property final static TrDevice_PlasmaGun DefaultProperties() { mixin(MGDPC("TrDevice_PlasmaGun", "TrDevice_PlasmaGun TribesGame.Default__TrDevice_PlasmaGun")); }
}
|
D
|
module wx.ListBox;
public import wx.common;
public import wx.Control;
public import wx.ClientData;
//---------------------------------------------------------------------
extern(D) class ЛистБокс : Контрол
{
enum
{
СОРТИРУЕМЫЙ = 0x0010,
ЕДИНИЧНЫЙ = 0x0020,
МНОЖЕСТВЕННЫЙ = 0x0040,
РАСШИРЕННЫЙ = 0x0080,
wxLB_OWNERDRAW = 0x0100,
wxLB_NEED_SB = 0x0200,
wxLB_ALWAYS_SB = 0x0400,
ГПРОКРУТКА = ГПРОКРУТ,
ЦЕЛ_ВЫСОТА = 0x0800,
}
public const ткст СтрИмениЛистБокса = "listBox";
public this(ЦелУкз вхобъ);
public this();
public this(Окно родитель, цел ид, Точка поз = ДЕФПОЗ, Размер размер = ДЕФРАЗМ,
ткст[] выборы = пусто, цел стиль = 0, Оценщик оценщик =пусто, ткст имя = СтрИмениЛистБокса);
//public static ВизОбъект Нов(ЦелУкз вхобъ);
public this(Окно родитель, Точка поз = ДЕФПОЗ, Размер размер = ДЕФРАЗМ,
ткст[] выборы = пусто, цел стиль = 0, Оценщик оценщик = пусто, ткст имя = СтрИмениЛистБокса);
public бул создай(Окно родитель, цел ид, inout Точка поз, inout Размер размер, цел ч,
ткст[] выборы, цел стиль, Оценщик оценщик, ткст имя);
public цел выделение();
public проц выделение(цел значение);
public ткст выделениеТекста();
public проц выделениеТекста(ткст значение);
public проц устВыделение(цел ч, бул селект);
public проц устВыделение(ткст элт, бул селект);
public проц очисть();
public ткст дайТкст(цел ч);
public проц устТкст(цел ч, ткст стр);
public проц добавь(ткст элт);
public проц добавь(ткст элт, ДанныеКлиента данные);
public проц удали(цел ч);
public проц вставь(ткст элт, цел поз);
public проц вставь(ткст элт, цел поз, ДанныеКлиента данные);
public проц вставьЭлементы(ткст[] элты, цел поз);
public проц установи(ткст[] элты, ДанныеКлиента данные);
public проц установи(ткст[] элты);
public бул выделен(цел ч);
public бул сортирован();
public бул соМножественнымВыделением();
public проц деселектируй(цел ч);
public проц деселектируйВсе(цел элтОставляемыйВыделенным);
public цел[] выделения();
public проц устПервЭлт(цел ч);
public проц устПервЭлт(ткст т);
public проц команда(Событие соб);
public цел счёт();
public проц Select_Add(ДатчикСобытий значение);
public проц Select_Remove(ДатчикСобытий значение);
public проц добавьДНажатие(ДатчикСобытий значение);
public проц удалиДНажатие(ДатчикСобытий значение);
}
//---------------------------------------------------------------------
extern(D) class ЧекЛистБокс : ЛистБокс
{
const ткст СтрИмениЛистБокса = "listBox";
public this(ЦелУкз вхобъ);
public this();
public this(Окно родитель, цел ид, Точка поз = ДЕФПОЗ, Размер размер = ДЕФРАЗМ, ткст[] выборы = пусто, цел стиль = 0, Оценщик оценщик = пусто, ткст имя = СтрИмениЛистБокса);
public this(Окно родитель, Точка поз = ДЕФПОЗ, Размер размер = ДЕФРАЗМ, ткст[] выборы = пусто, цел стиль = 0, Оценщик оценщик = пусто, ткст имя = СтрИмениЛистБокса);
public бул отмечен(цел индекс);
public проц отметь(цел индекс);
public проц отметь(цел индекс, бул чекать);
version(__МАК__) {}
else
public цел высотаЭлта();
public проц Checked_Add(ДатчикСобытий значение);
public проц Checked_Remove(ДатчикСобытий значение);
}
//-------------------------------------------------------------------
|
D
|
/Users/mu/Hello/.build/x86_64-apple-macosx/debug/Vapor.build/Content/JSONCoder+Custom.swift.o : /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Utilities/FileIO.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/FormDataCoder+HTTP.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/SessionData.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Utilities/Thread.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/URLEncoded.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Deprecated.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Commands/ServeCommand.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Commands/RoutesCommand.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Commands/BootCommand.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+Method.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/SessionCache.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/ResponseCodable.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Request/RequestCodable.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+Middleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/Middleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/CORSMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/FileMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/DateMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/ErrorMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/SessionsMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+LazyMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/Response.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Utilities/AnyResponse.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/MiddlewareConfig.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Server/NIOServerConfig.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/SessionsConfig.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/ContentConfig.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Request/HTTPMethod+String.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+Path.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/JSONCoder+Custom.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/Request+Session.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/Session.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Application.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/RouteCollection.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+Function.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Services/VaporProvider.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/Responder.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/BasicResponder.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/ApplicationResponder.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/WebSocket/WebSocketResponder.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/PlaintextEncoder.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/HTTPMessageContainer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/ParametersContainer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/ContentContainer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/QueryContainer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/EngineRouter.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Server/Server.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Server/NIOServer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Server/RunningServer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/WebSocket/WebSocketServer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/WebSocket/NIOWebSocketServer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Error/Error.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Logging/Logger+LogError.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Error/AbortError.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/Sessions.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/KeyedCacheSessions.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/MemorySessions.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/ContentCoders.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Utilities/Exports.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/HTTPStatus.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/Redirect.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/SingleValueGet.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Services/Config+Default.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Commands/CommandConfig+Default.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Services/Services+Default.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Client/Client.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Client/FoundationClient.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/WebSocket/WebSocketClient.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/WebSocket/NIOWebSocketClient.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+Content.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/Content.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Error/Abort.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Request/Request.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/View/Vapor+View.swift /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOHTTP1.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOOpenSSL.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/HTTP.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOTLS.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Command.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Service.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Console.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Logging.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Routing.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Random.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/URLEncodedForm.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Validation.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 /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Crypto.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/WebSocket.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOWebSocket.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 /Users/mu/Hello/.build/x86_64-apple-macosx/debug/DatabaseKit.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/TemplateKit.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Multipart.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOSHA1/include/CNIOSHA1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/asn1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/tls1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dtls1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pkcs12.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl2.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pem2.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl23.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl3.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509v3.h /usr/local/Cellar/libressl/2.8.3/include/openssl/md5.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pkcs7.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509.h /usr/local/Cellar/libressl/2.8.3/include/openssl/sha.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dsa.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ecdsa.h /usr/local/Cellar/libressl/2.8.3/include/openssl/rsa.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOZlib/include/CNIOZlib.h /usr/local/Cellar/libressl/2.8.3/include/openssl/obj_mac.h /usr/local/Cellar/libressl/2.8.3/include/openssl/hmac.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ec.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /usr/local/Cellar/libressl/2.8.3/include/openssl/rand.h /usr/local/Cellar/libressl/2.8.3/include/openssl/conf.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslconf.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dh.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ecdh.h /usr/local/Cellar/libressl/2.8.3/include/openssl/lhash.h /usr/local/Cellar/libressl/2.8.3/include/openssl/stack.h /usr/local/Cellar/libressl/2.8.3/include/openssl/safestack.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl.h /Users/mu/Hello/.build/checkouts/swift-nio-ssl/Sources/CNIOOpenSSL/include/c_nio_openssl.h /Users/mu/Hello/.build/checkouts/crypto/Sources/CCryptoOpenSSL/include/c_crypto_openssl.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pem.h /usr/local/Cellar/libressl/2.8.3/include/openssl/bn.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /usr/local/Cellar/libressl/2.8.3/include/openssl/bio.h /usr/local/Cellar/libressl/2.8.3/include/openssl/crypto.h /usr/local/Cellar/libressl/2.8.3/include/openssl/srtp.h /usr/local/Cellar/libressl/2.8.3/include/openssl/evp.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ossl_typ.h /usr/local/Cellar/libressl/2.8.3/include/openssl/buffer.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include/CNIOHTTPParser.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include/c_nio_http_parser.h /usr/local/Cellar/libressl/2.8.3/include/openssl/err.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslfeatures.h /usr/local/Cellar/libressl/2.8.3/include/openssl/objects.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslv.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509_vfy.h /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/mu/Hello/.build/checkouts/crypto/Sources/CBase32/include/module.modulemap /Users/mu/Hello/.build/checkouts/crypto/Sources/CBcrypt/include/module.modulemap /Users/mu/Hello/.build/checkouts/swift-nio-zlib-support/module.modulemap /Users/mu/Hello/.build/checkouts/swift-nio-ssl-support/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/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.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/mu/Hello/.build/x86_64-apple-macosx/debug/Vapor.build/Content/JSONCoder+Custom~partial.swiftmodule : /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Utilities/FileIO.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/FormDataCoder+HTTP.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/SessionData.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Utilities/Thread.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/URLEncoded.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Deprecated.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Commands/ServeCommand.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Commands/RoutesCommand.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Commands/BootCommand.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+Method.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/SessionCache.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/ResponseCodable.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Request/RequestCodable.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+Middleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/Middleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/CORSMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/FileMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/DateMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/ErrorMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/SessionsMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+LazyMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/Response.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Utilities/AnyResponse.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/MiddlewareConfig.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Server/NIOServerConfig.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/SessionsConfig.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/ContentConfig.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Request/HTTPMethod+String.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+Path.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/JSONCoder+Custom.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/Request+Session.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/Session.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Application.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/RouteCollection.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+Function.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Services/VaporProvider.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/Responder.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/BasicResponder.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/ApplicationResponder.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/WebSocket/WebSocketResponder.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/PlaintextEncoder.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/HTTPMessageContainer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/ParametersContainer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/ContentContainer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/QueryContainer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/EngineRouter.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Server/Server.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Server/NIOServer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Server/RunningServer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/WebSocket/WebSocketServer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/WebSocket/NIOWebSocketServer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Error/Error.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Logging/Logger+LogError.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Error/AbortError.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/Sessions.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/KeyedCacheSessions.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/MemorySessions.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/ContentCoders.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Utilities/Exports.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/HTTPStatus.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/Redirect.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/SingleValueGet.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Services/Config+Default.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Commands/CommandConfig+Default.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Services/Services+Default.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Client/Client.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Client/FoundationClient.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/WebSocket/WebSocketClient.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/WebSocket/NIOWebSocketClient.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+Content.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/Content.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Error/Abort.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Request/Request.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/View/Vapor+View.swift /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOHTTP1.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOOpenSSL.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/HTTP.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOTLS.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Command.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Service.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Console.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Logging.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Routing.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Random.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/URLEncodedForm.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Validation.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 /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Crypto.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/WebSocket.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOWebSocket.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 /Users/mu/Hello/.build/x86_64-apple-macosx/debug/DatabaseKit.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/TemplateKit.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Multipart.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOSHA1/include/CNIOSHA1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/asn1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/tls1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dtls1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pkcs12.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl2.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pem2.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl23.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl3.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509v3.h /usr/local/Cellar/libressl/2.8.3/include/openssl/md5.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pkcs7.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509.h /usr/local/Cellar/libressl/2.8.3/include/openssl/sha.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dsa.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ecdsa.h /usr/local/Cellar/libressl/2.8.3/include/openssl/rsa.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOZlib/include/CNIOZlib.h /usr/local/Cellar/libressl/2.8.3/include/openssl/obj_mac.h /usr/local/Cellar/libressl/2.8.3/include/openssl/hmac.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ec.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /usr/local/Cellar/libressl/2.8.3/include/openssl/rand.h /usr/local/Cellar/libressl/2.8.3/include/openssl/conf.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslconf.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dh.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ecdh.h /usr/local/Cellar/libressl/2.8.3/include/openssl/lhash.h /usr/local/Cellar/libressl/2.8.3/include/openssl/stack.h /usr/local/Cellar/libressl/2.8.3/include/openssl/safestack.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl.h /Users/mu/Hello/.build/checkouts/swift-nio-ssl/Sources/CNIOOpenSSL/include/c_nio_openssl.h /Users/mu/Hello/.build/checkouts/crypto/Sources/CCryptoOpenSSL/include/c_crypto_openssl.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pem.h /usr/local/Cellar/libressl/2.8.3/include/openssl/bn.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /usr/local/Cellar/libressl/2.8.3/include/openssl/bio.h /usr/local/Cellar/libressl/2.8.3/include/openssl/crypto.h /usr/local/Cellar/libressl/2.8.3/include/openssl/srtp.h /usr/local/Cellar/libressl/2.8.3/include/openssl/evp.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ossl_typ.h /usr/local/Cellar/libressl/2.8.3/include/openssl/buffer.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include/CNIOHTTPParser.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include/c_nio_http_parser.h /usr/local/Cellar/libressl/2.8.3/include/openssl/err.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslfeatures.h /usr/local/Cellar/libressl/2.8.3/include/openssl/objects.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslv.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509_vfy.h /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/mu/Hello/.build/checkouts/crypto/Sources/CBase32/include/module.modulemap /Users/mu/Hello/.build/checkouts/crypto/Sources/CBcrypt/include/module.modulemap /Users/mu/Hello/.build/checkouts/swift-nio-zlib-support/module.modulemap /Users/mu/Hello/.build/checkouts/swift-nio-ssl-support/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/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.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/mu/Hello/.build/x86_64-apple-macosx/debug/Vapor.build/Content/JSONCoder+Custom~partial.swiftdoc : /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Utilities/FileIO.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/FormDataCoder+HTTP.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/SessionData.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Utilities/Thread.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/URLEncoded.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Deprecated.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Commands/ServeCommand.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Commands/RoutesCommand.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Commands/BootCommand.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+Method.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/SessionCache.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/ResponseCodable.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Request/RequestCodable.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+Middleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/Middleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/CORSMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/FileMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/DateMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/ErrorMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/SessionsMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+LazyMiddleware.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/Response.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Utilities/AnyResponse.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Middleware/MiddlewareConfig.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Server/NIOServerConfig.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/SessionsConfig.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/ContentConfig.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Request/HTTPMethod+String.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+Path.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/JSONCoder+Custom.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/Request+Session.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/Session.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Application.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/RouteCollection.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+Function.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Services/VaporProvider.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/Responder.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/BasicResponder.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/ApplicationResponder.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/WebSocket/WebSocketResponder.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/PlaintextEncoder.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/HTTPMessageContainer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/ParametersContainer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/ContentContainer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/QueryContainer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/EngineRouter.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Server/Server.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Server/NIOServer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Server/RunningServer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/WebSocket/WebSocketServer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/WebSocket/NIOWebSocketServer.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Error/Error.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Logging/Logger+LogError.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Error/AbortError.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/Sessions.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/KeyedCacheSessions.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Sessions/MemorySessions.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/ContentCoders.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Utilities/Exports.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/HTTPStatus.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Response/Redirect.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/SingleValueGet.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Services/Config+Default.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Commands/CommandConfig+Default.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Services/Services+Default.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Client/Client.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Client/FoundationClient.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/WebSocket/WebSocketClient.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/WebSocket/NIOWebSocketClient.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Routing/Router+Content.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Content/Content.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Error/Abort.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/Request/Request.swift /Users/mu/Hello/.build/checkouts/vapor/Sources/Vapor/View/Vapor+View.swift /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOHTTP1.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOOpenSSL.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/HTTP.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOTLS.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Command.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Service.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Console.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Logging.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Routing.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Random.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/URLEncodedForm.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Validation.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 /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Crypto.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/WebSocket.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/NIOWebSocket.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 /Users/mu/Hello/.build/x86_64-apple-macosx/debug/DatabaseKit.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/TemplateKit.swiftmodule /Users/mu/Hello/.build/x86_64-apple-macosx/debug/Multipart.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOSHA1/include/CNIOSHA1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/asn1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/tls1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dtls1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pkcs12.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl2.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pem2.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl23.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl3.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509v3.h /usr/local/Cellar/libressl/2.8.3/include/openssl/md5.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pkcs7.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509.h /usr/local/Cellar/libressl/2.8.3/include/openssl/sha.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dsa.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ecdsa.h /usr/local/Cellar/libressl/2.8.3/include/openssl/rsa.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOZlib/include/CNIOZlib.h /usr/local/Cellar/libressl/2.8.3/include/openssl/obj_mac.h /usr/local/Cellar/libressl/2.8.3/include/openssl/hmac.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ec.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /usr/local/Cellar/libressl/2.8.3/include/openssl/rand.h /usr/local/Cellar/libressl/2.8.3/include/openssl/conf.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslconf.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dh.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ecdh.h /usr/local/Cellar/libressl/2.8.3/include/openssl/lhash.h /usr/local/Cellar/libressl/2.8.3/include/openssl/stack.h /usr/local/Cellar/libressl/2.8.3/include/openssl/safestack.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl.h /Users/mu/Hello/.build/checkouts/swift-nio-ssl/Sources/CNIOOpenSSL/include/c_nio_openssl.h /Users/mu/Hello/.build/checkouts/crypto/Sources/CCryptoOpenSSL/include/c_crypto_openssl.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pem.h /usr/local/Cellar/libressl/2.8.3/include/openssl/bn.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /usr/local/Cellar/libressl/2.8.3/include/openssl/bio.h /usr/local/Cellar/libressl/2.8.3/include/openssl/crypto.h /usr/local/Cellar/libressl/2.8.3/include/openssl/srtp.h /usr/local/Cellar/libressl/2.8.3/include/openssl/evp.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ossl_typ.h /usr/local/Cellar/libressl/2.8.3/include/openssl/buffer.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include/CNIOHTTPParser.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include/c_nio_http_parser.h /usr/local/Cellar/libressl/2.8.3/include/openssl/err.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslfeatures.h /usr/local/Cellar/libressl/2.8.3/include/openssl/objects.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslv.h /Users/mu/Hello/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509_vfy.h /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/mu/Hello/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/mu/Hello/.build/checkouts/crypto/Sources/CBase32/include/module.modulemap /Users/mu/Hello/.build/checkouts/crypto/Sources/CBcrypt/include/module.modulemap /Users/mu/Hello/.build/checkouts/swift-nio-zlib-support/module.modulemap /Users/mu/Hello/.build/checkouts/swift-nio-ssl-support/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/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.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
|
/mnt/c/Users/zeliwang/hello_world/digital_signature/target/debug/deps/block_padding-7da8e0f59070f12c.rmeta: /home/zeliwang/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/block-padding-0.1.4/src/lib.rs
/mnt/c/Users/zeliwang/hello_world/digital_signature/target/debug/deps/libblock_padding-7da8e0f59070f12c.rlib: /home/zeliwang/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/block-padding-0.1.4/src/lib.rs
/mnt/c/Users/zeliwang/hello_world/digital_signature/target/debug/deps/block_padding-7da8e0f59070f12c.d: /home/zeliwang/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/block-padding-0.1.4/src/lib.rs
/home/zeliwang/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/block-padding-0.1.4/src/lib.rs:
|
D
|
import std.math:floor; //import std.typecons:Nullable;
import gfm.math:vec2i;
import doxel_height_map, height_generator;
interface IHeightProvider
{
int getHeight(int i, int j);
void setOffset(int h);
}
class FlatHeightProvider
{
int height;
this(){}
this(int height){this.height = height;}
int getHeight(int i, int j){return height;}
void setOffset(int h){}
}
class HeightProvider: IHeightProvider
{
private IHeightGenerator generator;
private HeightMap heightMap;
private int offset;
this(IHeightGenerator generator, HeightMap heightMap)
{
this.generator = generator;
this.heightMap = heightMap;
}
this(IHeightGenerator generator, HeightMap heightMap, int offset)
{
this.generator = generator;
this.heightMap = heightMap;
this.offset = offset;
}
void setOffset(int h){offset = h;}
int getHeight(int i, int j)
{
return getGenerate(i, j) + offset;
//return generator.generateHeight(i, j);
}
/// gets the height from heightmap, or generates it if it hasn't been yet.
private int getGenerate(int i, int j)
{
vec2i[int] mapSite = MapSiteCalculator.toMapSite(i, j);
auto container = heightMap.getCreateHeightCellContainer(mapSite);
HeightCell cell = cast(HeightCell)container.getMapCell(mapSite[1]);
if(cell is null)
{
int[mapCellCount] heights;
auto offsetI = (cast(int)floor((cast(float)i)/mapCellWidth))*mapCellWidth;
auto offsetJ = (cast(int)floor((cast(float)j)/mapCellLength))*mapCellLength;
foreach(ii;0..mapCellWidth)
{
foreach(jj;0..mapCellLength)
{
heights[ii + mapCellWidth*jj] = generator.generateHeight(offsetI + ii, offsetJ + jj);
}
}
cell = new HeightCell(container, heights, mapSite[1]);
}
return cell.getHeight(mapSite[0]);
}
unittest{
import testrunner;
class MockHeightProvider: IHeightGenerator
{
int generateHeight(int i, int j){ // 16 | 18
int h = i<0 ? (j<0 ? 15: 16) : (j<0 ? 17: 18); // ---------
return h; // 15 | 17
}
}
beginSuite("height_provider");
runtest("getGenerate(0,0)", delegate void(){
// arrange
auto map = new HeightMap();
auto provider = new HeightProvider(new MockHeightProvider(), map);
// act
provider.getGenerate(0,0);
// assert
auto result = map.getHeightCell([1: cellCenter, 2: cellCenter]);
assert(result !is null);
assertEqual(18, result.getHeight(1,1));
});
runtest("getGenerate(-1,-1)", delegate void(){
// arrange
auto map = new HeightMap();
auto provider = new HeightProvider(new MockHeightProvider(), map);
// act
provider.getGenerate(-1,-1);
// assert
auto result = map.getHeightCell([1: cellCenter-vec2i(1,1), 2: cellCenter]);
assert(result !is null);
assertEqual(15, result.getHeight(1,1));
});
runtest("getGenerate(-1,0)", delegate void(){
// arrange
auto map = new HeightMap();
auto provider = new HeightProvider(new MockHeightProvider(), map);
// act
provider.getGenerate(-1,1);
// assert
auto result = map.getHeightCell([1: cellCenter+vec2i(-1,0), 2: cellCenter]);
assert(result !is null);
assertEqual(16, result.getHeight(1,1));
});
endSuite();
}
}
|
D
|
module yurai.prebuild.views.view_css_main_navigation;
import yurai;
import models;
public final class view_css_main_navigation : View
{
public:
final:
this(IHttpRequest request, IHttpResponse response)
{
super("css_main_navigation", request,response, []);
}
override ViewResult generate(bool processLayout)
{
return generateFinal(processLayout);
}
ViewResult generateModel()
{
return generateFinal(true);
}
override ViewResult generateFinal(bool processLayout)
{
auto maxWidth = "100%";
append(`
.main-navigation {
background-color: rgb(221,254,228) !important;
padding-top: 0;
}
.main-navigation .navbar-brand img {
height: 42px;
width: auto;
}
.main-navigation .navbar-collapse,
.main-navigation .navbar-toggler {
margin-top: 7px;
}
`);
setContentType("text/css");
return finalizeContent(null,processLayout);
}
}
|
D
|
// PERMUTE_ARGS: -g -version=PULL8152
// EXTRA_CPP_SOURCES: extra-files/cppb.cpp
// EXTRA_FILES: extra-files/cppb.h
import core.stdc.stdio;
import core.stdc.stdarg;
import core.stdc.config;
import core.stdc.stdint;
extern (C++)
int foob(int i, int j, int k);
class C
{
extern (C++) int bar(int i, int j, int k)
{
printf("this = %p\n", this);
printf("i = %d\n", i);
printf("j = %d\n", j);
printf("k = %d\n", k);
return 1;
}
}
extern (C++)
int foo(int i, int j, int k)
{
printf("i = %d\n", i);
printf("j = %d\n", j);
printf("k = %d\n", k);
assert(i == 1);
assert(j == 2);
assert(k == 3);
return 1;
}
void test1()
{
foo(1, 2, 3);
auto i = foob(1, 2, 3);
assert(i == 7);
C c = new C();
c.bar(4, 5, 6);
}
/****************************************/
extern (C++) interface D
{
int bar(int i, int j, int k);
}
extern (C++) D getD();
void test2()
{
D d = getD();
int i = d.bar(9,10,11);
assert(i == 8);
}
/****************************************/
extern (C++) int callE(E);
extern (C++) interface E
{
int bar(int i, int j, int k);
}
class F : E
{
extern (C++) int bar(int i, int j, int k)
{
printf("F.bar: i = %d\n", i);
printf("F.bar: j = %d\n", j);
printf("F.bar: k = %d\n", k);
assert(i == 11);
assert(j == 12);
assert(k == 13);
return 8;
}
}
void test3()
{
F f = new F();
int i = callE(f);
assert(i == 8);
}
/****************************************/
extern (C++) void foo4(char* p);
void test4()
{
foo4(null);
}
/****************************************/
extern(C++)
{
struct foo5 { int i; int j; void* p; }
interface bar5{
foo5 getFoo(int i);
}
bar5 newBar();
}
void test5()
{
bar5 b = newBar();
foo5 f = b.getFoo(4);
printf("f.p = %p, b = %p\n", f.p, cast(void*)b);
assert(f.p == cast(void*)b);
}
/****************************************/
extern(C++)
{
struct S6
{
int i;
double d;
}
union S6_2
{
int i;
double d;
}
enum S6_3
{
A, B
}
S6 foo6();
S6_2 foo6_2();
S6_3 foo6_3();
}
extern (C) int foosize6();
void test6()
{
S6 f = foo6();
printf("%d %d\n", foosize6(), S6.sizeof);
assert(foosize6() == S6.sizeof);
version (X86)
{
assert(f.i == 42);
printf("f.d = %g\n", f.d);
assert(f.d == 2.5);
assert(foo6_2().i == 42);
assert(foo6_3() == S6_3.A);
}
}
/****************************************/
extern (C) int foo7();
struct S
{
int i;
long l;
}
void test7()
{
printf("%d %d\n", foo7(), S.sizeof);
assert(foo7() == S.sizeof);
}
/****************************************/
extern (C++) void foo8(const(char)*);
void test8()
{
char c;
foo8(&c);
}
/****************************************/
// https://issues.dlang.org/show_bug.cgi?id=4059
struct elem9 { }
extern(C++) void foobar9(elem9*, elem9*);
void test9()
{
elem9 *a;
foobar9(a, a);
}
/****************************************/
struct A11802;
struct B11802;
extern(C++) class C11802
{
int x;
void fun(A11802*) { x += 2; }
void fun(B11802*) { x *= 2; }
}
extern(C++) class D11802 : C11802
{
override void fun(A11802*) { x += 3; }
override void fun(B11802*) { x *= 3; }
}
extern(C++) void test11802x(D11802);
void test11802()
{
auto x = new D11802();
x.x = 0;
test11802x(x);
assert(x.x == 9);
}
/****************************************/
struct S13956
{
}
extern(C++) void func13956(S13956 arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6);
extern(C++) void check13956(S13956 arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6)
{
assert(arg0 == S13956());
assert(arg1 == 1);
assert(arg2 == 2);
assert(arg3 == 3);
assert(arg4 == 4);
assert(arg5 == 5);
assert(arg6 == 6);
}
void test13956()
{
func13956(S13956(), 1, 2, 3, 4, 5, 6);
}
/****************************************/
// https://issues.dlang.org/show_bug.cgi?id=5148
extern (C++)
{
void foo10(const(char)*, const(char)*);
void foo10(const int, const int);
void foo10(const char, const char);
void foo10(bool, bool);
struct MyStructType { }
void foo10(const MyStructType s, const MyStructType t);
enum MyEnumType { onemember }
void foo10(const MyEnumType s, const MyEnumType t);
}
void test10()
{
char* p;
foo10(p, p);
foo10(1,2);
foo10('c','d');
MyStructType s;
foo10(s,s);
MyEnumType e;
foo10(e,e);
}
/****************************************/
extern (C++, N11.M) { void bar11(); }
extern (C++, A11.B) { extern (C++, C) { void bar(); }}
void test11()
{
bar11();
A11.B.C.bar();
}
/****************************************/
struct Struct10071
{
void *p;
c_long_double r;
}
extern(C++) size_t offset10071();
void test10071()
{
assert(offset10071() == Struct10071.r.offsetof);
}
/****************************************/
char[100] valistbuffer;
extern(C++) void myvprintfx(const(char)* format, va_list va)
{
vsprintf(valistbuffer.ptr, format, va);
}
extern(C++) void myvprintf(const(char)*, va_list);
extern(C++) void myprintf(const(char)* format, ...)
{
va_list ap;
va_start(ap, format);
myvprintf(format, ap);
va_end(ap);
}
void testvalist()
{
myprintf("hello %d", 999);
assert(valistbuffer[0..9] == "hello 999");
}
/****************************************/
// https://issues.dlang.org/show_bug.cgi?id=12825
extern(C++) class C12825
{
uint a = 0x12345678;
}
void test12825()
{
auto c = new C12825();
}
/****************************************/
struct S13955a
{
float a;
double b;
}
struct S13955b
{
double a;
float b;
}
struct S13955c
{
float a;
float b;
}
struct S13955d
{
double a;
double b;
}
extern(C++) void check13955(S13955a a, S13955b b, S13955c c, S13955d d)
{
assert(a.a == 2);
assert(a.b == 4);
assert(b.a == 8);
assert(b.b == 16);
assert(c.a == 32);
assert(c.b == 64);
assert(d.a == 128);
assert(d.b == 256);
}
extern(C++) void func13955(S13955a a, S13955b b, S13955c c, S13955d d);
void test13955()
{
func13955(S13955a(2, 4), S13955b(8, 16), S13955c(32, 64), S13955d(128, 256));
}
/****************************************/
extern(C++) class C13161
{
void dummyfunc();
long val_5;
uint val_9;
}
extern(C++) class Test : C13161
{
uint val_0;
long val_1;
}
extern(C++) size_t getoffset13161();
extern(C++) class C13161a
{
void dummyfunc();
c_long_double val_5;
uint val_9;
}
extern(C++) class Testa : C13161a
{
bool val_0;
}
extern(C++) size_t getoffset13161a();
void test13161()
{
assert(getoffset13161() == Test.val_0.offsetof);
assert(getoffset13161a() == Testa.val_0.offsetof);
}
/****************************************/
version (linux)
{
extern(C++, __gnu_cxx)
{
struct new_allocator(T)
{
alias size_type = size_t;
static if (is(T : char))
void deallocate(T*, size_type) { }
else
void deallocate(T*, size_type);
}
}
}
extern (C++, std)
{
extern (C++, class) struct allocator(T)
{
version (linux)
{
alias size_type = size_t;
void deallocate(T* p, size_type sz)
{ (cast(__gnu_cxx.new_allocator!T*)&this).deallocate(p, sz); }
}
}
class vector(T, A = allocator!T)
{
final void push_back(ref const T);
}
struct char_traits(T)
{
}
// https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_dual_abi.html
version (none)
{
extern (C++, __cxx11)
{
struct basic_string(T, C = char_traits!T, A = allocator!T)
{
}
}
}
else
{
extern (C++, class) struct basic_string(T, C = char_traits!T, A = allocator!T)
{
}
}
struct basic_istream(T, C = char_traits!T)
{
}
struct basic_ostream(T, C = char_traits!T)
{
}
struct basic_iostream(T, C = char_traits!T)
{
}
class exception { }
// https://issues.dlang.org/show_bug.cgi?id=14956
extern(C++, N14956)
{
struct S14956 { }
}
}
extern (C++)
{
version (linux)
{
void foo14(std.vector!(int) p);
void foo14a(std.basic_string!(char) *p);
void foo14b(std.basic_string!(int) *p);
void foo14c(std.basic_istream!(char) *p);
void foo14d(std.basic_ostream!(char) *p);
void foo14e(std.basic_iostream!(char) *p);
void foo14f(std.char_traits!char* x, std.basic_string!char* p, std.basic_string!char* q);
}
}
void test14()
{
version (linux)
{
std.vector!int p;
foo14(p);
foo14a(null);
foo14b(null);
foo14c(null);
foo14d(null);
foo14e(null);
foo14f(null, null, null);
}
}
version (linux)
{
void test14a(std.allocator!int * pa)
{
pa.deallocate(null, 0);
}
void gun(std.vector!int pa)
{
int x = 42;
pa.push_back(x);
}
}
void test13289()
{
assert(f13289_cpp_wchar_t('a') == 'A');
assert(f13289_cpp_wchar_t('B') == 'B');
assert(f13289_d_wchar('c') == 'C');
assert(f13289_d_wchar('D') == 'D');
assert(f13289_d_dchar('e') == 'E');
assert(f13289_d_dchar('F') == 'F');
assert(f13289_cpp_test());
}
extern(C++)
{
bool f13289_cpp_test();
version(Posix)
{
dchar f13289_cpp_wchar_t(dchar);
}
else version(Windows)
{
wchar f13289_cpp_wchar_t(wchar);
}
wchar f13289_d_wchar(wchar ch)
{
if (ch <= 'z' && ch >= 'a')
{
return cast(wchar)(ch - ('a' - 'A'));
}
else
{
return ch;
}
}
dchar f13289_d_dchar(dchar ch)
{
if (ch <= 'z' && ch >= 'a')
{
return ch - ('a' - 'A');
}
else
{
return ch;
}
}
}
/****************************************/
version (CRuntime_Microsoft)
{
version (PULL8152)
{
enum __c_long_double : double;
}
else
{
struct __c_long_double
{
this(double d) { ld = d; }
double ld;
alias ld this;
}
}
alias __c_long_double myld;
}
else
alias c_long_double myld;
extern (C++) myld testld(myld);
void test15()
{
myld ld = 5.0;
ld = testld(ld);
assert(ld == 6.0);
}
/****************************************/
version( Windows )
{
alias int x_long;
alias uint x_ulong;
}
else
{
static if( (void*).sizeof > int.sizeof )
{
alias long x_long;
alias ulong x_ulong;
}
else
{
alias int x_long;
alias uint x_ulong;
}
}
version (PULL8152)
{
enum __c_long : x_long;
enum __c_ulong : x_ulong;
}
else
{
struct __c_long
{
this(x_long d) { ld = d; }
x_long ld;
alias ld this;
}
struct __c_ulong
{
this(x_ulong d) { ld = d; }
x_ulong ld;
alias ld this;
}
}
alias __c_long mylong;
alias __c_ulong myulong;
extern (C++) mylong testl(mylong);
extern (C++) myulong testul(myulong);
void test16()
{
{
mylong ld = 5;
ld = testl(ld);
printf("ld = %lld, mylong.sizeof = %lld\n", cast(long)ld, cast(long)mylong.sizeof);
assert(ld == 5 + mylong.sizeof);
}
{
myulong ld = 5;
ld = testul(ld);
assert(ld == 5 + myulong.sizeof);
}
version (PULL8152)
{
static if (__c_long.sizeof == long.sizeof)
{
static assert(__c_long.max == long.max);
static assert(__c_long.min == long.min);
static assert(__c_long.init == long.init);
static assert(__c_ulong.max == ulong.max);
static assert(__c_ulong.min == ulong.min);
static assert(__c_ulong.init == ulong.init);
__c_long cl = 0;
cl = cl + 1;
long l = cl;
cl = l;
__c_ulong cul = 0;
cul = cul + 1;
ulong ul = cul;
cul = ul;
}
else static if (__c_long.sizeof == int.sizeof)
{
static assert(__c_long.max == int.max);
static assert(__c_long.min == int.min);
static assert(__c_long.init == int.init);
static assert(__c_ulong.max == uint.max);
static assert(__c_ulong.min == uint.min);
static assert(__c_ulong.init == uint.init);
__c_long cl = 0;
cl = cl + 1;
int i = cl;
cl = i;
__c_ulong cul = 0;
cul = cul + 1;
uint u = cul;
cul = u;
}
else
static assert(0);
}
}
/****************************************/
struct S13707
{
void* a;
void* b;
this(void* a, void* b)
{
this.a = a;
this.b = b;
}
}
extern(C++) S13707 func13707();
void test13707()
{
auto p = func13707();
assert(p.a == null);
assert(p.b == null);
}
/****************************************/
struct S13932(int x)
{
int member;
}
extern(C++) void func13932(S13932!(-1) s);
/****************************************/
extern(C++, N13337.M13337)
{
struct S13337{}
void foo13337(S13337 s);
}
/****************************************/
// https://issues.dlang.org/show_bug.cgi?id=14195
struct Delegate1(T) {}
struct Delegate2(T1, T2) {}
template Signature(T)
{
alias Signature = typeof(*(T.init));
}
extern(C++)
{
alias del1_t = Delegate1!(Signature!(void function()));
alias del2_t = Delegate2!(Signature!(int function(float, double)), Signature!(int function(float, double)));
void test14195a(del1_t);
void test14195b(del2_t);
}
void test14195()
{
test14195a(del1_t());
test14195b(del2_t());
}
/****************************************/
// https://issues.dlang.org/show_bug.cgi?id=14200
template Tuple14200(T...)
{
alias Tuple14200 = T;
}
extern(C++) void test14200a(Tuple14200!(int));
extern(C++) void test14200b(float, Tuple14200!(int, double));
void test14200()
{
test14200a(1);
test14200b(1.0f, 1, 1.0);
}
/****************************************/
// https://issues.dlang.org/show_bug.cgi?id=14956
extern(C++) void test14956(S14956 s);
/****************************************/
// check order of overloads in vtable
extern (C++) class Statement {}
extern (C++) class ErrorStatement {}
extern (C++) class PeelStatement {}
extern (C++) class ExpStatement {}
extern (C++) class DtorExpStatement {}
extern (C++) class Visitor
{
public:
int visit(Statement) { return 1; }
int visit(ErrorStatement) { return 2; }
int visit(PeelStatement) { return 3; }
}
extern (C++) class Visitor2 : Visitor
{
int visit2(ExpStatement) { return 4; }
int visit2(DtorExpStatement) { return 5; }
}
extern(C++) bool testVtableCpp(Visitor2 sv);
extern(C++) Visitor2 getVisitor2();
bool testVtableD(Visitor2 sv)
{
Statement s1;
ErrorStatement s2;
PeelStatement s3;
ExpStatement s4;
DtorExpStatement s5;
if (sv.visit(s1) != 1) return false;
if (sv.visit(s2) != 2) return false;
if (sv.visit(s3) != 3) return false;
if (sv.visit2(s4) != 4) return false;
if (sv.visit2(s5) != 5) return false;
return true;
}
void testVtable()
{
Visitor2 dinst = new Visitor2;
if (!testVtableCpp(dinst))
assert(0);
Visitor2 cppinst = getVisitor2();
if (!testVtableD(cppinst))
assert(0);
}
/****************************************/
/* problems detected by fuzzer */
extern(C++) void fuzz1_cppvararg(int64_t arg10, int64_t arg11, bool arg12);
extern(C++) void fuzz1_dvararg(int64_t arg10, int64_t arg11, bool arg12)
{
fuzz1_checkValues(arg10, arg11, arg12);
}
extern(C++) void fuzz1_checkValues(int64_t arg10, int64_t arg11, bool arg12)
{
assert(arg10 == 103);
assert(arg11 == 104);
assert(arg12 == false);
}
void fuzz1()
{
long arg10 = 103;
long arg11 = 104;
bool arg12 = false;
fuzz1_dvararg(arg10, arg11, arg12);
fuzz1_cppvararg(arg10, arg11, arg12);
}
////////
extern(C++) void fuzz2_cppvararg(uint64_t arg10, uint64_t arg11, bool arg12);
extern(C++) void fuzz2_dvararg(uint64_t arg10, uint64_t arg11, bool arg12)
{
fuzz2_checkValues(arg10, arg11, arg12);
}
extern(C++) void fuzz2_checkValues(uint64_t arg10, uint64_t arg11, bool arg12)
{
assert(arg10 == 103);
assert(arg11 == 104);
assert(arg12 == false);
}
void fuzz2()
{
ulong arg10 = 103;
ulong arg11 = 104;
bool arg12 = false;
fuzz2_dvararg(arg10, arg11, arg12);
fuzz2_cppvararg(arg10, arg11, arg12);
}
////////
extern(C++) void fuzz3_cppvararg(wchar arg10, wchar arg11, bool arg12);
extern(C++) void fuzz3_dvararg(wchar arg10, wchar arg11, bool arg12)
{
fuzz2_checkValues(arg10, arg11, arg12);
}
extern(C++) void fuzz3_checkValues(wchar arg10, wchar arg11, bool arg12)
{
assert(arg10 == 103);
assert(arg11 == 104);
assert(arg12 == false);
}
void fuzz3()
{
wchar arg10 = 103;
wchar arg11 = 104;
bool arg12 = false;
fuzz3_dvararg(arg10, arg11, arg12);
fuzz3_cppvararg(arg10, arg11, arg12);
}
void fuzz()
{
fuzz1();
fuzz2();
fuzz3();
}
/****************************************/
extern (C++)
{
void throwit();
}
void testeh()
{
printf("testeh()\n");
version (linux)
{
version (X86_64)
{
bool caught;
try
{
throwit();
}
catch (std.exception e)
{
caught = true;
}
assert(caught);
}
}
}
/****************************************/
version (linux)
{
version (X86_64)
{
bool raii_works = false;
struct RAIITest
{
~this()
{
raii_works = true;
}
}
void dFunction()
{
RAIITest rt;
throwit();
}
void testeh2()
{
printf("testeh2()\n");
try
{
dFunction();
}
catch(std.exception e)
{
assert(raii_works);
}
}
}
else
void testeh2() { }
}
else
void testeh2() { }
/****************************************/
extern (C++) { void throwle(); void throwpe(); }
void testeh3()
{
printf("testeh3()\n");
version (linux)
{
version (X86_64)
{
bool caught = false;
try
{
throwle();
}
catch (std.exception e) //polymorphism test.
{
caught = true;
}
assert(caught);
}
}
}
/****************************************/
// https://issues.dlang.org/show_bug.cgi?id=15576
extern (C++, ns15576)
{
extern __gshared int global15576;
extern (C++, ns)
{
extern __gshared int n_global15576;
}
}
void test15576()
{
global15576 = n_global15576 = 123;
}
/****************************************/
// https://issues.dlang.org/show_bug.cgi?id=15579
extern (C++)
{
class Base
{
//~this() {}
void based() { }
ubyte x = 4;
}
interface Interface
{
int MethodCPP();
int MethodD();
}
class Derived : Base, Interface
{
short y = 5;
int MethodCPP();
int MethodD() {
printf("Derived.MethodD(): this = %p, x = %d, y = %d\n", this, x, y);
Derived p = this;
//p = cast(Derived)(cast(void*)p - 16);
assert(p.x == 4 || p.x == 7);
assert(p.y == 5 || p.y == 8);
return 3;
}
int Method() { return 6; }
}
Derived cppfoo(Derived);
Interface cppfooi(Interface);
}
void test15579()
{
Derived d = new Derived();
printf("d = %p\n", d);
assert(d.x == 4);
assert(d.y == 5);
assert((cast(Interface)d).MethodCPP() == 30);
assert((cast(Interface)d).MethodD() == 3);
assert(d.MethodCPP() == 30);
assert(d.MethodD() == 3);
assert(d.Method() == 6);
d = cppfoo(d);
assert(d.x == 7);
assert(d.y == 8);
printf("d2 = %p\n", d);
/* Casting to an interface involves thunks in the vtbl[].
* g++ puts the thunks for MethodD in the same COMDAT as MethodD.
* But D doesn't, so when the linker "picks one" of the D generated MethodD
* or the g++ generated MethodD, it may wind up with a messed up thunk,
* resulting in a seg fault. The solution is to not expect objects of the same
* type to be constructed on both sides of the D/C++ divide if the same member
* function (in this case, MethodD) is also defined on both sides.
*/
version (Windows)
{
assert((cast(Interface)d).MethodD() == 3);
}
assert((cast(Interface)d).MethodCPP() == 30);
assert(d.Method() == 6);
printf("d = %p, i = %p\n", d, cast(Interface)d);
version (Windows)
{
Interface i = cppfooi(d);
printf("i2: %p\n", i);
assert(i.MethodD() == 3);
assert(i.MethodCPP() == 30);
}
printf("test15579() done\n");
}
/****************************************/
// https://issues.dlang.org/show_bug.cgi?id=15610
extern(C++) class Base2
{
int i;
void baser() { }
}
extern(C++) interface Interface2 { abstract void f(); }
extern(C++) class Derived2 : Base2, Interface2
{
final
override void f();
}
void test15610()
{
auto c = new Derived2();
printf("test15610(): c = %p\n", c);
c.i = 3;
c.f();
}
/******************************************/
// https://issues.dlang.org/show_bug.cgi?id=15455
struct X6
{
ushort a;
ushort b;
ubyte c;
ubyte d;
}
static assert(X6.sizeof == 6);
struct X8
{
ushort a;
X6 b;
}
static assert(X8.sizeof == 8);
void test15455a(X8 s)
{
assert(s.a == 1);
assert(s.b.a == 2);
assert(s.b.b == 3);
assert(s.b.c == 4);
assert(s.b.d == 5);
}
extern (C++) void test15455b(X8 s);
void test15455()
{
X8 s;
s.a = 1;
s.b.a = 2;
s.b.b = 3;
s.b.c = 4;
s.b.d = 5;
test15455a(s);
test15455b(s);
}
/****************************************/
// https://issues.dlang.org/show_bug.cgi?id=15372
extern(C++) int foo15372(T)(int v);
void test15372()
{
version(Windows){}
else
assert(foo15372!int(1) == 1);
}
/****************************************/
// https://issues.dlang.org/show_bug.cgi?id=15802
extern(C++) {
template Foo15802(T) {
static int boo(T v);
}
}
void test15802()
{
version(Windows){}
else
assert(Foo15802!(int).boo(1) == 1);
}
/****************************************/
// https://issues.dlang.org/show_bug.cgi?id=16536
// mangling mismatch on OSX
version(OSX) extern(C++) uint64_t pass16536(uint64_t);
void test16536()
{
version(OSX) assert(pass16536(123) == 123);
}
/****************************************/
// https://issues.dlang.org/show_bug.cgi?id=15589
// extern(C++) virtual destructors are not put in vtbl[]
extern(C++)
{
class A15589
{
extern(D) static int[] dtorSeq;
struct S
{
this(int x) { this.x = x; }
~this() { dtorSeq ~= x; }
int x;
}
int foo() { return 100; } // shift dtor to slot 1
~this() { dtorSeq ~= 10; }
S s1 = S(1);
S s2 = S(2);
}
class B15589 : A15589
{
int bar() { return 200;} // add an additional function AFTER the dtor at slot 2
~this() { dtorSeq ~= 20; }
S s3 = S(3);
}
void test15589b(A15589 p);
}
void test15589()
{
A15589 c = new B15589;
assert(A15589.dtorSeq == null);
assert(c.foo() == 100);
assert((cast(B15589)c).bar() == 200);
c.__xdtor(); // virtual dtor call
assert(A15589.dtorSeq[] == [ 20, 3, 10, 2, 1 ]); // destroyed full hierarchy!
A15589.dtorSeq = null;
test15589b(c);
assert(A15589.dtorSeq[] == [ 20, 3, 10, 2, 1 ]); // destroyed full hierarchy!
}
extern(C++)
{
class Cpp15589Base
{
public:
final ~this();
void nonVirtual();
int a;
}
class Cpp15589Derived : Cpp15589Base
{
public:
this();
final ~this();
int b;
}
class Cpp15589BaseVirtual
{
public:
void beforeDtor();
this();
~this();
void afterDtor();
int c = 1;
}
class Cpp15589DerivedVirtual : Cpp15589BaseVirtual
{
public:
this();
~this();
override void afterDtor();
int d;
}
class Cpp15589IntroducingVirtual : Cpp15589Base
{
public:
this();
void beforeIntroducedVirtual();
~this();
void afterIntroducedVirtual(int);
int e;
}
struct Cpp15589Struct
{
~this();
int s;
}
void trace15589(int ch)
{
traceBuf[traceBufPos++] = cast(char) ch;
}
}
__gshared char[32] traceBuf;
__gshared size_t traceBufPos;
mixin template scopeAllocCpp(C)
{
// workaround for https://issues.dlang.org/show_bug.cgi?id=18986
version(OSX)
enum cppCtorReturnsThis = false;
else version(FreeBSD)
enum cppCtorReturnsThis = false;
else
enum cppCtorReturnsThis = true;
static if (cppCtorReturnsThis)
scope C ptr = new C;
else
{
ubyte[__traits(classInstanceSize, C)] data;
C ptr = (){ auto p = cast(C) data.ptr; p.__ctor(); return p; }();
}
}
void test15589b()
{
traceBufPos = 0;
{
Cpp15589Struct struc = Cpp15589Struct();
mixin scopeAllocCpp!Cpp15589Derived derived;
mixin scopeAllocCpp!Cpp15589DerivedVirtual derivedVirtual;
mixin scopeAllocCpp!Cpp15589IntroducingVirtual introducingVirtual;
introducingVirtual.ptr.destroy();
derivedVirtual.ptr.destroy();
derived.ptr.destroy();
}
printf("traceBuf15589 %.*s\n", cast(int)traceBufPos, traceBuf.ptr);
assert(traceBuf[0..traceBufPos] == "IbVvBbs");
}
/****************************************/
// https://issues.dlang.org/show_bug.cgi?id=18928
// Win64: extern(C++) bad codegen, wrong calling convention
extern(C++) struct Small18928
{
int x;
}
extern(C++) class CC18928
{
Small18928 getVirtual(); // { return S(3); }
final Small18928 getFinal(); // { return S(4); }
static Small18928 getStatic(); // { return S(5); }
}
extern(C++) CC18928 newCC18928();
void test18928()
{
auto cc = newCC18928();
Small18928 v = cc.getVirtual();
assert(v.x == 3);
Small18928 f = cc.getFinal();
assert(f.x == 4);
Small18928 s = cc.getStatic();
assert(s.x == 5);
}
/****************************************/
// https://issues.dlang.org/show_bug.cgi?id=18953
// Win32: extern(C++) struct destructor not called correctly through runtime
extern(C++)
struct S18953
{
char x;
~this() nothrow @nogc { traceBuf[traceBufPos++] = x; }
}
void test18953()
{
traceBufPos = 0;
S18953[] arr = new S18953[3];
arr[1].x = '1';
arr[2].x = '2';
arr.length = 1;
assumeSafeAppend(arr); // destroys arr[1] and arr[2]
printf("traceBuf18953 %.*s\n", cast(int)traceBufPos, traceBuf.ptr);
assert(traceBuf[0..traceBufPos] == "21");
}
/****************************************/
// https://issues.dlang.org/show_bug.cgi?id=18966
extern(C++):
class Base18966
{
this() @safe nothrow;
~this();
void vf();
int x;
}
class Derived18966 : Base18966
{
override void vf() { x = 200; }
}
class Explicit18966 : Base18966
{
this() @safe { super(); }
override void vf() { x = 250; }
}
class Implicit18966 : Base18966
{
this() nothrow {}
override void vf() { x = 300; }
}
// test vptr in full ctor chain of mixed D/C++ class hierarchies
// TODO: Make this a D class and let C++ derive from it. This works on Windows,
// but results in linker errors on Posix due to extra base ctor (`C2`
// mangling) being called by the B ctor.
class A18966 // in C++
{
char[8] calledOverloads = 0;
int i;
this();
void foo();
}
class B18966 : A18966 // in C++
{
this();
override void foo();
}
class C18966 : B18966
{
this() { foo(); }
override void foo() { calledOverloads[i++] = 'C'; }
}
class D18966 : C18966
{
this() { foo(); }
override void foo() { calledOverloads[i++] = 'D'; }
}
void test18966()
{
Derived18966 d = new Derived18966;
assert(d.x == 10);
d.vf();
assert(d.x == 200);
Explicit18966 e = new Explicit18966;
assert(e.x == 10);
e.vf();
assert(e.x == 250);
Implicit18966 i = new Implicit18966;
assert(i.x == 10);
i.vf();
assert(i.x == 300);
// TODO: Allocating + constructing a C++ class with the D GC is not
// supported on Posix. The returned pointer (probably from C++ ctor)
// seems to be an offset and not the actual object address.
version (Windows)
{
auto a = new A18966;
assert(a.calledOverloads[0..2] == "A\0");
auto b = new B18966;
assert(b.calledOverloads[0..3] == "AB\0");
}
auto c = new C18966;
assert(c.calledOverloads[0..4] == "ABC\0");
auto d2 = new D18966;
// note: the vptr semantics in ctors of extern(C++) classes may be revised (to "ABCD")
assert(d2.calledOverloads[0..5] == "ABDD\0");
}
/****************************************/
// https://issues.dlang.org/show_bug.cgi?id=19134
class Base19134
{
int a = 123;
this() { a += 42; }
int foo() const { return a; }
}
class Derived19134 : Base19134
{
int b = 666;
this()
{
a *= 2;
b -= 6;
}
override int foo() const { return b; }
}
void test19134()
{
static const d = new Derived19134;
assert(d.a == (123 + 42) * 2);
assert(d.b == 666 - 6);
assert(d.foo() == 660);
}
// https://issues.dlang.org/show_bug.cgi?id=18955
alias std_string = std.basic_string!(char);
extern(C++) void callback18955(ref const(std_string) str)
{
}
extern(C++) void test18955();
/****************************************/
void main()
{
test1();
test2();
test3();
test4();
test13956();
test5();
test6();
test10071();
test7();
test8();
test11802();
test9();
test10();
test13955();
test11();
testvalist();
test12825();
test13161();
test14();
test13289();
test15();
test16();
func13707();
func13932(S13932!(-1)(0));
foo13337(S13337());
test14195();
test14200();
test14956(S14956());
testVtable();
fuzz();
testeh();
testeh2();
testeh3();
test15576();
test15579();
test15610();
test15455();
test15372();
test15802();
test16536();
test15589();
test15589b();
test18928();
test18953();
test18966();
test19134();
test18955();
printf("Success\n");
}
|
D
|
import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric;
struct SW {
double w;
double s;
double d(double c) {
return (s+w) * (s/(s+w)*100 - c);
}
@property
double concentration() {
if (w+s == 0) return 0;
return s / (w+s) * 100;
}
}
SW[1000] SWS;
void main()
{
auto nk = readln.split.to!(int[]);
auto N = nk[0];
auto K = nk[1];
foreach (i; 0..N) {
auto wp = readln.split.to!(double[]);
auto s = wp[0] * wp[1] / 100;
auto w = wp[0] - s;
SWS[i] = SW(w, s);
}
double min_c = 0, max_c = 101;
foreach (_; 0..1000) {
auto mid_c = (min_c + max_c) / 2;
sort!((a, b) => a.d(mid_c) > b.d(mid_c))(SWS[0..N]);
auto sw_s = SW(0, 0);
foreach (sw; SWS[0..K]) {
sw_s.w += sw.w;
sw_s.s += sw.s;
}
if (sw_s.concentration > mid_c) {
min_c = mid_c;
} else {
max_c = mid_c;
}
}
writefln("%0.10f", max_c);
}
|
D
|
// COMPILED_IMPORTS: imports/test50a.d
// PERMUTE_ARGS:
import imports.test50a;
class Bar : Foo {
alias typeof(Foo.tupleof) Bleh;
}
|
D
|
/orange_pro/swift_dev/Fanplan/.build/debug/PerfectNet.build/NetTCP.swift.o : /orange_pro/swift_dev/Fanplan/Packages/PerfectNet-0.7.0/Sources/NetTCP.swift /orange_pro/swift_dev/Fanplan/Packages/PerfectNet-0.7.0/Sources/Net.swift /orange_pro/swift_dev/Fanplan/Packages/PerfectNet-0.7.0/Sources/NetTCPSSL.swift /orange_pro/swift_dev/Fanplan/Packages/PerfectNet-0.7.0/Sources/NetNamedPipe.swift /orange_pro/swift_dev/Fanplan/Packages/PerfectNet-0.7.0/Sources/NetEvent.swift /orange_pro/swift_dev/swift/usr/lib/swift/linux/x86_64/Swift.swiftmodule /orange_pro/swift_dev/swift/usr/lib/swift/shims/Visibility.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/SwiftStdint.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/UnicodeShims.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/SwiftStddef.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/LibcShims.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/RuntimeStubs.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/RuntimeShims.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/RefCount.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/HeapObject.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/GlobalObjects.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/FoundationShims.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/CoreFoundationShims.h /orange_pro/swift_dev/Fanplan/Packages/LinuxBridge-0.4.0/module.modulemap /orange_pro/swift_dev/swift/usr/lib/swift/linux/x86_64/glibc.modulemap /orange_pro/swift_dev/swift/usr/lib/swift/shims/module.map /orange_pro/swift_dev/swift/usr/lib/swift/linux/x86_64/SwiftOnoneSupport.swiftmodule /orange_pro/swift_dev/Fanplan/.build/debug/PerfectThread.swiftmodule /orange_pro/swift_dev/Fanplan/Packages/LinuxBridge-0.4.0/LinuxBridge.h /orange_pro/swift_dev/Fanplan/Packages/OpenSSL-0.3.0/module.modulemap /orange_pro/swift_dev/Fanplan/Packages/OpenSSL-0.3.0/openssl.h
/orange_pro/swift_dev/Fanplan/.build/debug/PerfectNet.build/NetTCP~partial.swiftmodule : /orange_pro/swift_dev/Fanplan/Packages/PerfectNet-0.7.0/Sources/NetTCP.swift /orange_pro/swift_dev/Fanplan/Packages/PerfectNet-0.7.0/Sources/Net.swift /orange_pro/swift_dev/Fanplan/Packages/PerfectNet-0.7.0/Sources/NetTCPSSL.swift /orange_pro/swift_dev/Fanplan/Packages/PerfectNet-0.7.0/Sources/NetNamedPipe.swift /orange_pro/swift_dev/Fanplan/Packages/PerfectNet-0.7.0/Sources/NetEvent.swift /orange_pro/swift_dev/swift/usr/lib/swift/linux/x86_64/Swift.swiftmodule /orange_pro/swift_dev/swift/usr/lib/swift/shims/Visibility.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/SwiftStdint.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/UnicodeShims.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/SwiftStddef.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/LibcShims.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/RuntimeStubs.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/RuntimeShims.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/RefCount.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/HeapObject.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/GlobalObjects.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/FoundationShims.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/CoreFoundationShims.h /orange_pro/swift_dev/Fanplan/Packages/LinuxBridge-0.4.0/module.modulemap /orange_pro/swift_dev/swift/usr/lib/swift/linux/x86_64/glibc.modulemap /orange_pro/swift_dev/swift/usr/lib/swift/shims/module.map /orange_pro/swift_dev/swift/usr/lib/swift/linux/x86_64/SwiftOnoneSupport.swiftmodule /orange_pro/swift_dev/Fanplan/.build/debug/PerfectThread.swiftmodule /orange_pro/swift_dev/Fanplan/Packages/LinuxBridge-0.4.0/LinuxBridge.h /orange_pro/swift_dev/Fanplan/Packages/OpenSSL-0.3.0/module.modulemap /orange_pro/swift_dev/Fanplan/Packages/OpenSSL-0.3.0/openssl.h
/orange_pro/swift_dev/Fanplan/.build/debug/PerfectNet.build/NetTCP~partial.swiftdoc : /orange_pro/swift_dev/Fanplan/Packages/PerfectNet-0.7.0/Sources/NetTCP.swift /orange_pro/swift_dev/Fanplan/Packages/PerfectNet-0.7.0/Sources/Net.swift /orange_pro/swift_dev/Fanplan/Packages/PerfectNet-0.7.0/Sources/NetTCPSSL.swift /orange_pro/swift_dev/Fanplan/Packages/PerfectNet-0.7.0/Sources/NetNamedPipe.swift /orange_pro/swift_dev/Fanplan/Packages/PerfectNet-0.7.0/Sources/NetEvent.swift /orange_pro/swift_dev/swift/usr/lib/swift/linux/x86_64/Swift.swiftmodule /orange_pro/swift_dev/swift/usr/lib/swift/shims/Visibility.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/SwiftStdint.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/UnicodeShims.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/SwiftStddef.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/LibcShims.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/RuntimeStubs.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/RuntimeShims.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/RefCount.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/HeapObject.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/GlobalObjects.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/FoundationShims.h /orange_pro/swift_dev/swift/usr/lib/swift/shims/CoreFoundationShims.h /orange_pro/swift_dev/Fanplan/Packages/LinuxBridge-0.4.0/module.modulemap /orange_pro/swift_dev/swift/usr/lib/swift/linux/x86_64/glibc.modulemap /orange_pro/swift_dev/swift/usr/lib/swift/shims/module.map /orange_pro/swift_dev/swift/usr/lib/swift/linux/x86_64/SwiftOnoneSupport.swiftmodule /orange_pro/swift_dev/Fanplan/.build/debug/PerfectThread.swiftmodule /orange_pro/swift_dev/Fanplan/Packages/LinuxBridge-0.4.0/LinuxBridge.h /orange_pro/swift_dev/Fanplan/Packages/OpenSSL-0.3.0/module.modulemap /orange_pro/swift_dev/Fanplan/Packages/OpenSSL-0.3.0/openssl.h
|
D
|
module tpl.collection;
class Коллекция(Ш)
{
private Ш[] _t;
public final цел добавь(Ш t)
{
this._t ~= t;
return this._t.length - 1;
}
public final проц сотри()
{
this._t.length = 0;
}
public final цел длина()
{
return this._t.length;
}
public final проц удали(Ш t)
{
this.удалиПо(this.найди(t));
}
public final проц удалиПо(цел idx)
{
цел x = 0;
Ш[] новШ = new Ш[this._t.length - 1];
foreach(цел i, Ш t; this._t)
{
if(i != idx)
{
новШ[x] = t;
x++;
}
}
this._t = новШ;
}
public final цел найди(Ш t)
{
foreach(цел i, Ш ft; this._t)
{
if(ft is t)
{
return i;
}
}
return -1;
}
public Ш opIndex(цел i)
{
if(i >= 0 && i < this._t.length)
{
return this._t[i];
}
return null;
}
public цел opApply(цел delegate(ref Ш) dg)
{
цел res = 0;
if(this._t.length)
{
for(цел i = 0; i < this._t.length; i++)
{
res = dg(this._t[i]);
if(res)
{
break;
}
}
}
return res;
}
public цел opApply(цел delegate(ref цел, ref Ш) dg)
{
цел res = 0;
if(this._t.length)
{
for(цел i = 0; i < this._t.length; i++)
{
res = dg(i, this._t[i]);
if(res)
{
break;
}
}
}
return res;
}
}
|
D
|
module vulkan.helpers.Context;
import vulkan.all;
enum MemID : string {
LOCAL = "MEM_LOCAL",
SHARED = "MEM_SHARED",
STAGING = "MEM_STAGING_UP",
STAGING_DOWN = "MEM_STAGING_DN"
}
enum BufID : string {
VERTEX = "VERTEX",
INDEX = "INDEX",
UNIFORM = "UNIFORM",
STORAGE = "STORAGE",
STAGING = "STAGING_UP",
STAGING_DOWN = "STAGING_DN"
}
final class VulkanContext {
private:
DeviceMemory[string] memories;
DeviceBuffer[string] buffers;
ShaderCompiler _shaderCompiler;
Fonts _fonts;
Images _images;
Transfer _transfer;
InfoBuilder infoBuilder;
public:
Vulkan vk;
VkDevice device;
VkRenderPass renderPass;
bool verboseLogging = false;
Fonts fonts() { if(!_fonts) throw new Error("Fonts has not been added to context"); return _fonts; }
Images images() { if(!_images) throw new Error("Images has not been added to context"); return _images; }
ShaderCompiler shaderCompiler() { if(!_shaderCompiler) throw new Error("ShaderCompiler has not been added to context"); return _shaderCompiler; }
Transfer transfer() { return _transfer; }
InfoBuilder build() { return infoBuilder; }
this(Vulkan vk) {
this.vk = vk;
this.device = vk.device;
this._transfer = new Transfer(this);
this.infoBuilder = new InfoBuilder(this);
}
void destroy() {
if(_shaderCompiler) shaderCompiler.destroy();
if(_fonts) _fonts.destroy();
if(_images) _images.destroy();
foreach(m; memories.values()) {
m.destroy();
}
}
override string toString() {
auto buf = new StringBuffer().add("VulkanContext(\n");
foreach(k,v; memories) {
buf.add("\t[%s %s]\n", k, v.size.sizeToString());
foreach(k2, v2; buffers) {
if(v2.memory is v) {
buf.add("\t\t%s %s\n", k2, v2.size.sizeToString());
}
}
}
return buf.add(")").toString();
}
auto withMemory(MemID id, DeviceMemory mem) {
if(mem is null) return this;
if(id in memories) throw new Error("Memory ID '%s' already added to context".format(id));
memories[id] = mem;
return this;
}
auto withBuffer(MemID mem, BufID buf, VBufferUsage usage, ulong size) {
if(buf in buffers) throw new Error("Buffer ID '%s' already added to context".format(buf));
auto m = mem in memories;
if(!m) throw new Error("Memory ID '%s' not found in context".format(mem));
buffers[buf] = m.allocBuffer(buf, size, usage);
return this;
}
auto withShaderCompiler(string srcDirectory, string destDirectory) {
this._shaderCompiler = new ShaderCompiler(device, srcDirectory, destDirectory);
return this;
}
auto withFonts(string fontDirectory) {
this._fonts = new Fonts(this, fontDirectory);
return this;
}
auto withImages(string baseDirectory) {
this._images = new Images(this, baseDirectory);
return this;
}
auto withRenderPass(VkRenderPass renderPass) {
this.renderPass = renderPass;
return this;
}
bool hasMemory(MemID id) {
return (id in memories) !is null;
}
bool hasMemory(string id) {
return hasMemory(id.as!MemID);
}
/**
* Return the buffer with given BufID
*/
DeviceBuffer buffer(BufID id) {
auto b = id in buffers;
if(!b) throw new Error("Buffer ID '%s' not found in context".format(id));
return *b;
}
DeviceBuffer buffer(string id) {
return buffer(id.as!BufID);
}
/**
* Return the memory with given MemID
*/
DeviceMemory memory(MemID id) {
auto ptr = id in memories;
if(!ptr) throw new Error("Memory ID '%s' not found in context".format(id));
return *ptr;
}
DeviceMemorySnapshot[] takeMemorySnapshot() {
DeviceMemorySnapshot[] snaps;
foreach(m; memories.values()) {
snaps ~= new DeviceMemorySnapshot(m);
}
return snaps;
}
void dumpMemory() {
string buf;
foreach(s; takeMemorySnapshot()) {
buf ~= "\n%s".format(s);
}
this.log(buf);
}
}
|
D
|
E: c775, c115, c743, c143, c785, c853, c289, c373, c311, c3, c579, c323, c230, c395, c88, c515, c357, c716, c206, c194, c139, c388, c153, c219, c739, c619, c523, c40, c151, c204, c105, c858, c738, c611, c489, c609, c851, c856, c878, c283, c343, c586, c710, c818, c360, c117, c715, c480, c703, c325, c137, c163, c196, c876, c334, c155, c79, c759, c495, c12, c596, c729, c510, c465, c735, c766, c346, c603, c550, c209, c562, c53, c10, c545, c329, c220, c560, c441, c686, c826, c530, c213, c52, c769, c595, c270, c349, c594, c187, c811, c228, c864, c23, c506, c458, c539, c277, c598, c846, c294, c552, c354, c647, c513, c493, c365, c825, c413, c368, c559, c268, c687, c374, c803, c591, c326, c556, c134, c755, c632, c551, c340, c127, c109, c690, c601, c724, c427, c704, c254, c138, c261, c218, c24, c600, c567, c362, c31, c587, c778, c38, c645, c226, c101, c517, c832, c75, c271, c447, c83, c492, c94, c790, c468, c369, c831, c419, c813, c412, c727, c768, c215, c224, c745, c70, c146, c821, c253, c92, c108, c332, c35, c57, c249, c459, c673, c855, c830, c682, c25, c36, c361, c576, c257, c201, c456, c21, c305, c867, c364, c385, c440, c829, c353, c418, c4, c540, c481, c169, c529, c285, c788, c47, c744, c777, c657, c111, c121, c297, c747, c566, c677, c381, c787, c42, c225, c122, c145, c722, c279, c162, c536, c26, c179, c674, c84, c322, c89, c820, c848, c129, c535, c571, c61, c665, c299, c317, c478, c660, c351, c842, c238, c625, c232, c466, c378, c445, c367, c414, c282, c177, c643, c662, c720, c531, c387, c663, c658, c431, c337, c633, c422, c356, c185, c87, c123, c321, c661, c794, c20, c2, c763, c214, c822, c479, c622, c808, c497, c221, c424, c173, c502, c563, c405, c765, c74, c124, c751, c426, c474, c390, c98, c607, c241, c252, c528, c304, c828, c324, c272, c491, c815, c871, c9, c683, c295.
p3(E)
c775
c230
c105
c856
c283
c506
c458
c204
c600
c10
c790
c108
c766
c47
c111
c677
c326
c727
c690
c842
c724
c365
c285
c686
c633
c739
c294
c89
c704
c329
c825
c855
.
p5(E,E)
c115,c743
c143,c785
c115,c853
c579,c323
c579,c139
c523,c785
c40,c853
c738,c611
c523,c878
c219,c743
c523,c343
c523,c586
c738,c853
c311,c360
c480,c703
c325,c360
c489,c323
c143,c853
c153,c878
c480,c743
c735,c586
c523,c716
c579,c586
c735,c611
c480,c206
c153,c586
c325,c853
c715,c194
c735,c357
c329,c220
c213,c52
c194,c878
c716,c785
c596,c586
c115,c703
c153,c360
c596,c853
c596,c139
c153,c194
c523,c12
c489,c611
c40,c716
c294,c552
c735,c858
c209,c853
c825,c413
c40,c194
c311,c853
c735,c743
c489,c853
c79,c268
c489,c343
c219,c117
c40,c743
c489,c703
c738,c117
c715,c360
c738,c139
c254,c270
c523,c323
c143,c194
c143,c12
c579,c858
c194,c858
c40,c611
c738,c206
c480,c194
c115,c117
c194,c343
c729,c139
c311,c194
c729,c117
c325,c139
c596,c194
c729,c343
c40,c785
c194,c117
c715,c323
c349,c832
c596,c323
c52,c83
c724,c601
c489,c194
c579,c703
c523,c117
c596,c611
c153,c323
c209,c586
c729,c858
c194,c785
c40,c357
c727,c768
c738,c360
c311,c139
c735,c360
c194,c611
c194,c716
c325,c743
c143,c716
c311,c206
c735,c117
c716,c360
c738,c323
c194,c743
c480,c357
c489,c586
c489,c206
c515,c88
c523,c360
c729,c785
c219,c785
c143,c858
c596,c357
c40,c878
c579,c117
c209,c360
c738,c343
c325,c12
c715,c878
c735,c12
c169,c12
c153,c716
c715,c357
c209,c117
c715,c785
c523,c853
c480,c117
c715,c388
c143,c878
c194,c194
c715,c12
c225,c122
c729,c357
c194,c139
c209,c323
c40,c139
c716,c743
c579,c611
c716,c343
c209,c611
c143,c611
c209,c785
c311,c343
c194,c586
c219,c388
c115,c611
c194,c12
c716,c878
c735,c323
c790,c84
c219,c360
c325,c611
c209,c12
c579,c388
c153,c139
c143,c388
c715,c703
c716,c586
c153,c12
c729,c323
c40,c388
c325,c858
c729,c206
c480,c858
c209,c716
c219,c716
c480,c343
c716,c323
c219,c206
c311,c785
c735,c703
c738,c878
c219,c858
c153,c206
c596,c117
c480,c586
c480,c139
c209,c743
c738,c388
c219,c12
c729,c388
c523,c139
c209,c703
c115,c357
c738,c357
c489,c785
c735,c206
c738,c703
c690,c109
c489,c139
c738,c12
c715,c853
c716,c12
c311,c388
c311,c12
c153,c853
c219,c853
c143,c117
c489,c716
c115,c858
c40,c360
c729,c360
c729,c716
c579,c360
c325,c357
c194,c360
c596,c785
c40,c206
c735,c194
c311,c878
c579,c343
c219,c703
c735,c388
c715,c139
c715,c858
c716,c388
c194,c703
c194,c206
c738,c586
c579,c206
c40,c586
c735,c139
c153,c611
c311,c323
c326,c556
c321,c661
c40,c117
c729,c611
c729,c853
c115,c323
c716,c139
c153,c785
c219,c194
c523,c206
c219,c878
c311,c611
c209,c343
c143,c743
c738,c743
c219,c586
c686,c441
c153,c858
c108,c21
c143,c586
c311,c703
c579,c853
c739,c219
c40,c703
c325,c343
c523,c194
c738,c858
c633,c356
c715,c586
c115,c139
c480,c878
c596,c12
c89,c270
c219,c611
c738,c785
c480,c785
c715,c343
c143,c357
c489,c388
c209,c206
c716,c853
c194,c323
c209,c139
c115,c388
c194,c388
c153,c703
c153,c388
c209,c858
c209,c357
c735,c878
c21,c387
c489,c12
c153,c343
c735,c853
c40,c858
c729,c194
.
p0(E,E)
c289,c373
c88,c515
c357,c716
c206,c194
c388,c153
c219,c739
c357,c311
c151,c204
c858,c716
c743,c489
c853,c311
c609,c851
c139,c194
c710,c818
c206,c738
c117,c715
c785,c523
c743,c143
c137,c163
c196,c876
c388,c480
c334,c155
c79,c759
c611,c219
c12,c596
c586,c729
c586,c153
c194,c715
c510,c465
c139,c523
c743,c40
c611,c579
c853,c715
c586,c523
c388,c115
c603,c550
c858,c209
c562,c53
c360,c219
c194,c735
c194,c596
c878,c716
c560,c283
c441,c686
c388,c729
c826,c530
c703,c153
c769,c595
c270,c349
c343,c480
c785,c311
c858,c735
c864,c23
c743,c579
c539,c277
c598,c506
c716,c219
c611,c194
c194,c579
c846,c357
c354,c506
c493,c365
c388,c40
c323,c325
c716,c523
c716,c194
c343,c40
c323,c579
c117,c115
c134,c755
c357,c153
c357,c596
c632,c551
c703,c715
c340,c127
c743,c596
c109,c690
c139,c715
c360,c729
c601,c724
c427,c704
c703,c194
c117,c480
c139,c40
c586,c115
c388,c143
c218,c24
c139,c325
c31,c587
c343,c143
c343,c523
c785,c729
c357,c523
c853,c194
c206,c153
c271,c447
c343,c194
c139,c153
c194,c489
c611,c40
c388,c209
c357,c489
c468,c369
c853,c115
c12,c729
c813,c412
c716,c596
c878,c523
c687,c215
c785,c596
c360,c715
c586,c311
c323,c745
c858,c325
c70,c146
c703,c738
c206,c715
c343,c596
c716,c480
c716,c738
c253,c92
c323,c480
c703,c311
c878,c489
c586,c716
c332,c35
c117,c596
c57,c249
c673,c855
c830,c682
c194,c219
c25,c36
c556,c326
c586,c596
c361,c576
c257,c201
c743,c219
c778,c206
c323,c735
c163,c334
c703,c489
c194,c729
c440,c829
c360,c143
c703,c523
c117,c735
c703,c596
c117,c209
c360,c489
c12,c219
c357,c738
c785,c716
c323,c523
c743,c115
c703,c40
c323,c153
c529,c228
c343,c489
c703,c209
c343,c209
c716,c716
c388,c596
c343,c219
c611,c115
c137,c121
c139,c716
c343,c115
c139,c738
c878,c325
c40,c566
c323,c311
c206,c219
c858,c596
c611,c143
c787,c42
c206,c480
c145,c722
c194,c209
c716,c143
c279,c357
c194,c115
c858,c523
c206,c579
c878,c115
c716,c115
c586,c194
c12,c738
c343,c579
c536,c567
c858,c738
c26,c179
c743,c480
c703,c716
c360,c115
c357,c115
c586,c738
c878,c480
c322,c89
c343,c311
c878,c735
c820,c848
c785,c153
c716,c325
c343,c716
c206,c40
c716,c209
c357,c579
c139,c579
c609,c535
c117,c40
c858,c194
c343,c729
c571,c61
c388,c716
c79,c279
c12,c115
c657,c317
c853,c480
c357,c715
c853,c579
c12,c40
c323,c40
c117,c523
c586,c735
c858,c715
c716,c40
c117,c143
c117,c489
c785,c219
c117,c219
c611,c489
c858,c489
c703,c325
c529,c466
c357,c325
c323,c715
c94,c24
c611,c311
c743,c716
c378,c12
c878,c715
c145,c111
c878,c209
c703,c480
c12,c715
c846,c445
c360,c596
c785,c325
c876,c79
c545,c26
c139,c735
c357,c480
c360,c40
c858,c153
c785,c738
c785,c40
c643,c662
c323,c115
c586,c579
c716,c715
c388,c579
c663,c658
c665,c677
c703,c115
c362,c209
c194,c143
c194,c194
c169,c422
c139,c596
c586,c325
c388,c219
c360,c579
c716,c579
c139,c219
c716,c153
c413,c825
c52,c123
c343,c738
c788,c285
c388,c311
c657,c232
c194,c325
c853,c143
c611,c735
c768,c727
c83,c52
c343,c153
c763,c214
c611,c715
c194,c311
c206,c143
c878,c311
c194,c738
c622,c808
c117,c716
c703,c579
c12,c489
c323,c143
c117,c729
c853,c523
c743,c325
c356,c633
c12,c153
c785,c489
c360,c153
c716,c735
c139,c480
c388,c523
c343,c735
c12,c209
c743,c194
c323,c219
c220,c329
c765,c74
c878,c596
c117,c311
c346,c766
c206,c489
c586,c480
c493,c124
c357,c219
c206,c735
c611,c729
c194,c716
c474,c390
c607,c241
c388,c194
c388,c715
c12,c480
c332,c204
c785,c715
c206,c209
c785,c143
c853,c596
c528,c304
c586,c219
c853,c325
c360,c194
c853,c716
c139,c729
c12,c579
c206,c311
c117,c194
c853,c735
c853,c738
c785,c194
c858,c480
c878,c579
c703,c143
c743,c715
c878,c219
c139,c143
c12,c143
c878,c153
c323,c738
c323,c209
c206,c596
c743,c153
c117,c738
c360,c735
c858,c729
c743,c729
c815,c871
c117,c325
c388,c738
c357,c194
c270,c254
c9,c683
c853,c153
c84,c790
c323,c716
c388,c325
c343,c715
c611,c325
c878,c194
c703,c735
c360,c716
c360,c311
c194,c480
c743,c738
c357,c729
c858,c579
c323,c489
c357,c143
c12,c194
c360,c523
c206,c523
c611,c153
c357,c209
c270,c89
c12,c523
c853,c209
c194,c153
c12,c735
c853,c729
c785,c480
c12,c325
c360,c209
c194,c523
c853,c219
c716,c489
c611,c716
c194,c40
c12,c716
c858,c219
c117,c579
c360,c325
c878,c143
c858,c143
c743,c311
c139,c115
c295,c238
c853,c489
c360,c480
c586,c715
c878,c738
c858,c40
c743,c209
c611,c480
c586,c209
c858,c311
c586,c489
c357,c40
c139,c489
c206,c325
c21,c108
c703,c219
c716,c311
c785,c209
c611,c209
c858,c115
c611,c738
c853,c40
c268,c79
c785,c579
c360,c738
c323,c729
c388,c735
c206,c716
c586,c40
c117,c153
c878,c40
c743,c735
c703,c729
c716,c729
c206,c729
c357,c735
c785,c115
c785,c735
c611,c596
c388,c489
c878,c729
c323,c596
c139,c209
c12,c311
c139,c311
c206,c115
c743,c523
c343,c325
c611,c523
c586,c143
c552,c294
c323,c194
c129,c775
.
p8(E,E)
c311,c3
c143,c3
c88,c591
c715,c3
c489,c3
c194,c3
c567,c362
c716,c3
c196,c459
c418,c4
c744,c777
c40,c3
c715,c381
c115,c3
c738,c3
c729,c3
c153,c3
c431,c337
c735,c3
c579,c3
c794,c787
c523,c3
c219,c3
c828,c769
c209,c3
c325,c3
.
p1(E)
c395
c495
c594
c687
c778
c385
c405
c491
.
p2(E)
c619
c187
c38
c540
c660
c226
c387
c2
c75
.
p7(E,E)
c766,c346
c326,c556
c101,c517
c739,c219
c724,c601
c329,c220
c294,c552
c108,c21
c855,c673
c285,c788
c297,c747
c111,c145
c79,c747
c686,c441
c775,c129
c677,c665
c727,c768
c143,c238
c790,c84
c282,c177
c89,c270
c79,c268
c825,c413
c254,c270
c155,c334
c633,c356
c204,c332
c603,c221
c424,c173
c515,c88
c690,c109
c162,c252
c365,c493
.
p6(E,E)
c10,c545
c357,c3
c703,c3
c343,c3
c368,c559
c117,c3
c360,c3
c3,c75
c831,c419
c224,c562
c858,c3
c364,c545
c139,c3
c323,c3
c735,c657
c853,c3
c388,c3
c878,c3
c625,c232
c206,c3
c743,c3
c611,c3
c785,c3
c367,c414
c35,c253
c720,c531
c98,c803
c194,c3
c769,c337
.
p4(E,E)
c811,c228
c647,c513
c138,c261
c228,c311
c560,c162
c185,c87
c38,c23
c822,c479
c751,c426
.
p10(E,E)
c374,c803
c645,c226
c492,c94
c368,c456
c305,c867
c478,c121
c395,c351
c20,c413
c502,c563
c324,c272
.
p9(E)
c821
c619
c353
c481
c674
c299
c848
c497
.
|
D
|
//Автор Кристофер Миллер. Переработано для Динрус Виталием Кулич.
//Библиотека визуальных конпонентов VIZ (первоначально DFL).
module viz.listbox;
private import viz.x.dlib;
private import viz.x.winapi, viz.control, viz.base, viz.app;
private import viz.drawing, viz.event, viz.collections;
private extern(C) ук memmove(проц*, проц*, т_мера len);
private extern(Windows) проц _initListbox();
alias СтроковыйОбъект ListString;
abstract class УпрЭлтСписок: СуперКлассУпрЭлта // docmain
{
final Ткст getItemText(Объект item)
{
return дайТкстОбъекта(item);
}
//СобОбработчик selectedValueChanged;
Событие!(УпрЭлтСписок, АргиСоб) selectedValueChanged;
abstract проц выбранныйИндекс(цел idx); // setter
abstract цел выбранныйИндекс(); // getter
abstract проц выбранноеЗначение(Объект val); // setter
abstract проц выбранноеЗначение(Ткст str); // setter
abstract Объект выбранноеЗначение(); // getter
static Цвет дефЦветФона() // getter
{
return СистемныеЦвета.окно;
}
override Цвет цветФона() // getter
{
if(Цвет.пуст == цвфона)
return дефЦветФона;
return цвфона;
}
alias УпрЭлт.цветФона цветФона; // Overload.
static Цвет дефЦветПП() //getter
{
return СистемныеЦвета.текстОкна;
}
override Цвет цветПП() // getter
{
if(Цвет.пуст == цвпп)
return дефЦветПП;
return цвпп;
}
alias УпрЭлт.цветПП цветПП; // Overload.
this()
{
}
protected:
проц onSelectedValueChanged(АргиСоб ea)
{
selectedValueChanged(this, ea);
}
// Index change causes the значение to be изменено.
проц onSelectedIndexChanged(АргиСоб ea)
{
onSelectedValueChanged(ea); // This appears to be correct.
}
}
enum SelectionMode: ббайт
{
ONE, НЕУК,
MULTI_SIMPLE,
MULTI_EXTENDED,
}
class ListBox: УпрЭлтСписок // docmain
{
static class SelectedIndexCollection
{
deprecated alias length count;
цел length() // getter
{
if(!lbox.созданУказатель_ли)
return 0;
if(lbox.isMultSel())
{
return lbox.prevwproc(LB_GETSELCOUNT, 0, 0);
}
else
{
return (lbox.выбранныйИндекс == -1) ? 0 : 1;
}
}
цел opIndex(цел idx)
{
foreach(цел onidx; this)
{
if(!idx)
return onidx;
idx--;
}
// If it's not found it's out of границы and bad things happen.
assert(0);
return -1;
}
бул содержит(цел idx)
{
return индексУ(idx) != -1;
}
цел индексУ(цел idx)
{
цел i = 0;
foreach(цел onidx; this)
{
if(onidx == idx)
return i;
i++;
}
return -1;
}
цел opApply(цел delegate(inout цел) дг)
{
цел результат = 0;
if(lbox.isMultSel())
{
цел[] элты;
элты = new цел[length];
if(элты.length != lbox.prevwproc(LB_GETSELITEMS, элты.length, cast(LPARAM)cast(цел*)элты))
throw new ВизИскл("Unable to enumerate selected list элты");
foreach(цел _idx; элты)
{
цел idx = _idx; // Prevent inout.
результат = дг(idx);
if(результат)
break;
}
}
else
{
цел idx;
idx = lbox.выбранныйИндекс;
if(-1 != idx)
результат = дг(idx);
}
return результат;
}
mixin OpApplyAddIndex!(opApply, цел);
protected this(ListBox lb)
{
lbox = lb;
}
package:
ListBox lbox;
}
static class SelectedObjectCollection
{
deprecated alias length count;
цел length() // getter
{
if(!lbox.созданУказатель_ли)
return 0;
if(lbox.isMultSel())
{
return lbox.prevwproc(LB_GETSELCOUNT, 0, 0);
}
else
{
return (lbox.выбранныйИндекс == -1) ? 0 : 1;
}
}
Объект opIndex(цел idx)
{
foreach(Объект объ; this)
{
if(!idx)
return объ;
idx--;
}
// If it's not found it's out of границы and bad things happen.
assert(0);
return пусто;
}
бул содержит(Объект объ)
{
return индексУ(объ) != -1;
}
бул содержит(Ткст str)
{
return индексУ(str) != -1;
}
цел индексУ(Объект объ)
{
цел idx = 0;
foreach(Объект onobj; this)
{
if(onobj == объ) // Not using is.
return idx;
idx++;
}
return -1;
}
цел индексУ(Ткст str)
{
цел idx = 0;
foreach(Объект onobj; this)
{
//if(дайТкстОбъекта(onobj) is str && дайТкстОбъекта(onobj).length == str.length)
if(дайТкстОбъекта(onobj) == str)
return idx;
idx++;
}
return -1;
}
private цел myOpApply(цел delegate(inout Объект) дг)
{
цел результат = 0;
if(lbox.isMultSel())
{
цел[] элты;
элты = new цел[length];
if(элты.length != lbox.prevwproc(LB_GETSELITEMS, элты.length, cast(LPARAM)cast(цел*)элты))
throw new ВизИскл("Unable to enumerate selected list элты");
foreach(цел idx; элты)
{
Объект объ;
объ = lbox.элты[idx];
результат = дг(объ);
if(результат)
break;
}
}
else
{
Объект объ;
объ = lbox.выбранныйПункт;
if(объ)
результат = дг(объ);
}
return результат;
}
private цел myOpApply(цел delegate(inout Ткст) дг)
{
цел результат = 0;
if(lbox.isMultSel())
{
цел[] элты;
элты = new цел[length];
if(элты.length != lbox.prevwproc(LB_GETSELITEMS, элты.length, cast(LPARAM)cast(цел*)элты))
throw new ВизИскл("Unable to enumerate selected list элты");
foreach(цел idx; элты)
{
Ткст str;
str = дайТкстОбъекта(lbox.элты[idx]);
результат = дг(str);
if(результат)
break;
}
}
else
{
Объект объ;
Ткст str;
объ = lbox.выбранныйПункт;
if(объ)
{
str = дайТкстОбъекта(объ);
результат = дг(str);
}
}
return результат;
}
mixin OpApplyAddIndex!(myOpApply, Ткст);
mixin OpApplyAddIndex!(myOpApply, Объект);
// Had to do it this way because: DMD 1.028: -H is broken for mixin identifiers
// Note that this way probably prevents opApply from being overridden.
alias myOpApply opApply;
protected this(ListBox lb)
{
lbox = lb;
}
package:
ListBox lbox;
}
const цел DEFAULT_ITEM_HEIGHT = 13;
const цел NO_MATCHES = LB_ERR;
protected override Размер дефРазм() // getter
{
return Размер(120, 95);
}
проц стильКромки(ПСтильКромки bs) // setter
{
switch(bs)
{
case ПСтильКромки.ФИКС_3М:
_style(_style() & ~WS_BORDER);
_exStyle(_exStyle() | WS_EX_CLIENTEDGE);
break;
case ПСтильКромки.ФИКС_ЕДИН:
_exStyle(_exStyle() & ~WS_EX_CLIENTEDGE);
_style(_style() | WS_BORDER);
break;
case ПСтильКромки.НЕУК:
_style(_style() & ~WS_BORDER);
_exStyle(_exStyle() & ~WS_EX_CLIENTEDGE);
break;
}
if(созданУказатель_ли)
{
перерисуйПолностью();
}
}
ПСтильКромки стильКромки() // getter
{
if(_exStyle() & WS_EX_CLIENTEDGE)
return ПСтильКромки.ФИКС_3М;
else if(_style() & WS_BORDER)
return ПСтильКромки.ФИКС_ЕДИН;
return ПСтильКромки.НЕУК;
}
проц режимОтрисовки(ПРежимОтрисовки dm) // setter
{
LONG wl = _style() & ~(LBS_OWNERDRAWVARIABLE | LBS_OWNERDRAWFIXED);
switch(dm)
{
case ПРежимОтрисовки.OWNER_DRAW_VARIABLE:
wl |= LBS_OWNERDRAWVARIABLE;
break;
case ПРежимОтрисовки.OWNER_DRAW_FIXED:
wl |= LBS_OWNERDRAWFIXED;
break;
case ПРежимОтрисовки.НОРМА:
break;
}
_style(wl);
_crecreate();
}
ПРежимОтрисовки режимОтрисовки() // getter
{
LONG wl = _style();
if(wl & LBS_OWNERDRAWVARIABLE)
return ПРежимОтрисовки.OWNER_DRAW_VARIABLE;
if(wl & LBS_OWNERDRAWFIXED)
return ПРежимОтрисовки.OWNER_DRAW_FIXED;
return ПРежимОтрисовки.НОРМА;
}
final проц horizontalExtent(цел he) // setter
{
if(созданУказатель_ли)
prevwproc(LB_SETHORIZONTALEXTENT, he, 0);
hextent = he;
}
final цел horizontalExtent() // getter
{
if(созданУказатель_ли)
hextent = cast(цел)prevwproc(LB_GETHORIZONTALEXTENT, 0, 0);
return hextent;
}
final проц horizontalScrollbar(бул подтвержд) // setter
{
if(подтвержд)
_style(_style() | WS_HSCROLL);
else
_style(_style() & ~WS_HSCROLL);
_crecreate();
}
final бул horizontalScrollbar() // getter
{
return (_style() & WS_HSCROLL) != 0;
}
final проц интегральнаяВысота(бул подтвержд) //setter
{
if(подтвержд)
_style(_style() & ~LBS_NOINTEGRALHEIGHT);
else
_style(_style() | LBS_NOINTEGRALHEIGHT);
_crecreate();
}
final бул интегральнаяВысота() // getter
{
return (_style() & LBS_NOINTEGRALHEIGHT) == 0;
}
// This function has нет эффект if the ПРежимОтрисовки is OWNER_DRAW_VARIABLE.
final проц высотаПункта(цел h) // setter
{
if(режимОтрисовки == ПРежимОтрисовки.OWNER_DRAW_VARIABLE)
return;
iheight = h;
if(созданУказатель_ли)
prevwproc(LB_SETITEMHEIGHT, 0, MAKELPARAM(h, 0));
}
// Return значение is meaningless when ПРежимОтрисовки is OWNER_DRAW_VARIABLE.
final цел высотаПункта() // getter
{
// Requesting it like this when хозяин рисуй variable doesn't work.
/+
if(!созданУказатель_ли)
return iheight;
цел результат = prevwproc(LB_GETITEMHEIGHT, 0, 0);
if(результат == LB_ERR)
результат = iheight; // ?
else
iheight = результат;
return результат;
+/
return iheight;
}
final ObjectCollection элты() // getter
{
return icollection;
}
final проц multiColumn(бул подтвержд) // setter
{
// TODO: is this the correct implementation?
if(подтвержд)
_style(_style() | LBS_MULTICOLUMN | WS_HSCROLL);
else
_style(_style() & ~(LBS_MULTICOLUMN | WS_HSCROLL));
_crecreate();
}
final бул multiColumn() // getter
{
return (_style() & LBS_MULTICOLUMN) != 0;
}
final проц scrollAlwaysVisible(бул подтвержд) // setter
{
if(подтвержд)
_style(_style() | LBS_DISABLENOSCROLL);
else
_style(_style() & ~LBS_DISABLENOSCROLL);
_crecreate();
}
final бул scrollAlwaysVisible() // getter
{
return (_style() & LBS_DISABLENOSCROLL) != 0;
}
override проц выбранныйИндекс(цел idx) // setter
{
if(созданУказатель_ли)
{
if(isMultSel())
{
if(idx == -1)
{
// Remove все selection.
// Not working право.
//prevwproc(LB_SELITEMRANGE, нет, MAKELPARAM(0, ushort.max));
// Get the indices directly because deselecting them during
// selidxcollection.foreach could screw it up.
цел[] элты;
элты = new цел[selidxcollection.length];
if(элты.length != prevwproc(LB_GETSELITEMS, элты.length, cast(LPARAM)cast(цел*)элты))
throw new ВизИскл("Unable to сотри selected list элты");
foreach(цел _idx; элты)
{
prevwproc(LB_SETSEL, нет, _idx);
}
}
else
{
// ?
prevwproc(LB_SETSEL, да, idx);
}
}
else
{
prevwproc(LB_SETCURSEL, idx, 0);
}
}
}
override цел выбранныйИндекс() // getter
{
if(созданУказатель_ли)
{
if(isMultSel())
{
if(selidxcollection.length)
return selidxcollection[0];
}
else
{
LRESULT результат;
результат = prevwproc(LB_GETCURSEL, 0, 0);
if(LB_ERR != результат) // Redundant.
return cast(цел)результат;
}
}
return -1;
}
final проц выбранныйПункт(Объект o) // setter
{
цел i;
i = элты.индексУ(o);
if(i != -1)
выбранныйИндекс = i;
}
final проц выбранныйПункт(Ткст str) // setter
{
цел i;
i = элты.индексУ(str);
if(i != -1)
выбранныйИндекс = i;
}
final Объект выбранныйПункт() // getter
{
цел idx;
idx = выбранныйИндекс;
if(idx == -1)
return пусто;
return элты[idx];
}
override проц выбранноеЗначение(Объект val) // setter
{
выбранныйПункт = val;
}
override проц выбранноеЗначение(Ткст str) // setter
{
выбранныйПункт = str;
}
override Объект выбранноеЗначение() // getter
{
return выбранныйПункт;
}
final SelectedIndexCollection selectedIndices() // getter
{
return selidxcollection;
}
final SelectedObjectCollection selectedItems() // getter
{
return selobjcollection;
}
проц selectionMode(SelectionMode selmode) // setter
{
LONG wl = _style() & ~(LBS_NOSEL | LBS_EXTENDEDSEL | LBS_MULTIPLESEL);
switch(selmode)
{
case SelectionMode.ONE:
break;
case SelectionMode.MULTI_SIMPLE:
wl |= LBS_MULTIPLESEL;
break;
case SelectionMode.MULTI_EXTENDED:
wl |= LBS_EXTENDEDSEL;
break;
case SelectionMode.НЕУК:
wl |= LBS_NOSEL;
break;
}
_style(wl);
_crecreate();
}
SelectionMode selectionMode() // getter
{
LONG wl = _style();
if(wl & LBS_NOSEL)
return SelectionMode.НЕУК;
if(wl & LBS_EXTENDEDSEL)
return SelectionMode.MULTI_EXTENDED;
if(wl & LBS_MULTIPLESEL)
return SelectionMode.MULTI_SIMPLE;
return SelectionMode.ONE;
}
final проц сортированный(бул подтвержд) // setter
{
/+
if(подтвержд)
_style(_style() | LBS_SORT);
else
_style(_style() & ~LBS_SORT);
+/
_sorting = подтвержд;
}
final бул сортированный() // getter
{
//return (_style() & LBS_SORT) != 0;
return _sorting;
}
final проц topIndex(цел idx) // setter
{
if(созданУказатель_ли)
prevwproc(LB_SETTOPINDEX, idx, 0);
}
final цел topIndex() // getter
{
if(созданУказатель_ли)
return prevwproc(LB_GETTOPINDEX, 0, 0);
return 0;
}
final проц useTabStops(бул подтвержд) // setter
{
if(подтвержд)
_style(_style() | LBS_USETABSTOPS);
else
_style(_style() & ~LBS_USETABSTOPS);
_crecreate();
}
final бул useTabStops() // getter
{
return (_style() & LBS_USETABSTOPS) != 0;
}
final проц начниОбновление()
{
prevwproc(WM_SETREDRAW, нет, 0);
}
final проц завершиОбновление()
{
prevwproc(WM_SETREDRAW, да, 0);
инвалидируй(да); // покажи updates.
}
package final бул isMultSel()
{
return (_style() & (LBS_EXTENDEDSEL | LBS_MULTIPLESEL)) != 0;
}
final проц clearSelected()
{
if(создан)
выбранныйИндекс = -1;
}
final цел найдиТекст(Ткст str, цел начИндекс)
{
// TODO: найди string if упрэлт not создан ?
цел результат = NO_MATCHES;
if(создан)
{
if(viz.x.utf.использоватьЮникод)
результат = prevwproc(LB_FINDSTRING, начИндекс, cast(LPARAM)viz.x.utf.вЮни0(str));
else
результат = prevwproc(LB_FINDSTRING, начИндекс, cast(LPARAM)viz.x.utf.небезопАнзи0(str));
if(результат == LB_ERR) // Redundant.
результат = NO_MATCHES;
}
return результат;
}
final цел найдиТекст(Ткст str)
{
return найдиТекст(str, -1); // Start at beginning.
}
final цел найдиТекстСтрого(Ткст str, цел начИндекс)
{
// TODO: найди string if упрэлт not создан ?
цел результат = NO_MATCHES;
if(создан)
{
if(viz.x.utf.использоватьЮникод)
результат = prevwproc(LB_FINDSTRINGEXACT, начИндекс, cast(LPARAM)viz.x.utf.вЮни0(str));
else
результат = prevwproc(LB_FINDSTRINGEXACT, начИндекс, cast(LPARAM)viz.x.utf.небезопАнзи0(str));
if(результат == LB_ERR) // Redundant.
результат = NO_MATCHES;
}
return результат;
}
final цел найдиТекстСтрого(Ткст str)
{
return найдиТекстСтрого(str, -1); // Start at beginning.
}
final цел дайВысотуПункта(цел idx)
{
цел результат = prevwproc(LB_GETITEMHEIGHT, idx, 0);
if(LB_ERR == результат)
throw new ВизИскл("Unable to obtain item высота");
return результат;
}
final Прям getItemRectangle(цел idx)
{
RECT rect;
if(LB_ERR == prevwproc(LB_GETITEMRECT, idx, cast(LPARAM)&rect))
{
//if(idx >= 0 && idx < элты.length)
return Прям(0, 0, 0, 0); // ?
//throw new ВизИскл("Unable to obtain item rectangle");
}
return Прям(&rect);
}
final бул getSelected(цел idx)
{
return prevwproc(LB_GETSEL, idx, 0) > 0;
}
final цел indexFromPoint(цел ш, цел в)
{
// LB_ITEMFROMPOINT is "nearest", so also check with the item rectangle to
// see if the Точка is directly in the item.
// Maybe use LBItemFromPt() from common упрэлты.
цел результат = NO_MATCHES;
if(создан)
{
результат = prevwproc(LB_ITEMFROMPOINT, 0, MAKELPARAM(ш, в));
if(!HIWORD(результат)) // In client area
{
//результат = LOWORD(результат); // High word already 0.
if(результат < 0 || !getItemRectangle(результат).содержит(ш, в))
результат = NO_MATCHES;
}
else // Outside client area.
{
результат = NO_MATCHES;
}
}
return результат;
}
final цел indexFromPoint(Точка тчк)
{
return indexFromPoint(тчк.ш, тчк.в);
}
final проц setSelected(цел idx, бул подтвержд)
{
if(создан)
prevwproc(LB_SETSEL, подтвержд, idx);
}
protected ObjectCollection createItemCollection()
{
return new ObjectCollection(this);
}
проц sort()
{
if(icollection._items.length)
{
Объект[] itemscopy;
itemscopy = icollection._items.dup;
itemscopy.sort;
элты.сотри();
начниОбновление();
scope(exit)
завершиОбновление();
foreach(цел i, Объект o; itemscopy)
{
элты.вставь(i, o);
}
}
}
static class ObjectCollection
{
protected this(ListBox lbox)
{
this.lbox = lbox;
}
protected this(ListBox lbox, Объект[] range)
{
this.lbox = lbox;
добавьДиапазон(range);
}
protected this(ListBox lbox, Ткст[] range)
{
this.lbox = lbox;
добавьДиапазон(range);
}
/+
protected this(ListBox lbox, ObjectCollection range)
{
this.lbox = lbox;
добавьДиапазон(range);
}
+/
проц добавь(Объект значение)
{
add2(значение);
}
проц добавь(Ткст значение)
{
добавь(new ListString(значение));
}
проц добавьДиапазон(Объект[] range)
{
if(lbox.сортированный)
{
foreach(Объект значение; range)
{
добавь(значение);
}
}
else
{
_wraparray.добавьДиапазон(range);
}
}
проц добавьДиапазон(Ткст[] range)
{
foreach(Ткст значение; range)
{
добавь(значение);
}
}
private:
ListBox lbox;
Объект[] _items;
LRESULT insert2(WPARAM idx, Ткст val)
{
вставь(idx, val);
return idx;
}
LRESULT add2(Объект val)
{
цел i;
if(lbox.сортированный)
{
for(i = 0; i != _items.length; i++)
{
if(val < _items[i])
break;
}
}
else
{
i = _items.length;
}
вставь(i, val);
return i;
}
LRESULT add2(Ткст val)
{
return add2(new ListString(val));
}
проц _added(т_мера idx, Объект val)
{
if(lbox.создан)
{
if(viz.x.utf.использоватьЮникод)
lbox.prevwproc(LB_INSERTSTRING, idx, cast(LPARAM)viz.x.utf.вЮни0(дайТкстОбъекта(val)));
else
lbox.prevwproc(LB_INSERTSTRING, idx, cast(LPARAM)viz.x.utf.вАнзи0(дайТкстОбъекта(val))); // Can this be небезопАнзи0()?
}
}
проц _removed(т_мера idx, Объект val)
{
if(т_мера.max == idx) // Clear все.
{
if(lbox.создан)
{
lbox.prevwproc(LB_RESETCONTENT, 0, 0);
}
}
else
{
if(lbox.создан)
{
lbox.prevwproc(LB_DELETESTRING, cast(WPARAM)idx, 0);
}
}
}
public:
mixin ListWrapArray!(Объект, _items,
_blankListCallback!(Объект), _added,
_blankListCallback!(Объект), _removed,
да, нет, нет) _wraparray;
}
this()
{
_initListbox();
// Default useTabStops and vertical scrolling.
окСтиль |= WS_TABSTOP | LBS_USETABSTOPS | LBS_HASSTRINGS | WS_VSCROLL | LBS_NOTIFY;
окДопСтиль |= WS_EX_CLIENTEDGE;
ктрлСтиль |= ПСтилиУпрЭлта.ВЫДЕЛЕНИЕ;
окСтильКласса = стильКлассаЛистБокс;
icollection = createItemCollection();
selidxcollection = new SelectedIndexCollection(this);
selobjcollection = new SelectedObjectCollection(this);
}
protected override проц поСозданиюУказателя(АргиСоб ea)
{
super.поСозданиюУказателя(ea);
// Set the Ctrl ID to the УОК so that it is unique
// and WM_MEASUREITEM will work properly.
SetWindowLongA(уок, GWL_ID, cast(LONG)уок);
if(hextent != 0)
prevwproc(LB_SETHORIZONTALEXTENT, hextent, 0);
if(iheight != DEFAULT_ITEM_HEIGHT)
prevwproc(LB_SETITEMHEIGHT, 0, MAKELPARAM(iheight, 0));
Сообщение m;
m.уок = указатель;
m.сооб = LB_INSERTSTRING;
// Note: duplicate code.
if(viz.x.utf.использоватьЮникод)
{
foreach(цел i, Объект объ; icollection._items)
{
m.парам1 = i;
m.парам2 = cast(LPARAM)viz.x.utf.вЮни0(дайТкстОбъекта(объ)); // <--
предшОкПроц(m);
//if(LB_ERR == m.результат || LB_ERRSPACE == m.результат)
if(m.результат < 0)
throw new ВизИскл("Unable to добавь list item");
//prevwproc(LB_SETITEMDATA, m.результат, cast(LPARAM)cast(проц*)объ);
}
}
else
{
foreach(цел i, Объект объ; icollection._items)
{
m.парам1 = i;
m.парам2 = cast(LPARAM)viz.x.utf.вАнзи0(дайТкстОбъекта(объ)); // Can this be небезопАнзи0? // <--
предшОкПроц(m);
//if(LB_ERR == m.результат || LB_ERRSPACE == m.результат)
if(m.результат < 0)
throw new ВизИскл("Unable to добавь list item");
//prevwproc(LB_SETITEMDATA, m.результат, cast(LPARAM)cast(проц*)объ);
}
}
//перерисуйПолностью();
}
/+
override проц создайУказатель()
{
if(созданУказатель_ли)
return;
создайУказательНаКласс(LISTBOX_CLASSNAME);
поСозданиюУказателя(АргиСоб.пуст);
}
+/
protected override проц создайПараметры(inout ПарамыСозд cp)
{
super.создайПараметры(cp);
cp.имяКласса = LISTBOX_CLASSNAME;
}
//DrawItemEventHandler drawItem;
Событие!(ListBox, АргиСобПеретягаДанных) drawItem; //MeasureItemEventHandler measureItem;
Событие!(ListBox, АргиСобИзмеренияЭлемента) measureItem;
protected:
проц onDrawItem(АргиСобПеретягаДанных dieh)
{
drawItem(this, dieh);
}
проц onMeasureItem(АргиСобИзмеренияЭлемента miea)
{
measureItem(this, miea);
}
package final проц _WmDrawItem(DRAWITEMSTRUCT* dis)
in
{
assert(dis.hwndItem == указатель);
assert(dis.CtlType == ODT_LISTBOX);
}
body
{
ПСостОтрисовкиЭлемента состояние;
состояние = cast(ПСостОтрисовкиЭлемента)dis.itemState;
if(dis.itemID == -1)
{
FillRect(dis.hDC, &dis.rcItem, hbrBg);
if(состояние & ПСостОтрисовкиЭлемента.ФОКУС)
DrawFocusRect(dis.hDC, &dis.rcItem);
}
else
{
АргиСобПеретягаДанных diea;
Цвет bc, fc;
if(состояние & ПСостОтрисовкиЭлемента.ВЫДЕЛЕНО)
{
bc = Цвет.системныйЦвет(COLOR_HIGHLIGHT);
fc = Цвет.системныйЦвет(COLOR_HIGHLIGHTTEXT);
}
else
{
bc = цветФона;
fc = цветПП;
}
prepareDc(dis.hDC);
diea = new АргиСобПеретягаДанных(new Графика(dis.hDC, нет), окШрифт,
Прям(&dis.rcItem), dis.itemID, состояние, fc, bc);
onDrawItem(diea);
}
}
package final проц _WmMeasureItem(MEASUREITEMSTRUCT* mis)
in
{
assert(mis.CtlType == ODT_LISTBOX);
}
body
{
АргиСобИзмеренияЭлемента miea;
scope Графика gpx = new ОбщаяГрафика(указатель(), GetDC(указатель));
miea = new АргиСобИзмеренияЭлемента(gpx, mis.itemID, /+ mis.высотаПункта +/ iheight);
miea.ширинаЭлемента = mis.ширинаЭлемента;
onMeasureItem(miea);
mis.высотаПункта = miea.высотаПункта;
mis.ширинаЭлемента = miea.ширинаЭлемента;
}
override проц предшОкПроц(inout Сообщение сооб)
{
//сооб.результат = CallWindowProcA(первОкПроцЛистБокса, сооб.уок, сооб.сооб, сооб.парам1, сооб.парам2);
сооб.результат = viz.x.utf.вызовиОкПроц(первОкПроцЛистБокса, сооб.уок, сооб.сооб, сооб.парам1, сооб.парам2);
}
protected override проц поОбратномуСообщению(inout Сообщение m)
{
super.поОбратномуСообщению(m);
switch(m.сооб)
{
case WM_DRAWITEM:
_WmDrawItem(cast(DRAWITEMSTRUCT*)m.парам2);
m.результат = 1;
break;
case WM_MEASUREITEM:
_WmMeasureItem(cast(MEASUREITEMSTRUCT*)m.парам2);
m.результат = 1;
break;
case WM_COMMAND:
assert(cast(УОК)m.парам2 == указатель);
switch(HIWORD(m.парам1))
{
case LBN_SELCHANGE:
onSelectedIndexChanged(АргиСоб.пуст);
break;
case LBN_SELCANCEL:
onSelectedIndexChanged(АргиСоб.пуст);
break;
default: ;
}
break;
default: ;
}
}
override проц окПроц(inout Сообщение сооб)
{
switch(сооб.сооб)
{
case LB_ADDSTRING:
//сооб.результат = icollection.add2(вТкст(cast(ткст0)сооб.парам2).dup); // TODO: fix.
//сооб.результат = icollection.add2(вТкст(cast(ткст0)сооб.парам2).idup); // TODO: fix. // Needed in D2. Doesn't work in D1.
сооб.результат = icollection.add2(cast(Ткст)вТкст(cast(ткст0)сооб.парам2).dup); // TODO: fix. // Needed in D2.
return;
case LB_INSERTSTRING:
//сооб.результат = icollection.insert2(сооб.парам1, вТкст(cast(ткст0)сооб.парам2).dup); // TODO: fix.
//сооб.результат = icollection.insert2(сооб.парам1, вТкст(cast(ткст0)сооб.парам2).idup); // TODO: fix. // Needed in D2. Doesn't work in D1.
сооб.результат = icollection.insert2(сооб.парам1, cast(Ткст)вТкст(cast(ткст0)сооб.парам2).dup); // TODO: fix. // Needed in D2.
return;
case LB_DELETESTRING:
icollection.удалиПо(сооб.парам1);
сооб.результат = icollection.length;
return;
case LB_RESETCONTENT:
icollection.сотри();
return;
case LB_SETITEMDATA:
// Cannot установи item данные from outside DFL.
сооб.результат = LB_ERR;
return;
case LB_ADDFILE:
сооб.результат = LB_ERR;
return;
case LB_DIR:
сооб.результат = LB_ERR;
return;
default:
super.окПроц(сооб);
return;
}
предшОкПроц(сооб);
}
private:
цел hextent = 0;
цел iheight = DEFAULT_ITEM_HEIGHT;
ObjectCollection icollection;
SelectedIndexCollection selidxcollection;
SelectedObjectCollection selobjcollection;
бул _sorting = нет;
package:
final:
LRESULT prevwproc(UINT сооб, WPARAM wparam, LPARAM lparam)
{
//return CallWindowProcA(первОкПроцЛиствью, уок, сооб, wparam, lparam);
return viz.x.utf.вызовиОкПроц(первОкПроцЛистБокса, уок, сооб, wparam, lparam);
}
}
|
D
|
/*
* This file was automatically generated by sel-utils and
* released under the MIT License.
*
* License: https://github.com/sel-project/sel-utils/blob/master/LICENSE
* Repository: https://github.com/sel-project/sel-utils
* Generated from https://github.com/sel-project/sel-utils/blob/master/xml/protocol/java315.xml
*/
module sul.protocol.java315.clientbound;
import std.bitmanip : write, peek;
static import std.conv;
import std.system : Endian;
import std.typetuple : TypeTuple;
import std.typecons : Tuple;
import std.uuid : UUID;
import sul.utils.buffer;
import sul.utils.var;
static import sul.protocol.java315.types;
static if(__traits(compiles, { import sul.metadata.java315; })) import sul.metadata.java315;
alias Packets = TypeTuple!(SpawnObject, SpawnExperienceOrb, SpawnGlobalEntity, SpawnMob, SpawnPainting, SpawnPlayer, Animation, Statistics, BlockBreakAnimation, UpdateBlockEntity, BlockAction, BlockChange, BossBar, ServerDifficulty, TabComplete, ChatMessage, MultiBlockChange, ConfirmTransaction, CloseWindow, OpenWindow, WindowItems, WindowProperty, SetSlot, SetCooldown, PluginMessage, NamedSoundEffect, Disconnect, EntityStatus, Explosion, UnloadChunk, ChangeGameState, KeepAlive, ChunkData, Effect, Particle, JoinGame, Map, EntityRelativeMove, EntityLookAndRelativeMove, EntityLook, Entity, VehicleMove, OpenSignEditor, PlayerAbilities, CombatEvent, PlayerListItem, PlayerPositionAndLook, UseBed, DestroyEntities, RemoveEntityEffect, ResourcePackSend, Respawn, EntityHeadLook, WorldBorder, Camera, HeldItemChange, DisplayScoreboard, EntityMetadata, AttachEntity, EntityVelocity, EntityEquipment, SetExperience, UpdateHealth, ScoreboardObjective, SetPassengers, Teams, UpdateScore, SpawnPosition, TimeUpdate, Title, SoundEffect, PlayerListHeaderAndFooter, CollectItem, EntityTeleport, EntityProperties, EntityEffect);
class SpawnObject : Buffer {
public enum uint ID = 0;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId", "uuid", "type", "position", "pitch", "yaw", "data", "velocity"];
public uint entityId;
public UUID uuid;
public ubyte type;
public Tuple!(double, "x", double, "y", double, "z") position;
public ubyte pitch;
public ubyte yaw;
public int data;
public Tuple!(short, "x", short, "y", short, "z") velocity;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, UUID uuid=UUID.init, ubyte type=ubyte.init, Tuple!(double, "x", double, "y", double, "z") position=Tuple!(double, "x", double, "y", double, "z").init, ubyte pitch=ubyte.init, ubyte yaw=ubyte.init, int data=int.init, Tuple!(short, "x", short, "y", short, "z") velocity=Tuple!(short, "x", short, "y", short, "z").init) {
this.entityId = entityId;
this.uuid = uuid;
this.type = type;
this.position = position;
this.pitch = pitch;
this.yaw = yaw;
this.data = data;
this.velocity = velocity;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBytes(uuid.data);
writeBigEndianUbyte(type);
writeBigEndianDouble(position.x); writeBigEndianDouble(position.y); writeBigEndianDouble(position.z);
writeBigEndianUbyte(pitch);
writeBigEndianUbyte(yaw);
writeBigEndianInt(data);
writeBigEndianShort(velocity.x); writeBigEndianShort(velocity.y); writeBigEndianShort(velocity.z);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
if(_buffer.length>=_index+16){ ubyte[16] dvz=_buffer[_index.._index+16].dup; _index+=16; uuid=UUID(dvz); }
type=readBigEndianUbyte();
position.x=readBigEndianDouble(); position.y=readBigEndianDouble(); position.z=readBigEndianDouble();
pitch=readBigEndianUbyte();
yaw=readBigEndianUbyte();
data=readBigEndianInt();
velocity.x=readBigEndianShort(); velocity.y=readBigEndianShort(); velocity.z=readBigEndianShort();
}
public static pure nothrow @safe SpawnObject fromBuffer(bool readId=true)(ubyte[] buffer) {
SpawnObject ret = new SpawnObject();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "SpawnObject(entityId: " ~ std.conv.to!string(this.entityId) ~ ", uuid: " ~ std.conv.to!string(this.uuid) ~ ", type: " ~ std.conv.to!string(this.type) ~ ", position: " ~ std.conv.to!string(this.position) ~ ", pitch: " ~ std.conv.to!string(this.pitch) ~ ", yaw: " ~ std.conv.to!string(this.yaw) ~ ", data: " ~ std.conv.to!string(this.data) ~ ", velocity: " ~ std.conv.to!string(this.velocity) ~ ")";
}
}
class SpawnExperienceOrb : Buffer {
public enum uint ID = 1;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId", "position", "count"];
public uint entityId;
public Tuple!(double, "x", double, "y", double, "z") position;
public ushort count;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, Tuple!(double, "x", double, "y", double, "z") position=Tuple!(double, "x", double, "y", double, "z").init, ushort count=ushort.init) {
this.entityId = entityId;
this.position = position;
this.count = count;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBigEndianDouble(position.x); writeBigEndianDouble(position.y); writeBigEndianDouble(position.z);
writeBigEndianUshort(count);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
position.x=readBigEndianDouble(); position.y=readBigEndianDouble(); position.z=readBigEndianDouble();
count=readBigEndianUshort();
}
public static pure nothrow @safe SpawnExperienceOrb fromBuffer(bool readId=true)(ubyte[] buffer) {
SpawnExperienceOrb ret = new SpawnExperienceOrb();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "SpawnExperienceOrb(entityId: " ~ std.conv.to!string(this.entityId) ~ ", position: " ~ std.conv.to!string(this.position) ~ ", count: " ~ std.conv.to!string(this.count) ~ ")";
}
}
class SpawnGlobalEntity : Buffer {
public enum uint ID = 2;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// type
public enum ubyte THUNDERBOLT = 1;
public enum string[] FIELDS = ["entityId", "type", "position"];
public uint entityId;
public ubyte type;
public Tuple!(double, "x", double, "y", double, "z") position;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, ubyte type=ubyte.init, Tuple!(double, "x", double, "y", double, "z") position=Tuple!(double, "x", double, "y", double, "z").init) {
this.entityId = entityId;
this.type = type;
this.position = position;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBigEndianUbyte(type);
writeBigEndianDouble(position.x); writeBigEndianDouble(position.y); writeBigEndianDouble(position.z);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
type=readBigEndianUbyte();
position.x=readBigEndianDouble(); position.y=readBigEndianDouble(); position.z=readBigEndianDouble();
}
public static pure nothrow @safe SpawnGlobalEntity fromBuffer(bool readId=true)(ubyte[] buffer) {
SpawnGlobalEntity ret = new SpawnGlobalEntity();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "SpawnGlobalEntity(entityId: " ~ std.conv.to!string(this.entityId) ~ ", type: " ~ std.conv.to!string(this.type) ~ ", position: " ~ std.conv.to!string(this.position) ~ ")";
}
}
class SpawnMob : Buffer {
public enum uint ID = 3;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId", "uuid", "type", "position", "yaw", "pitch", "headPitch", "velocity", "metadata"];
public uint entityId;
public UUID uuid;
public uint type;
public Tuple!(double, "x", double, "y", double, "z") position;
public ubyte yaw;
public ubyte pitch;
public ubyte headPitch;
public Tuple!(short, "x", short, "y", short, "z") velocity;
public Metadata metadata;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, UUID uuid=UUID.init, uint type=uint.init, Tuple!(double, "x", double, "y", double, "z") position=Tuple!(double, "x", double, "y", double, "z").init, ubyte yaw=ubyte.init, ubyte pitch=ubyte.init, ubyte headPitch=ubyte.init, Tuple!(short, "x", short, "y", short, "z") velocity=Tuple!(short, "x", short, "y", short, "z").init, Metadata metadata=Metadata.init) {
this.entityId = entityId;
this.uuid = uuid;
this.type = type;
this.position = position;
this.yaw = yaw;
this.pitch = pitch;
this.headPitch = headPitch;
this.velocity = velocity;
this.metadata = metadata;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBytes(uuid.data);
writeBytes(varuint.encode(type));
writeBigEndianDouble(position.x); writeBigEndianDouble(position.y); writeBigEndianDouble(position.z);
writeBigEndianUbyte(yaw);
writeBigEndianUbyte(pitch);
writeBigEndianUbyte(headPitch);
writeBigEndianShort(velocity.x); writeBigEndianShort(velocity.y); writeBigEndianShort(velocity.z);
metadata.encode(bufferInstance);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
if(_buffer.length>=_index+16){ ubyte[16] dvz=_buffer[_index.._index+16].dup; _index+=16; uuid=UUID(dvz); }
type=varuint.decode(_buffer, &_index);
position.x=readBigEndianDouble(); position.y=readBigEndianDouble(); position.z=readBigEndianDouble();
yaw=readBigEndianUbyte();
pitch=readBigEndianUbyte();
headPitch=readBigEndianUbyte();
velocity.x=readBigEndianShort(); velocity.y=readBigEndianShort(); velocity.z=readBigEndianShort();
metadata=Metadata.decode(bufferInstance);
}
public static pure nothrow @safe SpawnMob fromBuffer(bool readId=true)(ubyte[] buffer) {
SpawnMob ret = new SpawnMob();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "SpawnMob(entityId: " ~ std.conv.to!string(this.entityId) ~ ", uuid: " ~ std.conv.to!string(this.uuid) ~ ", type: " ~ std.conv.to!string(this.type) ~ ", position: " ~ std.conv.to!string(this.position) ~ ", yaw: " ~ std.conv.to!string(this.yaw) ~ ", pitch: " ~ std.conv.to!string(this.pitch) ~ ", headPitch: " ~ std.conv.to!string(this.headPitch) ~ ", velocity: " ~ std.conv.to!string(this.velocity) ~ ", metadata: " ~ std.conv.to!string(this.metadata) ~ ")";
}
}
class SpawnPainting : Buffer {
public enum uint ID = 4;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// direction
public enum ubyte SOUTH = 0;
public enum ubyte WEST = 1;
public enum ubyte NORTH = 2;
public enum ubyte EAST = 3;
public enum string[] FIELDS = ["entityId", "uuid", "title", "position", "direction"];
public uint entityId;
public UUID uuid;
public string title;
public ulong position;
public ubyte direction;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, UUID uuid=UUID.init, string title=string.init, ulong position=ulong.init, ubyte direction=ubyte.init) {
this.entityId = entityId;
this.uuid = uuid;
this.title = title;
this.position = position;
this.direction = direction;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBytes(uuid.data);
writeBytes(varuint.encode(cast(uint)title.length)); writeString(title);
writeBigEndianUlong(position);
writeBigEndianUbyte(direction);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
if(_buffer.length>=_index+16){ ubyte[16] dvz=_buffer[_index.._index+16].dup; _index+=16; uuid=UUID(dvz); }
uint dlbu=varuint.decode(_buffer, &_index); title=readString(dlbu);
position=readBigEndianUlong();
direction=readBigEndianUbyte();
}
public static pure nothrow @safe SpawnPainting fromBuffer(bool readId=true)(ubyte[] buffer) {
SpawnPainting ret = new SpawnPainting();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "SpawnPainting(entityId: " ~ std.conv.to!string(this.entityId) ~ ", uuid: " ~ std.conv.to!string(this.uuid) ~ ", title: " ~ std.conv.to!string(this.title) ~ ", position: " ~ std.conv.to!string(this.position) ~ ", direction: " ~ std.conv.to!string(this.direction) ~ ")";
}
}
class SpawnPlayer : Buffer {
public enum uint ID = 5;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId", "uuid", "position", "yaw", "pitch", "metadata"];
public uint entityId;
public UUID uuid;
public Tuple!(double, "x", double, "y", double, "z") position;
public ubyte yaw;
public ubyte pitch;
public Metadata metadata;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, UUID uuid=UUID.init, Tuple!(double, "x", double, "y", double, "z") position=Tuple!(double, "x", double, "y", double, "z").init, ubyte yaw=ubyte.init, ubyte pitch=ubyte.init, Metadata metadata=Metadata.init) {
this.entityId = entityId;
this.uuid = uuid;
this.position = position;
this.yaw = yaw;
this.pitch = pitch;
this.metadata = metadata;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBytes(uuid.data);
writeBigEndianDouble(position.x); writeBigEndianDouble(position.y); writeBigEndianDouble(position.z);
writeBigEndianUbyte(yaw);
writeBigEndianUbyte(pitch);
metadata.encode(bufferInstance);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
if(_buffer.length>=_index+16){ ubyte[16] dvz=_buffer[_index.._index+16].dup; _index+=16; uuid=UUID(dvz); }
position.x=readBigEndianDouble(); position.y=readBigEndianDouble(); position.z=readBigEndianDouble();
yaw=readBigEndianUbyte();
pitch=readBigEndianUbyte();
metadata=Metadata.decode(bufferInstance);
}
public static pure nothrow @safe SpawnPlayer fromBuffer(bool readId=true)(ubyte[] buffer) {
SpawnPlayer ret = new SpawnPlayer();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "SpawnPlayer(entityId: " ~ std.conv.to!string(this.entityId) ~ ", uuid: " ~ std.conv.to!string(this.uuid) ~ ", position: " ~ std.conv.to!string(this.position) ~ ", yaw: " ~ std.conv.to!string(this.yaw) ~ ", pitch: " ~ std.conv.to!string(this.pitch) ~ ", metadata: " ~ std.conv.to!string(this.metadata) ~ ")";
}
}
class Animation : Buffer {
public enum uint ID = 6;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// animation
public enum ubyte SWING_MAIN_ARM = 0;
public enum ubyte TAKE_DAMAGE = 1;
public enum ubyte LEAVE_BED = 2;
public enum ubyte SWING_OFFHAND = 3;
public enum ubyte CRITICAL_EFFECT = 4;
public enum ubyte MAGICAL_CRITICAL_EFFECT = 5;
public enum string[] FIELDS = ["entityId", "animation"];
public uint entityId;
public ubyte animation;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, ubyte animation=ubyte.init) {
this.entityId = entityId;
this.animation = animation;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBigEndianUbyte(animation);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
animation=readBigEndianUbyte();
}
public static pure nothrow @safe Animation fromBuffer(bool readId=true)(ubyte[] buffer) {
Animation ret = new Animation();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "Animation(entityId: " ~ std.conv.to!string(this.entityId) ~ ", animation: " ~ std.conv.to!string(this.animation) ~ ")";
}
}
class Statistics : Buffer {
public enum uint ID = 7;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["statistics"];
public sul.protocol.java315.types.Statistic[] statistics;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(sul.protocol.java315.types.Statistic[] statistics) {
this.statistics = statistics;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(cast(uint)statistics.length)); foreach(crdldlc;statistics){ crdldlc.encode(bufferInstance); }
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
statistics.length=varuint.decode(_buffer, &_index); foreach(ref crdldlc;statistics){ crdldlc.decode(bufferInstance); }
}
public static pure nothrow @safe Statistics fromBuffer(bool readId=true)(ubyte[] buffer) {
Statistics ret = new Statistics();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "Statistics(statistics: " ~ std.conv.to!string(this.statistics) ~ ")";
}
}
class BlockBreakAnimation : Buffer {
public enum uint ID = 8;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId", "position", "stage"];
public uint entityId;
public ulong position;
public ubyte stage;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, ulong position=ulong.init, ubyte stage=ubyte.init) {
this.entityId = entityId;
this.position = position;
this.stage = stage;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBigEndianUlong(position);
writeBigEndianUbyte(stage);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
position=readBigEndianUlong();
stage=readBigEndianUbyte();
}
public static pure nothrow @safe BlockBreakAnimation fromBuffer(bool readId=true)(ubyte[] buffer) {
BlockBreakAnimation ret = new BlockBreakAnimation();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "BlockBreakAnimation(entityId: " ~ std.conv.to!string(this.entityId) ~ ", position: " ~ std.conv.to!string(this.position) ~ ", stage: " ~ std.conv.to!string(this.stage) ~ ")";
}
}
class UpdateBlockEntity : Buffer {
public enum uint ID = 9;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// action
public enum ubyte MOB_SPAWNER_DATA = 1;
public enum ubyte COMMAND_BLOCK_TEXT = 2;
public enum ubyte BEACON_POWERS = 3;
public enum ubyte MOB_HEAD_DATA = 4;
public enum ubyte FLOWER_POT_FLOWER = 5;
public enum ubyte BANNER_DATA = 6;
public enum ubyte STRUCTURE_DATA = 7;
public enum ubyte END_GATEWAY_DESTINATION = 8;
public enum ubyte SIGN_TEXT = 9;
public enum ubyte SHULKER_BOX_DECLARATION = 10;
public enum string[] FIELDS = ["position", "action", "nbt"];
public ulong position;
public ubyte action;
public ubyte[] nbt;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ulong position, ubyte action=ubyte.init, ubyte[] nbt=(ubyte[]).init) {
this.position = position;
this.action = action;
this.nbt = nbt;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUlong(position);
writeBigEndianUbyte(action);
writeBytes(nbt);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
position=readBigEndianUlong();
action=readBigEndianUbyte();
nbt=_buffer[_index..$].dup; _index=_buffer.length;
}
public static pure nothrow @safe UpdateBlockEntity fromBuffer(bool readId=true)(ubyte[] buffer) {
UpdateBlockEntity ret = new UpdateBlockEntity();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "UpdateBlockEntity(position: " ~ std.conv.to!string(this.position) ~ ", action: " ~ std.conv.to!string(this.action) ~ ", nbt: " ~ std.conv.to!string(this.nbt) ~ ")";
}
}
class BlockAction : Buffer {
public enum uint ID = 10;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// action
public enum ubyte NOTE_BLOCK_HARP = 0;
public enum ubyte NOTE_BLOCK_BASS_DRUM = 1;
public enum ubyte NOTE_BLOCK_SNARE_DRUM = 2;
public enum ubyte NOTE_BLOCK_CLICKS = 3;
public enum ubyte NOTE_BLOCK_STICKS = 3;
public enum ubyte NOTE_BLOCK_BASS_GUITAR = 4;
public enum ubyte PISTON_EXTEND = 0;
public enum ubyte PISTON_RETRACT = 1;
public enum ubyte CHEST_WATCHERS = 1;
public enum ubyte BEACON_RECALCULATE = 1;
public enum ubyte MOB_SPAWNER_RESET_DELAY = 1;
public enum ubyte END_GATEWAY_YELLOW_BEAM = 1;
// parameter
public enum ubyte PISTON_DOWN = 0;
public enum ubyte PISTON_UP = 1;
public enum ubyte PISTON_SOUTH = 2;
public enum ubyte PISTON_WEST = 3;
public enum ubyte PISTON_NORTH = 4;
public enum ubyte PISTON_EAST = 5;
public enum string[] FIELDS = ["position", "action", "parameter", "blockType"];
public ulong position;
public ubyte action;
public ubyte parameter;
public uint blockType;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ulong position, ubyte action=ubyte.init, ubyte parameter=ubyte.init, uint blockType=uint.init) {
this.position = position;
this.action = action;
this.parameter = parameter;
this.blockType = blockType;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUlong(position);
writeBigEndianUbyte(action);
writeBigEndianUbyte(parameter);
writeBytes(varuint.encode(blockType));
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
position=readBigEndianUlong();
action=readBigEndianUbyte();
parameter=readBigEndianUbyte();
blockType=varuint.decode(_buffer, &_index);
}
public static pure nothrow @safe BlockAction fromBuffer(bool readId=true)(ubyte[] buffer) {
BlockAction ret = new BlockAction();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "BlockAction(position: " ~ std.conv.to!string(this.position) ~ ", action: " ~ std.conv.to!string(this.action) ~ ", parameter: " ~ std.conv.to!string(this.parameter) ~ ", blockType: " ~ std.conv.to!string(this.blockType) ~ ")";
}
}
class BlockChange : Buffer {
public enum uint ID = 11;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["position", "block"];
public ulong position;
public uint block;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ulong position, uint block=uint.init) {
this.position = position;
this.block = block;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUlong(position);
writeBytes(varuint.encode(block));
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
position=readBigEndianUlong();
block=varuint.decode(_buffer, &_index);
}
public static pure nothrow @safe BlockChange fromBuffer(bool readId=true)(ubyte[] buffer) {
BlockChange ret = new BlockChange();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "BlockChange(position: " ~ std.conv.to!string(this.position) ~ ", block: " ~ std.conv.to!string(this.block) ~ ")";
}
}
class BossBar : Buffer {
public enum uint ID = 12;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["uuid", "action"];
public UUID uuid;
public uint action;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(UUID uuid, uint action=uint.init) {
this.uuid = uuid;
this.action = action;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(uuid.data);
writeBytes(varuint.encode(action));
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
if(_buffer.length>=_index+16){ ubyte[16] dvz=_buffer[_index.._index+16].dup; _index+=16; uuid=UUID(dvz); }
action=varuint.decode(_buffer, &_index);
}
public static pure nothrow @safe BossBar fromBuffer(bool readId=true)(ubyte[] buffer) {
BossBar ret = new BossBar();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "BossBar(uuid: " ~ std.conv.to!string(this.uuid) ~ ", action: " ~ std.conv.to!string(this.action) ~ ")";
}
alias _encode = encode;
enum string variantField = "action";
alias Variants = TypeTuple!(Add, Remove, UpdateHealth, UpdateTitle, UpdateStyle, UpdateFlags);
public class Add {
public enum typeof(action) ACTION = 0;
// color
public enum uint PINK = 0;
public enum uint BLUE = 1;
public enum uint RED = 2;
public enum uint GREEN = 3;
public enum uint YELLOW = 4;
public enum uint PURPLE = 5;
public enum uint WHITE = 6;
// division
public enum uint NO_DIVISION = 0;
public enum uint SIX_NOTCHES = 1;
public enum uint TEN_NOTCHES = 2;
public enum uint TWELVE_NOTCHES = 3;
public enum uint TWENTY_NOTCHES = 4;
// flags
public enum ubyte DARK_SKY = 1;
public enum ubyte IS_DRAGON_BAR = 2;
public enum string[] FIELDS = ["title", "health", "color", "division", "flags"];
public string title;
public float health;
public uint color;
public uint division;
public ubyte flags;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string title, float health=float.init, uint color=uint.init, uint division=uint.init, ubyte flags=ubyte.init) {
this.title = title;
this.health = health;
this.color = color;
this.division = division;
this.flags = flags;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 0;
_encode!writeId();
writeBytes(varuint.encode(cast(uint)title.length)); writeString(title);
writeBigEndianFloat(health);
writeBytes(varuint.encode(color));
writeBytes(varuint.encode(division));
writeBigEndianUbyte(flags);
return _buffer;
}
public pure nothrow @safe void decode() {
uint dlbu=varuint.decode(_buffer, &_index); title=readString(dlbu);
health=readBigEndianFloat();
color=varuint.decode(_buffer, &_index);
division=varuint.decode(_buffer, &_index);
flags=readBigEndianUbyte();
}
public override string toString() {
return "BossBar.Add(title: " ~ std.conv.to!string(this.title) ~ ", health: " ~ std.conv.to!string(this.health) ~ ", color: " ~ std.conv.to!string(this.color) ~ ", division: " ~ std.conv.to!string(this.division) ~ ", flags: " ~ std.conv.to!string(this.flags) ~ ")";
}
}
public class Remove {
public enum typeof(action) ACTION = 1;
public enum string[] FIELDS = [];
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 1;
_encode!writeId();
return _buffer;
}
public pure nothrow @safe void decode() {
}
public override string toString() {
return "BossBar.Remove()";
}
}
public class UpdateHealth {
public enum typeof(action) ACTION = 2;
public enum string[] FIELDS = ["health"];
public float health;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(float health) {
this.health = health;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 2;
_encode!writeId();
writeBigEndianFloat(health);
return _buffer;
}
public pure nothrow @safe void decode() {
health=readBigEndianFloat();
}
public override string toString() {
return "BossBar.UpdateHealth(health: " ~ std.conv.to!string(this.health) ~ ")";
}
}
public class UpdateTitle {
public enum typeof(action) ACTION = 3;
public enum string[] FIELDS = ["title"];
public string title;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string title) {
this.title = title;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 3;
_encode!writeId();
writeBytes(varuint.encode(cast(uint)title.length)); writeString(title);
return _buffer;
}
public pure nothrow @safe void decode() {
uint dlbu=varuint.decode(_buffer, &_index); title=readString(dlbu);
}
public override string toString() {
return "BossBar.UpdateTitle(title: " ~ std.conv.to!string(this.title) ~ ")";
}
}
public class UpdateStyle {
public enum typeof(action) ACTION = 4;
// color
public enum uint PINK = 0;
public enum uint BLUE = 1;
public enum uint RED = 2;
public enum uint GREEN = 3;
public enum uint YELLOW = 4;
public enum uint PURPLE = 5;
public enum uint WHITE = 6;
// division
public enum uint NO_DIVISION = 0;
public enum uint SIX_NOTCHES = 1;
public enum uint TEN_NOTCHES = 2;
public enum uint TWELVE_NOTCHES = 3;
public enum uint TWENTY_NOTCHES = 4;
public enum string[] FIELDS = ["color", "division"];
public uint color;
public uint division;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint color, uint division=uint.init) {
this.color = color;
this.division = division;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 4;
_encode!writeId();
writeBytes(varuint.encode(color));
writeBytes(varuint.encode(division));
return _buffer;
}
public pure nothrow @safe void decode() {
color=varuint.decode(_buffer, &_index);
division=varuint.decode(_buffer, &_index);
}
public override string toString() {
return "BossBar.UpdateStyle(color: " ~ std.conv.to!string(this.color) ~ ", division: " ~ std.conv.to!string(this.division) ~ ")";
}
}
public class UpdateFlags {
public enum typeof(action) ACTION = 5;
// flags
public enum ubyte DARK_SKY = 1;
public enum ubyte IS_DRAGON_BAR = 2;
public enum string[] FIELDS = ["flags"];
public ubyte flags;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ubyte flags) {
this.flags = flags;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 5;
_encode!writeId();
writeBigEndianUbyte(flags);
return _buffer;
}
public pure nothrow @safe void decode() {
flags=readBigEndianUbyte();
}
public override string toString() {
return "BossBar.UpdateFlags(flags: " ~ std.conv.to!string(this.flags) ~ ")";
}
}
}
class ServerDifficulty : Buffer {
public enum uint ID = 13;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// difficulty
public enum ubyte PEACEFUL = 0;
public enum ubyte EASY = 1;
public enum ubyte NORMAL = 2;
public enum ubyte HARD = 3;
public enum string[] FIELDS = ["difficulty"];
public ubyte difficulty;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ubyte difficulty) {
this.difficulty = difficulty;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUbyte(difficulty);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
difficulty=readBigEndianUbyte();
}
public static pure nothrow @safe ServerDifficulty fromBuffer(bool readId=true)(ubyte[] buffer) {
ServerDifficulty ret = new ServerDifficulty();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "ServerDifficulty(difficulty: " ~ std.conv.to!string(this.difficulty) ~ ")";
}
}
class TabComplete : Buffer {
public enum uint ID = 14;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["matches"];
public string[] matches;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string[] matches) {
this.matches = matches;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(cast(uint)matches.length)); foreach(bfyhc;matches){ writeBytes(varuint.encode(cast(uint)bfyhc.length)); writeString(bfyhc); }
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
matches.length=varuint.decode(_buffer, &_index); foreach(ref bfyhc;matches){ uint yzam=varuint.decode(_buffer, &_index); bfyhc=readString(yzam); }
}
public static pure nothrow @safe TabComplete fromBuffer(bool readId=true)(ubyte[] buffer) {
TabComplete ret = new TabComplete();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "TabComplete(matches: " ~ std.conv.to!string(this.matches) ~ ")";
}
}
class ChatMessage : Buffer {
public enum uint ID = 15;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// position
public enum ubyte CHAT = 0;
public enum ubyte SYSTEM_MESSAGE = 1;
public enum ubyte ABOVE_HOTBAR = 2;
public enum string[] FIELDS = ["message", "position"];
public string message;
public ubyte position;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string message, ubyte position=ubyte.init) {
this.message = message;
this.position = position;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(cast(uint)message.length)); writeString(message);
writeBigEndianUbyte(position);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
uint bvcfz=varuint.decode(_buffer, &_index); message=readString(bvcfz);
position=readBigEndianUbyte();
}
public static pure nothrow @safe ChatMessage fromBuffer(bool readId=true)(ubyte[] buffer) {
ChatMessage ret = new ChatMessage();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "ChatMessage(message: " ~ std.conv.to!string(this.message) ~ ", position: " ~ std.conv.to!string(this.position) ~ ")";
}
}
class MultiBlockChange : Buffer {
public enum uint ID = 16;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["chunk", "changes"];
public Tuple!(int, "x", int, "z") chunk;
public sul.protocol.java315.types.BlockChange[] changes;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(Tuple!(int, "x", int, "z") chunk, sul.protocol.java315.types.BlockChange[] changes=(sul.protocol.java315.types.BlockChange[]).init) {
this.chunk = chunk;
this.changes = changes;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianInt(chunk.x); writeBigEndianInt(chunk.z);
writeBytes(varuint.encode(cast(uint)changes.length)); foreach(yhbdc;changes){ yhbdc.encode(bufferInstance); }
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
chunk.x=readBigEndianInt(); chunk.z=readBigEndianInt();
changes.length=varuint.decode(_buffer, &_index); foreach(ref yhbdc;changes){ yhbdc.decode(bufferInstance); }
}
public static pure nothrow @safe MultiBlockChange fromBuffer(bool readId=true)(ubyte[] buffer) {
MultiBlockChange ret = new MultiBlockChange();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "MultiBlockChange(chunk: " ~ std.conv.to!string(this.chunk) ~ ", changes: " ~ std.conv.to!string(this.changes) ~ ")";
}
}
class ConfirmTransaction : Buffer {
public enum uint ID = 17;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["window", "action", "accepted"];
public ubyte window;
public ushort action;
public bool accepted;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ubyte window, ushort action=ushort.init, bool accepted=bool.init) {
this.window = window;
this.action = action;
this.accepted = accepted;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUbyte(window);
writeBigEndianUshort(action);
writeBigEndianBool(accepted);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
window=readBigEndianUbyte();
action=readBigEndianUshort();
accepted=readBigEndianBool();
}
public static pure nothrow @safe ConfirmTransaction fromBuffer(bool readId=true)(ubyte[] buffer) {
ConfirmTransaction ret = new ConfirmTransaction();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "ConfirmTransaction(window: " ~ std.conv.to!string(this.window) ~ ", action: " ~ std.conv.to!string(this.action) ~ ", accepted: " ~ std.conv.to!string(this.accepted) ~ ")";
}
}
class CloseWindow : Buffer {
public enum uint ID = 18;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["window"];
public ubyte window;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ubyte window) {
this.window = window;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUbyte(window);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
window=readBigEndianUbyte();
}
public static pure nothrow @safe CloseWindow fromBuffer(bool readId=true)(ubyte[] buffer) {
CloseWindow ret = new CloseWindow();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "CloseWindow(window: " ~ std.conv.to!string(this.window) ~ ")";
}
}
class OpenWindow : Buffer {
public enum uint ID = 19;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["window", "type", "title", "slots"];
public ubyte window;
public string type;
public string title;
public ubyte slots;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ubyte window, string type=string.init, string title=string.init, ubyte slots=ubyte.init) {
this.window = window;
this.type = type;
this.title = title;
this.slots = slots;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUbyte(window);
writeBytes(varuint.encode(cast(uint)type.length)); writeString(type);
writeBytes(varuint.encode(cast(uint)title.length)); writeString(title);
writeBigEndianUbyte(slots);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
window=readBigEndianUbyte();
uint dlz=varuint.decode(_buffer, &_index); type=readString(dlz);
uint dlbu=varuint.decode(_buffer, &_index); title=readString(dlbu);
slots=readBigEndianUbyte();
}
public static pure nothrow @safe OpenWindow fromBuffer(bool readId=true)(ubyte[] buffer) {
OpenWindow ret = new OpenWindow();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "OpenWindow(window: " ~ std.conv.to!string(this.window) ~ ", type: " ~ std.conv.to!string(this.type) ~ ", title: " ~ std.conv.to!string(this.title) ~ ", slots: " ~ std.conv.to!string(this.slots) ~ ")";
}
}
class WindowItems : Buffer {
public enum uint ID = 20;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["window", "slots"];
public ubyte window;
public sul.protocol.java315.types.Slot[] slots;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ubyte window, sul.protocol.java315.types.Slot[] slots=(sul.protocol.java315.types.Slot[]).init) {
this.window = window;
this.slots = slots;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUbyte(window);
writeBigEndianUshort(cast(ushort)slots.length); foreach(cxdm;slots){ cxdm.encode(bufferInstance); }
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
window=readBigEndianUbyte();
slots.length=readBigEndianUshort(); foreach(ref cxdm;slots){ cxdm.decode(bufferInstance); }
}
public static pure nothrow @safe WindowItems fromBuffer(bool readId=true)(ubyte[] buffer) {
WindowItems ret = new WindowItems();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "WindowItems(window: " ~ std.conv.to!string(this.window) ~ ", slots: " ~ std.conv.to!string(this.slots) ~ ")";
}
}
class WindowProperty : Buffer {
public enum uint ID = 21;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// property
public enum ushort FURNANCE_FIRE_ICON = 0;
public enum ushort FURNACE_MAX_FUEL_BURN_TIME = 1;
public enum ushort FURNACE_PROGRESS_ARROW = 2;
public enum ushort FURNCE_MAX_PROGRESS = 3;
public enum ushort ENCHANTMENT_LEVEL_REQUIREMENT_TOP = 0;
public enum ushort ENCHANTMENT_LEVEL_REQUIREMENT_MIDDLE = 1;
public enum ushort ENCHANTMENT_LEVEL_REQUIREMENT_BOTTOM = 2;
public enum ushort ENCHANTMENT_SEED = 3;
public enum ushort ENCHANTMENT_ID_TOP = 4;
public enum ushort ENCHANTMENT_ID_MIDDLE = 5;
public enum ushort ENCHANTMENT_ID_BOTTOM = 6;
public enum ushort ENCHANTMENT_LEVEL_TOP = 7;
public enum ushort ENCHANTMENT_LEVEL_MIDDLE = 8;
public enum ushort ENCHANTMENT_LEVEL_BOTTOM = 9;
public enum ushort BEACON_POWER_LEVEL = 0;
public enum ushort BEACON_FIRST_EFFECT = 1;
public enum ushort BEACON_SECOND_EFFECT = 2;
public enum ushort ANVIL_REPAIR_COST = 0;
public enum ushort BREWING_STAND_BREW_TIME = 0;
public enum string[] FIELDS = ["window", "property", "value"];
public ubyte window;
public ushort property;
public short value;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ubyte window, ushort property=ushort.init, short value=short.init) {
this.window = window;
this.property = property;
this.value = value;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUbyte(window);
writeBigEndianUshort(property);
writeBigEndianShort(value);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
window=readBigEndianUbyte();
property=readBigEndianUshort();
value=readBigEndianShort();
}
public static pure nothrow @safe WindowProperty fromBuffer(bool readId=true)(ubyte[] buffer) {
WindowProperty ret = new WindowProperty();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "WindowProperty(window: " ~ std.conv.to!string(this.window) ~ ", property: " ~ std.conv.to!string(this.property) ~ ", value: " ~ std.conv.to!string(this.value) ~ ")";
}
}
class SetSlot : Buffer {
public enum uint ID = 22;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["window", "slot", "item"];
public ubyte window;
public ushort slot;
public sul.protocol.java315.types.Slot item;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ubyte window, ushort slot=ushort.init, sul.protocol.java315.types.Slot item=sul.protocol.java315.types.Slot.init) {
this.window = window;
this.slot = slot;
this.item = item;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUbyte(window);
writeBigEndianUshort(slot);
item.encode(bufferInstance);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
window=readBigEndianUbyte();
slot=readBigEndianUshort();
item.decode(bufferInstance);
}
public static pure nothrow @safe SetSlot fromBuffer(bool readId=true)(ubyte[] buffer) {
SetSlot ret = new SetSlot();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "SetSlot(window: " ~ std.conv.to!string(this.window) ~ ", slot: " ~ std.conv.to!string(this.slot) ~ ", item: " ~ std.conv.to!string(this.item) ~ ")";
}
}
class SetCooldown : Buffer {
public enum uint ID = 23;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["item", "cooldown"];
public uint item;
public uint cooldown;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint item, uint cooldown=uint.init) {
this.item = item;
this.cooldown = cooldown;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(item));
writeBytes(varuint.encode(cooldown));
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
item=varuint.decode(_buffer, &_index);
cooldown=varuint.decode(_buffer, &_index);
}
public static pure nothrow @safe SetCooldown fromBuffer(bool readId=true)(ubyte[] buffer) {
SetCooldown ret = new SetCooldown();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "SetCooldown(item: " ~ std.conv.to!string(this.item) ~ ", cooldown: " ~ std.conv.to!string(this.cooldown) ~ ")";
}
}
class PluginMessage : Buffer {
public enum uint ID = 24;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["channel", "data"];
public string channel;
public ubyte[] data;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string channel, ubyte[] data=(ubyte[]).init) {
this.channel = channel;
this.data = data;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(cast(uint)channel.length)); writeString(channel);
writeBytes(data);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
uint yhb5b=varuint.decode(_buffer, &_index); channel=readString(yhb5b);
data=_buffer[_index..$].dup; _index=_buffer.length;
}
public static pure nothrow @safe PluginMessage fromBuffer(bool readId=true)(ubyte[] buffer) {
PluginMessage ret = new PluginMessage();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "PluginMessage(channel: " ~ std.conv.to!string(this.channel) ~ ", data: " ~ std.conv.to!string(this.data) ~ ")";
}
}
class NamedSoundEffect : Buffer {
public enum uint ID = 25;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["name", "category", "position", "volume", "pitch"];
public string name;
public uint category;
public Tuple!(int, "x", int, "y", int, "z") position;
public float volume;
public float pitch;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string name, uint category=uint.init, Tuple!(int, "x", int, "y", int, "z") position=Tuple!(int, "x", int, "y", int, "z").init, float volume=float.init, float pitch=float.init) {
this.name = name;
this.category = category;
this.position = position;
this.volume = volume;
this.pitch = pitch;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(cast(uint)name.length)); writeString(name);
writeBytes(varuint.encode(category));
writeBigEndianInt(position.x); writeBigEndianInt(position.y); writeBigEndianInt(position.z);
writeBigEndianFloat(volume);
writeBigEndianFloat(pitch);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
uint bfz=varuint.decode(_buffer, &_index); name=readString(bfz);
category=varuint.decode(_buffer, &_index);
position.x=readBigEndianInt(); position.y=readBigEndianInt(); position.z=readBigEndianInt();
volume=readBigEndianFloat();
pitch=readBigEndianFloat();
}
public static pure nothrow @safe NamedSoundEffect fromBuffer(bool readId=true)(ubyte[] buffer) {
NamedSoundEffect ret = new NamedSoundEffect();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "NamedSoundEffect(name: " ~ std.conv.to!string(this.name) ~ ", category: " ~ std.conv.to!string(this.category) ~ ", position: " ~ std.conv.to!string(this.position) ~ ", volume: " ~ std.conv.to!string(this.volume) ~ ", pitch: " ~ std.conv.to!string(this.pitch) ~ ")";
}
}
class Disconnect : Buffer {
public enum uint ID = 26;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["reason"];
public string reason;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string reason) {
this.reason = reason;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(cast(uint)reason.length)); writeString(reason);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
uint cvc9=varuint.decode(_buffer, &_index); reason=readString(cvc9);
}
public static pure nothrow @safe Disconnect fromBuffer(bool readId=true)(ubyte[] buffer) {
Disconnect ret = new Disconnect();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "Disconnect(reason: " ~ std.conv.to!string(this.reason) ~ ")";
}
}
class EntityStatus : Buffer {
public enum uint ID = 27;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// status
public enum ubyte SPAWN_TIPPED_ARROW_PARTICLE_EFFECTS = 0;
public enum ubyte PLAY_JUMPING_ANIMATION_AND_PARTICLES = 1;
public enum ubyte RESET_SPAWNER_DELAY = 1;
public enum ubyte PLAY_HURT_ANIMATION_AND_SOUND = 2;
public enum ubyte PLAY_DEATH_ANIMATION_AND_SOUND = 3;
public enum ubyte PLAY_ATTACK_ANIMATION_AND_SOUND = 4;
public enum ubyte SPAWN_SMOKE_PARTICLES = 6;
public enum ubyte SPAWN_HEART_PARTICLES = 7;
public enum ubyte PLAY_SHAKING_WATER_ANIMATION = 8;
public enum ubyte FINISHED_CONSUMING = 9;
public enum ubyte PLAY_EATING_GRASS_ANIMATION = 10;
public enum ubyte IGNITE_MINECART_TNT = 10;
public enum ubyte HOLD_POPPY = 11;
public enum ubyte SPAWN_VILLAGER_MATING_HEART_PARTICLES = 12;
public enum ubyte SPAWN_VILLAGER_ANGRY_PARTICLES = 13;
public enum ubyte SPAWN_VILLAGER_HAPPY_PARTICLES = 14;
public enum ubyte SPAWN_WITCH_MAGIC_PARTICLES = 15;
public enum ubyte PLAY_ZOMBIE_CURE_FINISHED_SOUND = 16;
public enum ubyte SPAWN_FIREWORK_EXPLOSION_EFFECT = 17;
public enum ubyte SPAWN_LOVE_PARTICLES = 18;
public enum ubyte RESET_SQUID_ROTATION = 19;
public enum ubyte SPAWN_EXPLOSION_PARTICLES = 20;
public enum ubyte PLAY_GUARDIAN_SOUND_EFFECT = 21;
public enum ubyte ENABLE_REDUCED_DEBUG_SCREEN = 22;
public enum ubyte DISABLE_REDUCED_DEBUG_SCREEN = 23;
public enum ubyte SET_OP_PERMISSION_LEVEL_0 = 24;
public enum ubyte SET_OP_PERMISSION_LEVEL_1 = 25;
public enum ubyte SET_OP_PERMISSION_LEVEL_2 = 26;
public enum ubyte SET_OP_PERMISSION_LEVEL_3 = 27;
public enum ubyte SET_OP_PERMISSION_LEVEL_4 = 28;
public enum ubyte PLAY_SHIELD_BLOCK_SOUND = 29;
public enum ubyte PLAY_SHIELD_BREAK_SOUND = 30;
public enum ubyte HOOK_KNOCKBACK = 31;
public enum ubyte PLAY_HIT_SOUND = 32;
public enum ubyte PLAY_THORNS_HURT_ANIMATION_AND_SOUND = 33;
public enum ubyte REMOVE_POPPY = 34;
public enum ubyte PLAY_TOTEM_UNDYING_ANIMATION = 35;
public enum string[] FIELDS = ["entityId", "status"];
public uint entityId;
public ubyte status;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, ubyte status=ubyte.init) {
this.entityId = entityId;
this.status = status;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUint(entityId);
writeBigEndianUbyte(status);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=readBigEndianUint();
status=readBigEndianUbyte();
}
public static pure nothrow @safe EntityStatus fromBuffer(bool readId=true)(ubyte[] buffer) {
EntityStatus ret = new EntityStatus();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "EntityStatus(entityId: " ~ std.conv.to!string(this.entityId) ~ ", status: " ~ std.conv.to!string(this.status) ~ ")";
}
}
class Explosion : Buffer {
public enum uint ID = 28;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["position", "radius", "records", "motion"];
public Tuple!(float, "x", float, "y", float, "z") position;
public float radius;
public Tuple!(byte, "x", byte, "y", byte, "z")[] records;
public Tuple!(float, "x", float, "y", float, "z") motion;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(Tuple!(float, "x", float, "y", float, "z") position, float radius=float.init, Tuple!(byte, "x", byte, "y", byte, "z")[] records=(Tuple!(byte, "x", byte, "y", byte, "z")[]).init, Tuple!(float, "x", float, "y", float, "z") motion=Tuple!(float, "x", float, "y", float, "z").init) {
this.position = position;
this.radius = radius;
this.records = records;
this.motion = motion;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianFloat(position.x); writeBigEndianFloat(position.y); writeBigEndianFloat(position.z);
writeBigEndianFloat(radius);
writeBigEndianUint(cast(uint)records.length); foreach(cvbjc;records){ writeBigEndianByte(cvbjc.x); writeBigEndianByte(cvbjc.y); writeBigEndianByte(cvbjc.z); }
writeBigEndianFloat(motion.x); writeBigEndianFloat(motion.y); writeBigEndianFloat(motion.z);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
position.x=readBigEndianFloat(); position.y=readBigEndianFloat(); position.z=readBigEndianFloat();
radius=readBigEndianFloat();
records.length=readBigEndianUint(); foreach(ref cvbjc;records){ cvbjc.x=readBigEndianByte(); cvbjc.y=readBigEndianByte(); cvbjc.z=readBigEndianByte(); }
motion.x=readBigEndianFloat(); motion.y=readBigEndianFloat(); motion.z=readBigEndianFloat();
}
public static pure nothrow @safe Explosion fromBuffer(bool readId=true)(ubyte[] buffer) {
Explosion ret = new Explosion();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "Explosion(position: " ~ std.conv.to!string(this.position) ~ ", radius: " ~ std.conv.to!string(this.radius) ~ ", records: " ~ std.conv.to!string(this.records) ~ ", motion: " ~ std.conv.to!string(this.motion) ~ ")";
}
}
class UnloadChunk : Buffer {
public enum uint ID = 29;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["position"];
public Tuple!(int, "x", int, "z") position;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(Tuple!(int, "x", int, "z") position) {
this.position = position;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianInt(position.x); writeBigEndianInt(position.z);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
position.x=readBigEndianInt(); position.z=readBigEndianInt();
}
public static pure nothrow @safe UnloadChunk fromBuffer(bool readId=true)(ubyte[] buffer) {
UnloadChunk ret = new UnloadChunk();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "UnloadChunk(position: " ~ std.conv.to!string(this.position) ~ ")";
}
}
class ChangeGameState : Buffer {
public enum uint ID = 30;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// reason
public enum ubyte INVALID_BED = 0;
public enum ubyte END_RAINING = 1;
public enum ubyte BEGIN_RAINING = 2;
public enum ubyte CHANGE_GAMEMODE = 3;
public enum ubyte EXIT_END = 4;
public enum ubyte DEMO_MESSAGE = 5;
public enum ubyte ARROW_HITTING_PLAYER = 6;
public enum ubyte FADE_VALUE = 7;
public enum ubyte FADE_TIME = 8;
public enum ubyte PLAY_ELDER_GUARDIAN_MOB_APPEARANCE = 10;
// value
public enum float SURVIVAL = 0;
public enum float CREATIVE = 1;
public enum float ADVENTURE = 2;
public enum float SPECTATOR = 3;
public enum float RESPAWN_IMMEDIATELY = 0;
public enum float RESPAWN_AFTER_CREDITS = 1;
public enum float SHOW_DEMO_SCREEN = 0;
public enum float TELL_MOVEMENT_CONTROLS = 101;
public enum float TELL_JUMP_CONTROLS = 102;
public enum float TELL_INVENTORY_CONTROLS = 103;
public enum float BRIGHT = 0;
public enum float DARK = 1;
public enum string[] FIELDS = ["reason", "value"];
public ubyte reason;
public float value;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ubyte reason, float value=float.init) {
this.reason = reason;
this.value = value;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUbyte(reason);
writeBigEndianFloat(value);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
reason=readBigEndianUbyte();
value=readBigEndianFloat();
}
public static pure nothrow @safe ChangeGameState fromBuffer(bool readId=true)(ubyte[] buffer) {
ChangeGameState ret = new ChangeGameState();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "ChangeGameState(reason: " ~ std.conv.to!string(this.reason) ~ ", value: " ~ std.conv.to!string(this.value) ~ ")";
}
}
class KeepAlive : Buffer {
public enum uint ID = 31;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["id"];
public uint id;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint id) {
this.id = id;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(id));
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
id=varuint.decode(_buffer, &_index);
}
public static pure nothrow @safe KeepAlive fromBuffer(bool readId=true)(ubyte[] buffer) {
KeepAlive ret = new KeepAlive();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "KeepAlive(id: " ~ std.conv.to!string(this.id) ~ ")";
}
}
class ChunkData : Buffer {
public enum uint ID = 32;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["position", "full", "sections", "data", "tilesCount", "tiles"];
public Tuple!(int, "x", int, "z") position;
public bool full;
public uint sections;
public ubyte[] data;
public uint tilesCount;
public ubyte[] tiles;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(Tuple!(int, "x", int, "z") position, bool full=bool.init, uint sections=uint.init, ubyte[] data=(ubyte[]).init, uint tilesCount=uint.init, ubyte[] tiles=(ubyte[]).init) {
this.position = position;
this.full = full;
this.sections = sections;
this.data = data;
this.tilesCount = tilesCount;
this.tiles = tiles;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianInt(position.x); writeBigEndianInt(position.z);
writeBigEndianBool(full);
writeBytes(varuint.encode(sections));
writeBytes(varuint.encode(cast(uint)data.length)); writeBytes(data);
writeBytes(varuint.encode(tilesCount));
writeBytes(tiles);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
position.x=readBigEndianInt(); position.z=readBigEndianInt();
full=readBigEndianBool();
sections=varuint.decode(_buffer, &_index);
data.length=varuint.decode(_buffer, &_index); if(_buffer.length>=_index+data.length){ data=_buffer[_index.._index+data.length].dup; _index+=data.length; }
tilesCount=varuint.decode(_buffer, &_index);
tiles=_buffer[_index..$].dup; _index=_buffer.length;
}
public static pure nothrow @safe ChunkData fromBuffer(bool readId=true)(ubyte[] buffer) {
ChunkData ret = new ChunkData();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "ChunkData(position: " ~ std.conv.to!string(this.position) ~ ", full: " ~ std.conv.to!string(this.full) ~ ", sections: " ~ std.conv.to!string(this.sections) ~ ", data: " ~ std.conv.to!string(this.data) ~ ", tilesCount: " ~ std.conv.to!string(this.tilesCount) ~ ", tiles: " ~ std.conv.to!string(this.tiles) ~ ")";
}
}
class Effect : Buffer {
public enum uint ID = 33;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// effect id
public enum uint DISPENSER_DISPENSE = 1000;
public enum uint DISPENSER_FAIL_DISPENSE = 1001;
public enum uint DISPENSER_SHOOT = 1002;
public enum uint ENDER_EYE_LAUNCH = 1003;
public enum uint FIREWORK_SHOT = 1004;
public enum uint IRON_DOOR_OPEN = 1005;
public enum uint WOODEN_DOOR_OPEN = 1006;
public enum uint WOODEN_TRAPDOOR_OPEN = 1007;
public enum uint FENCE_GATE_OPEN = 1008;
public enum uint FIRE_EXTINGUISH = 1009;
public enum uint PLAY_RECORD = 1010;
public enum uint IRON_DOOR_CLOSE = 1011;
public enum uint WOODEN_DOOR_CLOSE = 1012;
public enum uint WOODEN_TRAPDOOR_CLOSE = 1013;
public enum uint FENCE_GATE_CLOSE = 1014;
public enum uint GHAST_WARN = 1015;
public enum uint GHAST_SHOOT = 1016;
public enum uint ENDERDRAGON_SHOOT = 1017;
public enum uint BLAZE_SHOOT = 1018;
public enum uint ZOMBIE_ATTACK_WOOD_DOOR = 1019;
public enum uint ZOMBIE_ATTACK_IRON_DOOR = 1020;
public enum uint ZOMBIE_BREAK_WOOD_DOOR = 1021;
public enum uint WITHER_BREAK_BLOCK = 1022;
public enum uint WITHER_SPAWN = 1023;
public enum uint WITHER_SHOOT = 1024;
public enum uint BAT_TAKE_OFF = 1025;
public enum uint ZOMBIE_INFECT_VILLAGER = 1026;
public enum uint ZOMBIE_VILLAGER_CONVERT = 1027;
public enum uint ENDER_DRAGON_BREATH = 1028;
public enum uint ANVIL_BREAK = 1029;
public enum uint ANVIL_USE = 1030;
public enum uint ANVIL_LAND = 1031;
public enum uint PORTAL_TRAVEL = 1032;
public enum uint CHORUS_FLOWER_GROW = 1033;
public enum uint CHORUS_FLOWER_DIE = 1034;
public enum uint BREWING_STAND_BREW = 1035;
public enum uint IRON_TRAPDOOR_OPEN = 1036;
public enum uint IRON_TRAPDOOR_CLOSE = 1037;
public enum uint SPAWN_10_SMOKE_PARTICLES = 2000;
public enum uint BREAK_BREAK_PARTICLES_AND_SOUND = 2001;
public enum uint SPLASH_POTION_PARTICLES_AND_SOUND = 2002;
public enum uint ENDER_EYE_BREAK_PARTICLES_AND_SOUND = 2003;
public enum uint MOB_SPAWN_PARTICLES = 2004;
public enum uint BONEMEAL_PARTICLES = 2005;
public enum uint DRAGON_BREATH = 2006;
public enum uint END_GATEWAY_SPAWN = 3000;
public enum uint ENDERDRAGON_GROWL = 3001;
public enum string[] FIELDS = ["effectId", "position", "data", "disableVolume"];
public uint effectId;
public ulong position;
public uint data;
public bool disableVolume;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint effectId, ulong position=ulong.init, uint data=uint.init, bool disableVolume=bool.init) {
this.effectId = effectId;
this.position = position;
this.data = data;
this.disableVolume = disableVolume;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUint(effectId);
writeBigEndianUlong(position);
writeBigEndianUint(data);
writeBigEndianBool(disableVolume);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
effectId=readBigEndianUint();
position=readBigEndianUlong();
data=readBigEndianUint();
disableVolume=readBigEndianBool();
}
public static pure nothrow @safe Effect fromBuffer(bool readId=true)(ubyte[] buffer) {
Effect ret = new Effect();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "Effect(effectId: " ~ std.conv.to!string(this.effectId) ~ ", position: " ~ std.conv.to!string(this.position) ~ ", data: " ~ std.conv.to!string(this.data) ~ ", disableVolume: " ~ std.conv.to!string(this.disableVolume) ~ ")";
}
}
class Particle : Buffer {
public enum uint ID = 34;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// particle id
public enum uint EXPLODE = 0;
public enum uint LARGE_EXPLOSION = 1;
public enum uint HUGE_EXPLOSION = 2;
public enum uint FIREWORK_SPARK = 3;
public enum uint BUBBLE = 4;
public enum uint SPLASH = 5;
public enum uint WAKE = 6;
public enum uint SUSPENDED = 7;
public enum uint DEPTH_SUSPEND = 8;
public enum uint CRIT = 9;
public enum uint MAGIC_CRIT = 10;
public enum uint SMOKE = 11;
public enum uint LARGE_SMOKE = 12;
public enum uint SPELL = 13;
public enum uint INSTANT_SPELL = 14;
public enum uint MOB_SPELL = 15;
public enum uint MOB_SPELL_AMBIENT = 16;
public enum uint WITCH_MAGIC = 17;
public enum uint DRIP_WATER = 18;
public enum uint DRIP_LAVA = 19;
public enum uint ANGRY_VILLAGER = 20;
public enum uint HAPPY_VILLAGER = 21;
public enum uint TOWN_AURA = 22;
public enum uint NOTE = 23;
public enum uint PORTAL = 24;
public enum uint ENCHANTMENT_TABLE = 25;
public enum uint FLAME = 26;
public enum uint LAVA = 27;
public enum uint FOOTSTEP = 28;
public enum uint CLOUD = 29;
public enum uint RED_DUST = 30;
public enum uint SNOWBALL_POOF = 31;
public enum uint SNOW_SHOVEL = 32;
public enum uint SLIME = 33;
public enum uint HEART = 34;
public enum uint BARRIER = 35;
public enum uint ITEM_CRACK = 36;
public enum uint BLOCK_CRACK = 37;
public enum uint BLOCK_DUST = 38;
public enum uint DROPLET = 39;
public enum uint TAKE = 40;
public enum uint MOB_APPEARANCE = 41;
public enum uint DRAGON_BREATH = 42;
public enum uint ENDROD = 43;
public enum uint DAMAGE_INDICATOR = 44;
public enum uint SWEEP_ATTACK = 45;
public enum uint FALLING_DUST = 46;
public enum string[] FIELDS = ["particleId", "longDistance", "position", "offset", "data", "count", "additionalData"];
public uint particleId;
public bool longDistance;
public Tuple!(float, "x", float, "y", float, "z") position;
public Tuple!(float, "x", float, "y", float, "z") offset;
public float data;
public uint count;
public uint[2] additionalData;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint particleId, bool longDistance=bool.init, Tuple!(float, "x", float, "y", float, "z") position=Tuple!(float, "x", float, "y", float, "z").init, Tuple!(float, "x", float, "y", float, "z") offset=Tuple!(float, "x", float, "y", float, "z").init, float data=float.init, uint count=uint.init, uint[2] additionalData=(uint[2]).init) {
this.particleId = particleId;
this.longDistance = longDistance;
this.position = position;
this.offset = offset;
this.data = data;
this.count = count;
this.additionalData = additionalData;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUint(particleId);
writeBigEndianBool(longDistance);
writeBigEndianFloat(position.x); writeBigEndianFloat(position.y); writeBigEndianFloat(position.z);
writeBigEndianFloat(offset.x); writeBigEndianFloat(offset.y); writeBigEndianFloat(offset.z);
writeBigEndianFloat(data);
writeBigEndianUint(count);
foreach(yrarb5br;additionalData){ writeBytes(varuint.encode(yrarb5br)); }
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
particleId=readBigEndianUint();
longDistance=readBigEndianBool();
position.x=readBigEndianFloat(); position.y=readBigEndianFloat(); position.z=readBigEndianFloat();
offset.x=readBigEndianFloat(); offset.y=readBigEndianFloat(); offset.z=readBigEndianFloat();
data=readBigEndianFloat();
count=readBigEndianUint();
foreach(ref yrarb5br;additionalData){ yrarb5br=varuint.decode(_buffer, &_index); }
}
public static pure nothrow @safe Particle fromBuffer(bool readId=true)(ubyte[] buffer) {
Particle ret = new Particle();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "Particle(particleId: " ~ std.conv.to!string(this.particleId) ~ ", longDistance: " ~ std.conv.to!string(this.longDistance) ~ ", position: " ~ std.conv.to!string(this.position) ~ ", offset: " ~ std.conv.to!string(this.offset) ~ ", data: " ~ std.conv.to!string(this.data) ~ ", count: " ~ std.conv.to!string(this.count) ~ ", additionalData: " ~ std.conv.to!string(this.additionalData) ~ ")";
}
}
class JoinGame : Buffer {
public enum uint ID = 35;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// gamemode
public enum ubyte SURVIVAL = 0;
public enum ubyte CREATIVE = 1;
public enum ubyte ADVENTURE = 2;
public enum ubyte SPECTATOR = 3;
// dimension
public enum int NETHER = -1;
public enum int OVERWORLD = 0;
public enum int END = 1;
// difficulty
public enum ubyte PEACEFUL = 0;
public enum ubyte EASY = 1;
public enum ubyte NORMAL = 2;
public enum ubyte HARD = 3;
// level type
public enum string INFINITY = "default";
public enum string FLAT = "flat";
public enum string AMPLIFIED = "amplified";
public enum string LARGE_BIOMES = "largeBiomes";
public enum string[] FIELDS = ["entityId", "gamemode", "dimension", "difficulty", "maxPlayers", "levelType", "reducedDebug"];
public uint entityId;
public ubyte gamemode;
public int dimension;
public ubyte difficulty;
public ubyte maxPlayers;
public string levelType;
public bool reducedDebug;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, ubyte gamemode=ubyte.init, int dimension=int.init, ubyte difficulty=ubyte.init, ubyte maxPlayers=ubyte.init, string levelType=string.init, bool reducedDebug=bool.init) {
this.entityId = entityId;
this.gamemode = gamemode;
this.dimension = dimension;
this.difficulty = difficulty;
this.maxPlayers = maxPlayers;
this.levelType = levelType;
this.reducedDebug = reducedDebug;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUint(entityId);
writeBigEndianUbyte(gamemode);
writeBigEndianInt(dimension);
writeBigEndianUbyte(difficulty);
writeBigEndianUbyte(maxPlayers);
writeBytes(varuint.encode(cast(uint)levelType.length)); writeString(levelType);
writeBigEndianBool(reducedDebug);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=readBigEndianUint();
gamemode=readBigEndianUbyte();
dimension=readBigEndianInt();
difficulty=readBigEndianUbyte();
maxPlayers=readBigEndianUbyte();
uint bvzxeb=varuint.decode(_buffer, &_index); levelType=readString(bvzxeb);
reducedDebug=readBigEndianBool();
}
public static pure nothrow @safe JoinGame fromBuffer(bool readId=true)(ubyte[] buffer) {
JoinGame ret = new JoinGame();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "JoinGame(entityId: " ~ std.conv.to!string(this.entityId) ~ ", gamemode: " ~ std.conv.to!string(this.gamemode) ~ ", dimension: " ~ std.conv.to!string(this.dimension) ~ ", difficulty: " ~ std.conv.to!string(this.difficulty) ~ ", maxPlayers: " ~ std.conv.to!string(this.maxPlayers) ~ ", levelType: " ~ std.conv.to!string(this.levelType) ~ ", reducedDebug: " ~ std.conv.to!string(this.reducedDebug) ~ ")";
}
}
class Map : Buffer {
public enum uint ID = 36;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["mapId", "scale", "showIcons", "icons", "colums", "rows", "offset", "data"];
public uint mapId;
public ubyte scale;
public bool showIcons;
public sul.protocol.java315.types.Icon[] icons;
public ubyte colums;
public ubyte rows;
public Tuple!(ubyte, "x", ubyte, "z") offset;
public ubyte[] data;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint mapId, ubyte scale=ubyte.init, bool showIcons=bool.init, sul.protocol.java315.types.Icon[] icons=(sul.protocol.java315.types.Icon[]).init, ubyte colums=ubyte.init, ubyte rows=ubyte.init, Tuple!(ubyte, "x", ubyte, "z") offset=Tuple!(ubyte, "x", ubyte, "z").init, ubyte[] data=(ubyte[]).init) {
this.mapId = mapId;
this.scale = scale;
this.showIcons = showIcons;
this.icons = icons;
this.colums = colums;
this.rows = rows;
this.offset = offset;
this.data = data;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(mapId));
writeBigEndianUbyte(scale);
writeBigEndianBool(showIcons);
writeBytes(varuint.encode(cast(uint)icons.length)); foreach(anbm;icons){ anbm.encode(bufferInstance); }
writeBigEndianUbyte(colums);
writeBigEndianUbyte(rows);
writeBigEndianUbyte(offset.x); writeBigEndianUbyte(offset.z);
writeBytes(varuint.encode(cast(uint)data.length)); writeBytes(data);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
mapId=varuint.decode(_buffer, &_index);
scale=readBigEndianUbyte();
showIcons=readBigEndianBool();
icons.length=varuint.decode(_buffer, &_index); foreach(ref anbm;icons){ anbm.decode(bufferInstance); }
colums=readBigEndianUbyte();
rows=readBigEndianUbyte();
offset.x=readBigEndianUbyte(); offset.z=readBigEndianUbyte();
data.length=varuint.decode(_buffer, &_index); if(_buffer.length>=_index+data.length){ data=_buffer[_index.._index+data.length].dup; _index+=data.length; }
}
public static pure nothrow @safe Map fromBuffer(bool readId=true)(ubyte[] buffer) {
Map ret = new Map();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "Map(mapId: " ~ std.conv.to!string(this.mapId) ~ ", scale: " ~ std.conv.to!string(this.scale) ~ ", showIcons: " ~ std.conv.to!string(this.showIcons) ~ ", icons: " ~ std.conv.to!string(this.icons) ~ ", colums: " ~ std.conv.to!string(this.colums) ~ ", rows: " ~ std.conv.to!string(this.rows) ~ ", offset: " ~ std.conv.to!string(this.offset) ~ ", data: " ~ std.conv.to!string(this.data) ~ ")";
}
}
class EntityRelativeMove : Buffer {
public enum uint ID = 37;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId", "delta", "onGround"];
public uint entityId;
public Tuple!(short, "x", short, "y", short, "z") delta;
public bool onGround;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, Tuple!(short, "x", short, "y", short, "z") delta=Tuple!(short, "x", short, "y", short, "z").init, bool onGround=bool.init) {
this.entityId = entityId;
this.delta = delta;
this.onGround = onGround;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBigEndianShort(delta.x); writeBigEndianShort(delta.y); writeBigEndianShort(delta.z);
writeBigEndianBool(onGround);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
delta.x=readBigEndianShort(); delta.y=readBigEndianShort(); delta.z=readBigEndianShort();
onGround=readBigEndianBool();
}
public static pure nothrow @safe EntityRelativeMove fromBuffer(bool readId=true)(ubyte[] buffer) {
EntityRelativeMove ret = new EntityRelativeMove();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "EntityRelativeMove(entityId: " ~ std.conv.to!string(this.entityId) ~ ", delta: " ~ std.conv.to!string(this.delta) ~ ", onGround: " ~ std.conv.to!string(this.onGround) ~ ")";
}
}
class EntityLookAndRelativeMove : Buffer {
public enum uint ID = 38;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId", "delta", "yaw", "pitch", "onGround"];
public uint entityId;
public Tuple!(short, "x", short, "y", short, "z") delta;
public ubyte yaw;
public ubyte pitch;
public bool onGround;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, Tuple!(short, "x", short, "y", short, "z") delta=Tuple!(short, "x", short, "y", short, "z").init, ubyte yaw=ubyte.init, ubyte pitch=ubyte.init, bool onGround=bool.init) {
this.entityId = entityId;
this.delta = delta;
this.yaw = yaw;
this.pitch = pitch;
this.onGround = onGround;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBigEndianShort(delta.x); writeBigEndianShort(delta.y); writeBigEndianShort(delta.z);
writeBigEndianUbyte(yaw);
writeBigEndianUbyte(pitch);
writeBigEndianBool(onGround);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
delta.x=readBigEndianShort(); delta.y=readBigEndianShort(); delta.z=readBigEndianShort();
yaw=readBigEndianUbyte();
pitch=readBigEndianUbyte();
onGround=readBigEndianBool();
}
public static pure nothrow @safe EntityLookAndRelativeMove fromBuffer(bool readId=true)(ubyte[] buffer) {
EntityLookAndRelativeMove ret = new EntityLookAndRelativeMove();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "EntityLookAndRelativeMove(entityId: " ~ std.conv.to!string(this.entityId) ~ ", delta: " ~ std.conv.to!string(this.delta) ~ ", yaw: " ~ std.conv.to!string(this.yaw) ~ ", pitch: " ~ std.conv.to!string(this.pitch) ~ ", onGround: " ~ std.conv.to!string(this.onGround) ~ ")";
}
}
class EntityLook : Buffer {
public enum uint ID = 39;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId", "yaw", "pitch", "onGround"];
public uint entityId;
public ubyte yaw;
public ubyte pitch;
public bool onGround;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, ubyte yaw=ubyte.init, ubyte pitch=ubyte.init, bool onGround=bool.init) {
this.entityId = entityId;
this.yaw = yaw;
this.pitch = pitch;
this.onGround = onGround;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBigEndianUbyte(yaw);
writeBigEndianUbyte(pitch);
writeBigEndianBool(onGround);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
yaw=readBigEndianUbyte();
pitch=readBigEndianUbyte();
onGround=readBigEndianBool();
}
public static pure nothrow @safe EntityLook fromBuffer(bool readId=true)(ubyte[] buffer) {
EntityLook ret = new EntityLook();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "EntityLook(entityId: " ~ std.conv.to!string(this.entityId) ~ ", yaw: " ~ std.conv.to!string(this.yaw) ~ ", pitch: " ~ std.conv.to!string(this.pitch) ~ ", onGround: " ~ std.conv.to!string(this.onGround) ~ ")";
}
}
class Entity : Buffer {
public enum uint ID = 40;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId"];
public uint entityId;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId) {
this.entityId = entityId;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
}
public static pure nothrow @safe Entity fromBuffer(bool readId=true)(ubyte[] buffer) {
Entity ret = new Entity();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "Entity(entityId: " ~ std.conv.to!string(this.entityId) ~ ")";
}
}
class VehicleMove : Buffer {
public enum uint ID = 41;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["position", "yaw", "pitch"];
public Tuple!(double, "x", double, "y", double, "z") position;
public float yaw;
public float pitch;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(Tuple!(double, "x", double, "y", double, "z") position, float yaw=float.init, float pitch=float.init) {
this.position = position;
this.yaw = yaw;
this.pitch = pitch;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianDouble(position.x); writeBigEndianDouble(position.y); writeBigEndianDouble(position.z);
writeBigEndianFloat(yaw);
writeBigEndianFloat(pitch);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
position.x=readBigEndianDouble(); position.y=readBigEndianDouble(); position.z=readBigEndianDouble();
yaw=readBigEndianFloat();
pitch=readBigEndianFloat();
}
public static pure nothrow @safe VehicleMove fromBuffer(bool readId=true)(ubyte[] buffer) {
VehicleMove ret = new VehicleMove();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "VehicleMove(position: " ~ std.conv.to!string(this.position) ~ ", yaw: " ~ std.conv.to!string(this.yaw) ~ ", pitch: " ~ std.conv.to!string(this.pitch) ~ ")";
}
}
class OpenSignEditor : Buffer {
public enum uint ID = 42;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["position"];
public ulong position;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ulong position) {
this.position = position;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUlong(position);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
position=readBigEndianUlong();
}
public static pure nothrow @safe OpenSignEditor fromBuffer(bool readId=true)(ubyte[] buffer) {
OpenSignEditor ret = new OpenSignEditor();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "OpenSignEditor(position: " ~ std.conv.to!string(this.position) ~ ")";
}
}
class PlayerAbilities : Buffer {
public enum uint ID = 43;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// flags
public enum ubyte INVULNERABLE = 1;
public enum ubyte FLYING = 2;
public enum ubyte ALLOW_FLYING = 4;
public enum ubyte CREATIVE_MODE = 8;
public enum string[] FIELDS = ["flags", "flyingSpeed", "fovModifier"];
public ubyte flags;
public float flyingSpeed;
public float fovModifier;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ubyte flags, float flyingSpeed=float.init, float fovModifier=float.init) {
this.flags = flags;
this.flyingSpeed = flyingSpeed;
this.fovModifier = fovModifier;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUbyte(flags);
writeBigEndianFloat(flyingSpeed);
writeBigEndianFloat(fovModifier);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
flags=readBigEndianUbyte();
flyingSpeed=readBigEndianFloat();
fovModifier=readBigEndianFloat();
}
public static pure nothrow @safe PlayerAbilities fromBuffer(bool readId=true)(ubyte[] buffer) {
PlayerAbilities ret = new PlayerAbilities();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "PlayerAbilities(flags: " ~ std.conv.to!string(this.flags) ~ ", flyingSpeed: " ~ std.conv.to!string(this.flyingSpeed) ~ ", fovModifier: " ~ std.conv.to!string(this.fovModifier) ~ ")";
}
}
class CombatEvent : Buffer {
public enum uint ID = 44;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["eventId"];
public ubyte eventId;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ubyte eventId) {
this.eventId = eventId;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUbyte(eventId);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
eventId=readBigEndianUbyte();
}
public static pure nothrow @safe CombatEvent fromBuffer(bool readId=true)(ubyte[] buffer) {
CombatEvent ret = new CombatEvent();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "CombatEvent(eventId: " ~ std.conv.to!string(this.eventId) ~ ")";
}
alias _encode = encode;
enum string variantField = "eventId";
alias Variants = TypeTuple!(EnterCombat, EndCombat, EntityDead);
public class EnterCombat {
public enum typeof(eventId) EVENT_ID = 0;
public enum string[] FIELDS = [];
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
eventId = 0;
_encode!writeId();
return _buffer;
}
public pure nothrow @safe void decode() {
}
public override string toString() {
return "CombatEvent.EnterCombat()";
}
}
public class EndCombat {
public enum typeof(eventId) EVENT_ID = 1;
public enum string[] FIELDS = ["duration", "entityId"];
public uint duration;
public uint entityId;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint duration, uint entityId=uint.init) {
this.duration = duration;
this.entityId = entityId;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
eventId = 1;
_encode!writeId();
writeBytes(varuint.encode(duration));
writeBigEndianUint(entityId);
return _buffer;
}
public pure nothrow @safe void decode() {
duration=varuint.decode(_buffer, &_index);
entityId=readBigEndianUint();
}
public override string toString() {
return "CombatEvent.EndCombat(duration: " ~ std.conv.to!string(this.duration) ~ ", entityId: " ~ std.conv.to!string(this.entityId) ~ ")";
}
}
public class EntityDead {
public enum typeof(eventId) EVENT_ID = 2;
public enum string[] FIELDS = ["playerId", "entityId", "message"];
public uint playerId;
public uint entityId;
public string message;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint playerId, uint entityId=uint.init, string message=string.init) {
this.playerId = playerId;
this.entityId = entityId;
this.message = message;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
eventId = 2;
_encode!writeId();
writeBytes(varuint.encode(playerId));
writeBigEndianUint(entityId);
writeBytes(varuint.encode(cast(uint)message.length)); writeString(message);
return _buffer;
}
public pure nothrow @safe void decode() {
playerId=varuint.decode(_buffer, &_index);
entityId=readBigEndianUint();
uint bvcfz=varuint.decode(_buffer, &_index); message=readString(bvcfz);
}
public override string toString() {
return "CombatEvent.EntityDead(playerId: " ~ std.conv.to!string(this.playerId) ~ ", entityId: " ~ std.conv.to!string(this.entityId) ~ ", message: " ~ std.conv.to!string(this.message) ~ ")";
}
}
}
class PlayerListItem : Buffer {
public enum uint ID = 45;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["action"];
public uint action;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint action) {
this.action = action;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(action));
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
action=varuint.decode(_buffer, &_index);
}
public static pure nothrow @safe PlayerListItem fromBuffer(bool readId=true)(ubyte[] buffer) {
PlayerListItem ret = new PlayerListItem();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "PlayerListItem(action: " ~ std.conv.to!string(this.action) ~ ")";
}
alias _encode = encode;
enum string variantField = "action";
alias Variants = TypeTuple!(AddPlayer, UpdateGamemode, UpdateLatency, UpdateDisplayName, RemovePlayer);
public class AddPlayer {
public enum typeof(action) ACTION = 0;
public enum string[] FIELDS = ["players"];
public sul.protocol.java315.types.ListAddPlayer[] players;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(sul.protocol.java315.types.ListAddPlayer[] players) {
this.players = players;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 0;
_encode!writeId();
writeBytes(varuint.encode(cast(uint)players.length)); foreach(cxevc;players){ cxevc.encode(bufferInstance); }
return _buffer;
}
public pure nothrow @safe void decode() {
players.length=varuint.decode(_buffer, &_index); foreach(ref cxevc;players){ cxevc.decode(bufferInstance); }
}
public override string toString() {
return "PlayerListItem.AddPlayer(players: " ~ std.conv.to!string(this.players) ~ ")";
}
}
public class UpdateGamemode {
public enum typeof(action) ACTION = 1;
public enum string[] FIELDS = ["players"];
public sul.protocol.java315.types.ListUpdateGamemode[] players;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(sul.protocol.java315.types.ListUpdateGamemode[] players) {
this.players = players;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 1;
_encode!writeId();
writeBytes(varuint.encode(cast(uint)players.length)); foreach(cxevc;players){ cxevc.encode(bufferInstance); }
return _buffer;
}
public pure nothrow @safe void decode() {
players.length=varuint.decode(_buffer, &_index); foreach(ref cxevc;players){ cxevc.decode(bufferInstance); }
}
public override string toString() {
return "PlayerListItem.UpdateGamemode(players: " ~ std.conv.to!string(this.players) ~ ")";
}
}
public class UpdateLatency {
public enum typeof(action) ACTION = 2;
public enum string[] FIELDS = ["players"];
public sul.protocol.java315.types.ListUpdateLatency[] players;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(sul.protocol.java315.types.ListUpdateLatency[] players) {
this.players = players;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 2;
_encode!writeId();
writeBytes(varuint.encode(cast(uint)players.length)); foreach(cxevc;players){ cxevc.encode(bufferInstance); }
return _buffer;
}
public pure nothrow @safe void decode() {
players.length=varuint.decode(_buffer, &_index); foreach(ref cxevc;players){ cxevc.decode(bufferInstance); }
}
public override string toString() {
return "PlayerListItem.UpdateLatency(players: " ~ std.conv.to!string(this.players) ~ ")";
}
}
public class UpdateDisplayName {
public enum typeof(action) ACTION = 3;
public enum string[] FIELDS = ["players"];
public sul.protocol.java315.types.ListUpdateDisplayName[] players;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(sul.protocol.java315.types.ListUpdateDisplayName[] players) {
this.players = players;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 3;
_encode!writeId();
writeBytes(varuint.encode(cast(uint)players.length)); foreach(cxevc;players){ cxevc.encode(bufferInstance); }
return _buffer;
}
public pure nothrow @safe void decode() {
players.length=varuint.decode(_buffer, &_index); foreach(ref cxevc;players){ cxevc.decode(bufferInstance); }
}
public override string toString() {
return "PlayerListItem.UpdateDisplayName(players: " ~ std.conv.to!string(this.players) ~ ")";
}
}
public class RemovePlayer {
public enum typeof(action) ACTION = 4;
public enum string[] FIELDS = ["players"];
public UUID[] players;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(UUID[] players) {
this.players = players;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 4;
_encode!writeId();
writeBytes(varuint.encode(cast(uint)players.length)); foreach(cxevc;players){ writeBytes(cxevc.data); }
return _buffer;
}
public pure nothrow @safe void decode() {
players.length=varuint.decode(_buffer, &_index); foreach(ref cxevc;players){ if(_buffer.length>=_index+16){ ubyte[16] yhdm=_buffer[_index.._index+16].dup; _index+=16; cxevc=UUID(yhdm); } }
}
public override string toString() {
return "PlayerListItem.RemovePlayer(players: " ~ std.conv.to!string(this.players) ~ ")";
}
}
}
class PlayerPositionAndLook : Buffer {
public enum uint ID = 46;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// flags
public enum ubyte X = 1;
public enum ubyte Y = 2;
public enum ubyte Z = 4;
public enum ubyte Y_ROTATION = 8;
public enum ubyte X_ROTATION = 16;
public enum string[] FIELDS = ["position", "yaw", "pitch", "flags", "teleportId"];
public Tuple!(double, "x", double, "y", double, "z") position;
public float yaw;
public float pitch;
public ubyte flags;
public uint teleportId;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(Tuple!(double, "x", double, "y", double, "z") position, float yaw=float.init, float pitch=float.init, ubyte flags=ubyte.init, uint teleportId=uint.init) {
this.position = position;
this.yaw = yaw;
this.pitch = pitch;
this.flags = flags;
this.teleportId = teleportId;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianDouble(position.x); writeBigEndianDouble(position.y); writeBigEndianDouble(position.z);
writeBigEndianFloat(yaw);
writeBigEndianFloat(pitch);
writeBigEndianUbyte(flags);
writeBytes(varuint.encode(teleportId));
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
position.x=readBigEndianDouble(); position.y=readBigEndianDouble(); position.z=readBigEndianDouble();
yaw=readBigEndianFloat();
pitch=readBigEndianFloat();
flags=readBigEndianUbyte();
teleportId=varuint.decode(_buffer, &_index);
}
public static pure nothrow @safe PlayerPositionAndLook fromBuffer(bool readId=true)(ubyte[] buffer) {
PlayerPositionAndLook ret = new PlayerPositionAndLook();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "PlayerPositionAndLook(position: " ~ std.conv.to!string(this.position) ~ ", yaw: " ~ std.conv.to!string(this.yaw) ~ ", pitch: " ~ std.conv.to!string(this.pitch) ~ ", flags: " ~ std.conv.to!string(this.flags) ~ ", teleportId: " ~ std.conv.to!string(this.teleportId) ~ ")";
}
}
class UseBed : Buffer {
public enum uint ID = 47;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId", "position"];
public uint entityId;
public ulong position;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, ulong position=ulong.init) {
this.entityId = entityId;
this.position = position;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBigEndianUlong(position);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
position=readBigEndianUlong();
}
public static pure nothrow @safe UseBed fromBuffer(bool readId=true)(ubyte[] buffer) {
UseBed ret = new UseBed();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "UseBed(entityId: " ~ std.conv.to!string(this.entityId) ~ ", position: " ~ std.conv.to!string(this.position) ~ ")";
}
}
class DestroyEntities : Buffer {
public enum uint ID = 48;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityIds"];
public uint[] entityIds;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint[] entityIds) {
this.entityIds = entityIds;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(cast(uint)entityIds.length)); foreach(z5arsr;entityIds){ writeBytes(varuint.encode(z5arsr)); }
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityIds.length=varuint.decode(_buffer, &_index); foreach(ref z5arsr;entityIds){ z5arsr=varuint.decode(_buffer, &_index); }
}
public static pure nothrow @safe DestroyEntities fromBuffer(bool readId=true)(ubyte[] buffer) {
DestroyEntities ret = new DestroyEntities();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "DestroyEntities(entityIds: " ~ std.conv.to!string(this.entityIds) ~ ")";
}
}
class RemoveEntityEffect : Buffer {
public enum uint ID = 49;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId", "effectId"];
public uint entityId;
public ubyte effectId;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, ubyte effectId=ubyte.init) {
this.entityId = entityId;
this.effectId = effectId;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBigEndianUbyte(effectId);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
effectId=readBigEndianUbyte();
}
public static pure nothrow @safe RemoveEntityEffect fromBuffer(bool readId=true)(ubyte[] buffer) {
RemoveEntityEffect ret = new RemoveEntityEffect();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "RemoveEntityEffect(entityId: " ~ std.conv.to!string(this.entityId) ~ ", effectId: " ~ std.conv.to!string(this.effectId) ~ ")";
}
}
class ResourcePackSend : Buffer {
public enum uint ID = 50;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["url", "hash"];
public string url;
public string hash;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string url, string hash=string.init) {
this.url = url;
this.hash = hash;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(cast(uint)url.length)); writeString(url);
writeBytes(varuint.encode(cast(uint)hash.length)); writeString(hash);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
uint dj=varuint.decode(_buffer, &_index); url=readString(dj);
uint afa=varuint.decode(_buffer, &_index); hash=readString(afa);
}
public static pure nothrow @safe ResourcePackSend fromBuffer(bool readId=true)(ubyte[] buffer) {
ResourcePackSend ret = new ResourcePackSend();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "ResourcePackSend(url: " ~ std.conv.to!string(this.url) ~ ", hash: " ~ std.conv.to!string(this.hash) ~ ")";
}
}
class Respawn : Buffer {
public enum uint ID = 51;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// dimension
public enum int NETHER = -1;
public enum int OVERWORLD = 0;
public enum int END = 1;
// difficulty
public enum ubyte PEACEFUL = 0;
public enum ubyte EASY = 1;
public enum ubyte NORMAL = 2;
public enum ubyte HARD = 3;
// gamemode
public enum ubyte SURVIVAL = 0;
public enum ubyte CREATIVE = 1;
public enum ubyte ADVENTURE = 2;
public enum ubyte SPECTATOR = 3;
// level type
public enum string INFINITY = "default";
public enum string FLAT = "flat";
public enum string AMPLIFIED = "amplified";
public enum string LARGE_BIOMES = "largeBiomes";
public enum string[] FIELDS = ["dimension", "difficulty", "gamemode", "levelType"];
public int dimension;
public ubyte difficulty;
public ubyte gamemode;
public string levelType;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(int dimension, ubyte difficulty=ubyte.init, ubyte gamemode=ubyte.init, string levelType=string.init) {
this.dimension = dimension;
this.difficulty = difficulty;
this.gamemode = gamemode;
this.levelType = levelType;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianInt(dimension);
writeBigEndianUbyte(difficulty);
writeBigEndianUbyte(gamemode);
writeBytes(varuint.encode(cast(uint)levelType.length)); writeString(levelType);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
dimension=readBigEndianInt();
difficulty=readBigEndianUbyte();
gamemode=readBigEndianUbyte();
uint bvzxeb=varuint.decode(_buffer, &_index); levelType=readString(bvzxeb);
}
public static pure nothrow @safe Respawn fromBuffer(bool readId=true)(ubyte[] buffer) {
Respawn ret = new Respawn();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "Respawn(dimension: " ~ std.conv.to!string(this.dimension) ~ ", difficulty: " ~ std.conv.to!string(this.difficulty) ~ ", gamemode: " ~ std.conv.to!string(this.gamemode) ~ ", levelType: " ~ std.conv.to!string(this.levelType) ~ ")";
}
}
class EntityHeadLook : Buffer {
public enum uint ID = 52;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId", "headYaw"];
public uint entityId;
public ubyte headYaw;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, ubyte headYaw=ubyte.init) {
this.entityId = entityId;
this.headYaw = headYaw;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBigEndianUbyte(headYaw);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
headYaw=readBigEndianUbyte();
}
public static pure nothrow @safe EntityHeadLook fromBuffer(bool readId=true)(ubyte[] buffer) {
EntityHeadLook ret = new EntityHeadLook();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "EntityHeadLook(entityId: " ~ std.conv.to!string(this.entityId) ~ ", headYaw: " ~ std.conv.to!string(this.headYaw) ~ ")";
}
}
class WorldBorder : Buffer {
public enum uint ID = 53;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["action"];
public uint action;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint action) {
this.action = action;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(action));
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
action=varuint.decode(_buffer, &_index);
}
public static pure nothrow @safe WorldBorder fromBuffer(bool readId=true)(ubyte[] buffer) {
WorldBorder ret = new WorldBorder();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "WorldBorder(action: " ~ std.conv.to!string(this.action) ~ ")";
}
alias _encode = encode;
enum string variantField = "action";
alias Variants = TypeTuple!(SetSize, LerpSize, SetCenter, Initialize, SetWarningTime, SetWarningBlocks);
public class SetSize {
public enum typeof(action) ACTION = 0;
public enum string[] FIELDS = ["diameter"];
public double diameter;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(double diameter) {
this.diameter = diameter;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 0;
_encode!writeId();
writeBigEndianDouble(diameter);
return _buffer;
}
public pure nothrow @safe void decode() {
diameter=readBigEndianDouble();
}
public override string toString() {
return "WorldBorder.SetSize(diameter: " ~ std.conv.to!string(this.diameter) ~ ")";
}
}
public class LerpSize {
public enum typeof(action) ACTION = 1;
public enum string[] FIELDS = ["oldDiameter", "newDiameter", "speed"];
public double oldDiameter;
public double newDiameter;
public ulong speed;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(double oldDiameter, double newDiameter=double.init, ulong speed=ulong.init) {
this.oldDiameter = oldDiameter;
this.newDiameter = newDiameter;
this.speed = speed;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 1;
_encode!writeId();
writeBigEndianDouble(oldDiameter);
writeBigEndianDouble(newDiameter);
writeBytes(varulong.encode(speed));
return _buffer;
}
public pure nothrow @safe void decode() {
oldDiameter=readBigEndianDouble();
newDiameter=readBigEndianDouble();
speed=varulong.decode(_buffer, &_index);
}
public override string toString() {
return "WorldBorder.LerpSize(oldDiameter: " ~ std.conv.to!string(this.oldDiameter) ~ ", newDiameter: " ~ std.conv.to!string(this.newDiameter) ~ ", speed: " ~ std.conv.to!string(this.speed) ~ ")";
}
}
public class SetCenter {
public enum typeof(action) ACTION = 2;
public enum string[] FIELDS = ["center"];
public Tuple!(double, "x", double, "y", double, "z") center;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(Tuple!(double, "x", double, "y", double, "z") center) {
this.center = center;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 2;
_encode!writeId();
writeBigEndianDouble(center.x); writeBigEndianDouble(center.y); writeBigEndianDouble(center.z);
return _buffer;
}
public pure nothrow @safe void decode() {
center.x=readBigEndianDouble(); center.y=readBigEndianDouble(); center.z=readBigEndianDouble();
}
public override string toString() {
return "WorldBorder.SetCenter(center: " ~ std.conv.to!string(this.center) ~ ")";
}
}
public class Initialize {
public enum typeof(action) ACTION = 3;
public enum string[] FIELDS = ["center", "oldDiameter", "newDiameter", "speed", "portalTeleportBoundary", "warningTime", "warningBlocks"];
public Tuple!(double, "x", double, "y", double, "z") center;
public double oldDiameter;
public double newDiameter;
public ulong speed;
public uint portalTeleportBoundary;
public uint warningTime;
public uint warningBlocks;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(Tuple!(double, "x", double, "y", double, "z") center, double oldDiameter=double.init, double newDiameter=double.init, ulong speed=ulong.init, uint portalTeleportBoundary=uint.init, uint warningTime=uint.init, uint warningBlocks=uint.init) {
this.center = center;
this.oldDiameter = oldDiameter;
this.newDiameter = newDiameter;
this.speed = speed;
this.portalTeleportBoundary = portalTeleportBoundary;
this.warningTime = warningTime;
this.warningBlocks = warningBlocks;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 3;
_encode!writeId();
writeBigEndianDouble(center.x); writeBigEndianDouble(center.y); writeBigEndianDouble(center.z);
writeBigEndianDouble(oldDiameter);
writeBigEndianDouble(newDiameter);
writeBytes(varulong.encode(speed));
writeBytes(varuint.encode(portalTeleportBoundary));
writeBytes(varuint.encode(warningTime));
writeBytes(varuint.encode(warningBlocks));
return _buffer;
}
public pure nothrow @safe void decode() {
center.x=readBigEndianDouble(); center.y=readBigEndianDouble(); center.z=readBigEndianDouble();
oldDiameter=readBigEndianDouble();
newDiameter=readBigEndianDouble();
speed=varulong.decode(_buffer, &_index);
portalTeleportBoundary=varuint.decode(_buffer, &_index);
warningTime=varuint.decode(_buffer, &_index);
warningBlocks=varuint.decode(_buffer, &_index);
}
public override string toString() {
return "WorldBorder.Initialize(center: " ~ std.conv.to!string(this.center) ~ ", oldDiameter: " ~ std.conv.to!string(this.oldDiameter) ~ ", newDiameter: " ~ std.conv.to!string(this.newDiameter) ~ ", speed: " ~ std.conv.to!string(this.speed) ~ ", portalTeleportBoundary: " ~ std.conv.to!string(this.portalTeleportBoundary) ~ ", warningTime: " ~ std.conv.to!string(this.warningTime) ~ ", warningBlocks: " ~ std.conv.to!string(this.warningBlocks) ~ ")";
}
}
public class SetWarningTime {
public enum typeof(action) ACTION = 4;
public enum string[] FIELDS = ["warningTime"];
public uint warningTime;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint warningTime) {
this.warningTime = warningTime;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 4;
_encode!writeId();
writeBytes(varuint.encode(warningTime));
return _buffer;
}
public pure nothrow @safe void decode() {
warningTime=varuint.decode(_buffer, &_index);
}
public override string toString() {
return "WorldBorder.SetWarningTime(warningTime: " ~ std.conv.to!string(this.warningTime) ~ ")";
}
}
public class SetWarningBlocks {
public enum typeof(action) ACTION = 5;
public enum string[] FIELDS = ["warningBlocks"];
public uint warningBlocks;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint warningBlocks) {
this.warningBlocks = warningBlocks;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 5;
_encode!writeId();
writeBytes(varuint.encode(warningBlocks));
return _buffer;
}
public pure nothrow @safe void decode() {
warningBlocks=varuint.decode(_buffer, &_index);
}
public override string toString() {
return "WorldBorder.SetWarningBlocks(warningBlocks: " ~ std.conv.to!string(this.warningBlocks) ~ ")";
}
}
}
class Camera : Buffer {
public enum uint ID = 54;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId"];
public uint entityId;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId) {
this.entityId = entityId;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
}
public static pure nothrow @safe Camera fromBuffer(bool readId=true)(ubyte[] buffer) {
Camera ret = new Camera();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "Camera(entityId: " ~ std.conv.to!string(this.entityId) ~ ")";
}
}
class HeldItemChange : Buffer {
public enum uint ID = 55;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["slot"];
public ubyte slot;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ubyte slot) {
this.slot = slot;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUbyte(slot);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
slot=readBigEndianUbyte();
}
public static pure nothrow @safe HeldItemChange fromBuffer(bool readId=true)(ubyte[] buffer) {
HeldItemChange ret = new HeldItemChange();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "HeldItemChange(slot: " ~ std.conv.to!string(this.slot) ~ ")";
}
}
class DisplayScoreboard : Buffer {
public enum uint ID = 56;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// position
public enum ubyte LIST = 0;
public enum ubyte SIDEBAR = 1;
public enum ubyte BELOW_NAME = 2;
public enum string[] FIELDS = ["position", "scoreName"];
public ubyte position;
public string scoreName;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ubyte position, string scoreName=string.init) {
this.position = position;
this.scoreName = scoreName;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUbyte(position);
writeBytes(varuint.encode(cast(uint)scoreName.length)); writeString(scoreName);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
position=readBigEndianUbyte();
uint cncvy1=varuint.decode(_buffer, &_index); scoreName=readString(cncvy1);
}
public static pure nothrow @safe DisplayScoreboard fromBuffer(bool readId=true)(ubyte[] buffer) {
DisplayScoreboard ret = new DisplayScoreboard();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "DisplayScoreboard(position: " ~ std.conv.to!string(this.position) ~ ", scoreName: " ~ std.conv.to!string(this.scoreName) ~ ")";
}
}
class EntityMetadata : Buffer {
public enum uint ID = 57;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId", "metadata"];
public uint entityId;
public Metadata metadata;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, Metadata metadata=Metadata.init) {
this.entityId = entityId;
this.metadata = metadata;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
metadata.encode(bufferInstance);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
metadata=Metadata.decode(bufferInstance);
}
public static pure nothrow @safe EntityMetadata fromBuffer(bool readId=true)(ubyte[] buffer) {
EntityMetadata ret = new EntityMetadata();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "EntityMetadata(entityId: " ~ std.conv.to!string(this.entityId) ~ ", metadata: " ~ std.conv.to!string(this.metadata) ~ ")";
}
}
class AttachEntity : Buffer {
public enum uint ID = 58;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["target", "holder"];
public uint target;
public uint holder;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint target, uint holder=uint.init) {
this.target = target;
this.holder = holder;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUint(target);
writeBigEndianUint(holder);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
target=readBigEndianUint();
holder=readBigEndianUint();
}
public static pure nothrow @safe AttachEntity fromBuffer(bool readId=true)(ubyte[] buffer) {
AttachEntity ret = new AttachEntity();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "AttachEntity(target: " ~ std.conv.to!string(this.target) ~ ", holder: " ~ std.conv.to!string(this.holder) ~ ")";
}
}
class EntityVelocity : Buffer {
public enum uint ID = 59;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId", "velocity"];
public uint entityId;
public Tuple!(short, "x", short, "y", short, "z") velocity;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, Tuple!(short, "x", short, "y", short, "z") velocity=Tuple!(short, "x", short, "y", short, "z").init) {
this.entityId = entityId;
this.velocity = velocity;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBigEndianShort(velocity.x); writeBigEndianShort(velocity.y); writeBigEndianShort(velocity.z);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
velocity.x=readBigEndianShort(); velocity.y=readBigEndianShort(); velocity.z=readBigEndianShort();
}
public static pure nothrow @safe EntityVelocity fromBuffer(bool readId=true)(ubyte[] buffer) {
EntityVelocity ret = new EntityVelocity();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "EntityVelocity(entityId: " ~ std.conv.to!string(this.entityId) ~ ", velocity: " ~ std.conv.to!string(this.velocity) ~ ")";
}
}
class EntityEquipment : Buffer {
public enum uint ID = 60;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId", "slot", "item"];
public uint entityId;
public uint slot;
public sul.protocol.java315.types.Slot item;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, uint slot=uint.init, sul.protocol.java315.types.Slot item=sul.protocol.java315.types.Slot.init) {
this.entityId = entityId;
this.slot = slot;
this.item = item;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBytes(varuint.encode(slot));
item.encode(bufferInstance);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
slot=varuint.decode(_buffer, &_index);
item.decode(bufferInstance);
}
public static pure nothrow @safe EntityEquipment fromBuffer(bool readId=true)(ubyte[] buffer) {
EntityEquipment ret = new EntityEquipment();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "EntityEquipment(entityId: " ~ std.conv.to!string(this.entityId) ~ ", slot: " ~ std.conv.to!string(this.slot) ~ ", item: " ~ std.conv.to!string(this.item) ~ ")";
}
}
class SetExperience : Buffer {
public enum uint ID = 61;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["experience", "level", "totalExperience"];
public float experience;
public uint level;
public uint totalExperience;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(float experience, uint level=uint.init, uint totalExperience=uint.init) {
this.experience = experience;
this.level = level;
this.totalExperience = totalExperience;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianFloat(experience);
writeBytes(varuint.encode(level));
writeBytes(varuint.encode(totalExperience));
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
experience=readBigEndianFloat();
level=varuint.decode(_buffer, &_index);
totalExperience=varuint.decode(_buffer, &_index);
}
public static pure nothrow @safe SetExperience fromBuffer(bool readId=true)(ubyte[] buffer) {
SetExperience ret = new SetExperience();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "SetExperience(experience: " ~ std.conv.to!string(this.experience) ~ ", level: " ~ std.conv.to!string(this.level) ~ ", totalExperience: " ~ std.conv.to!string(this.totalExperience) ~ ")";
}
}
class UpdateHealth : Buffer {
public enum uint ID = 62;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["health", "hunger", "saturation"];
public float health;
public uint hunger;
public float saturation;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(float health, uint hunger=uint.init, float saturation=float.init) {
this.health = health;
this.hunger = hunger;
this.saturation = saturation;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianFloat(health);
writeBytes(varuint.encode(hunger));
writeBigEndianFloat(saturation);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
health=readBigEndianFloat();
hunger=varuint.decode(_buffer, &_index);
saturation=readBigEndianFloat();
}
public static pure nothrow @safe UpdateHealth fromBuffer(bool readId=true)(ubyte[] buffer) {
UpdateHealth ret = new UpdateHealth();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "UpdateHealth(health: " ~ std.conv.to!string(this.health) ~ ", hunger: " ~ std.conv.to!string(this.hunger) ~ ", saturation: " ~ std.conv.to!string(this.saturation) ~ ")";
}
}
class ScoreboardObjective : Buffer {
public enum uint ID = 63;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// mode
public enum ubyte CREATE = 0;
public enum ubyte REMOVE = 1;
public enum ubyte UPDATE = 2;
// type
public enum string NUMERIC = "integer";
public enum string GRAPHIC = "hearts";
public enum string[] FIELDS = ["name", "mode", "value", "type"];
public string name;
public ubyte mode;
public string value;
public string type;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string name, ubyte mode=ubyte.init, string value=string.init, string type=string.init) {
this.name = name;
this.mode = mode;
this.value = value;
this.type = type;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(cast(uint)name.length)); writeString(name);
writeBigEndianUbyte(mode);
if(mode!=1){ writeBytes(varuint.encode(cast(uint)value.length)); writeString(value); }
if(mode!=1){ writeBytes(varuint.encode(cast(uint)type.length)); writeString(type); }
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
uint bfz=varuint.decode(_buffer, &_index); name=readString(bfz);
mode=readBigEndianUbyte();
if(mode!=1){ uint dfdu=varuint.decode(_buffer, &_index); value=readString(dfdu); }
if(mode!=1){ uint dlz=varuint.decode(_buffer, &_index); type=readString(dlz); }
}
public static pure nothrow @safe ScoreboardObjective fromBuffer(bool readId=true)(ubyte[] buffer) {
ScoreboardObjective ret = new ScoreboardObjective();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "ScoreboardObjective(name: " ~ std.conv.to!string(this.name) ~ ", mode: " ~ std.conv.to!string(this.mode) ~ ", value: " ~ std.conv.to!string(this.value) ~ ", type: " ~ std.conv.to!string(this.type) ~ ")";
}
}
class SetPassengers : Buffer {
public enum uint ID = 64;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId", "passengers"];
public uint entityId;
public uint[] passengers;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, uint[] passengers=(uint[]).init) {
this.entityId = entityId;
this.passengers = passengers;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBytes(varuint.encode(cast(uint)passengers.length)); foreach(cfcvzvc;passengers){ writeBytes(varuint.encode(cfcvzvc)); }
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
passengers.length=varuint.decode(_buffer, &_index); foreach(ref cfcvzvc;passengers){ cfcvzvc=varuint.decode(_buffer, &_index); }
}
public static pure nothrow @safe SetPassengers fromBuffer(bool readId=true)(ubyte[] buffer) {
SetPassengers ret = new SetPassengers();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "SetPassengers(entityId: " ~ std.conv.to!string(this.entityId) ~ ", passengers: " ~ std.conv.to!string(this.passengers) ~ ")";
}
}
class Teams : Buffer {
public enum uint ID = 65;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["name", "mode"];
public string name;
public ubyte mode;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string name, ubyte mode=ubyte.init) {
this.name = name;
this.mode = mode;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(cast(uint)name.length)); writeString(name);
writeBigEndianUbyte(mode);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
uint bfz=varuint.decode(_buffer, &_index); name=readString(bfz);
mode=readBigEndianUbyte();
}
public static pure nothrow @safe Teams fromBuffer(bool readId=true)(ubyte[] buffer) {
Teams ret = new Teams();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "Teams(name: " ~ std.conv.to!string(this.name) ~ ", mode: " ~ std.conv.to!string(this.mode) ~ ")";
}
alias _encode = encode;
enum string variantField = "mode";
alias Variants = TypeTuple!(CreateTeam, RemoveTeam, UpdateTeamInfo, AddPlayers, RemovePlayers);
public class CreateTeam {
public enum typeof(mode) MODE = 0;
// friendly flags
public enum ubyte FRIENDLY_FIRE = 1;
public enum ubyte SEE_TEAM_INVISIBLE_PLAYERS = 2;
// nametag visibility
public enum string ALWAYS_HIDE = "always";
public enum string HIDE_OTHER_TEAMS = "hideOtherTeams";
public enum string HIDE_OWN_TEAM = "hideOwnTeam";
public enum string NEVER_HIDE = "never";
// collision rule
public enum string ALWAYS_PUSH = "always";
public enum string PUSH_OTHER_TEAMS = "pushOtherTeams";
public enum string PUSH_OWN_TEAM = "pushOwnTeam";
public enum string NEVER_PUSH = "never";
public enum string[] FIELDS = ["displayName", "prefix", "suffix", "friendlyFlags", "nametagVisibility", "collisionRule", "color", "players"];
public string displayName;
public string prefix;
public string suffix;
public ubyte friendlyFlags;
public string nametagVisibility;
public string collisionRule;
public ubyte color;
public string[] players;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string displayName, string prefix=string.init, string suffix=string.init, ubyte friendlyFlags=ubyte.init, string nametagVisibility=string.init, string collisionRule=string.init, ubyte color=ubyte.init, string[] players=(string[]).init) {
this.displayName = displayName;
this.prefix = prefix;
this.suffix = suffix;
this.friendlyFlags = friendlyFlags;
this.nametagVisibility = nametagVisibility;
this.collisionRule = collisionRule;
this.color = color;
this.players = players;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
mode = 0;
_encode!writeId();
writeBytes(varuint.encode(cast(uint)displayName.length)); writeString(displayName);
writeBytes(varuint.encode(cast(uint)prefix.length)); writeString(prefix);
writeBytes(varuint.encode(cast(uint)suffix.length)); writeString(suffix);
writeBigEndianUbyte(friendlyFlags);
writeBytes(varuint.encode(cast(uint)nametagVisibility.length)); writeString(nametagVisibility);
writeBytes(varuint.encode(cast(uint)collisionRule.length)); writeString(collisionRule);
writeBigEndianUbyte(color);
writeBytes(varuint.encode(cast(uint)players.length)); foreach(cxevc;players){ writeBytes(varuint.encode(cast(uint)cxevc.length)); writeString(cxevc); }
return _buffer;
}
public pure nothrow @safe void decode() {
uint zlcxe5bu=varuint.decode(_buffer, &_index); displayName=readString(zlcxe5bu);
uint cjzl=varuint.decode(_buffer, &_index); prefix=readString(cjzl);
uint cvzl=varuint.decode(_buffer, &_index); suffix=readString(cvzl);
friendlyFlags=readBigEndianUbyte();
uint bfzrzzcl=varuint.decode(_buffer, &_index); nametagVisibility=readString(bfzrzzcl);
uint y9bla9uv=varuint.decode(_buffer, &_index); collisionRule=readString(y9bla9uv);
color=readBigEndianUbyte();
players.length=varuint.decode(_buffer, &_index); foreach(ref cxevc;players){ uint yhdm=varuint.decode(_buffer, &_index); cxevc=readString(yhdm); }
}
public override string toString() {
return "Teams.CreateTeam(displayName: " ~ std.conv.to!string(this.displayName) ~ ", prefix: " ~ std.conv.to!string(this.prefix) ~ ", suffix: " ~ std.conv.to!string(this.suffix) ~ ", friendlyFlags: " ~ std.conv.to!string(this.friendlyFlags) ~ ", nametagVisibility: " ~ std.conv.to!string(this.nametagVisibility) ~ ", collisionRule: " ~ std.conv.to!string(this.collisionRule) ~ ", color: " ~ std.conv.to!string(this.color) ~ ", players: " ~ std.conv.to!string(this.players) ~ ")";
}
}
public class RemoveTeam {
public enum typeof(mode) MODE = 1;
public enum string[] FIELDS = [];
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
mode = 1;
_encode!writeId();
return _buffer;
}
public pure nothrow @safe void decode() {
}
public override string toString() {
return "Teams.RemoveTeam()";
}
}
public class UpdateTeamInfo {
public enum typeof(mode) MODE = 2;
// friendly flags
public enum ubyte FRIENDLY_FIRE = 1;
public enum ubyte SEE_TEAM_INVISIBLE_PLAYERS = 2;
// nametag visibility
public enum string ALWAYS_HIDE = "always";
public enum string HIDE_OTHER_TEAMS = "hideOtherTeams";
public enum string HIDE_OWN_TEAM = "hideOwnTeam";
public enum string NEVER_HIDE = "never";
// collision rule
public enum string ALWAYS_PUSH = "always";
public enum string PUSH_OTHER_TEAMS = "pushOtherTeams";
public enum string PUSH_OWN_TEAM = "pushOwnTeam";
public enum string NEVER_PUSH = "never";
public enum string[] FIELDS = ["displayName", "prefix", "suffix", "friendlyFlags", "nametagVisibility", "collisionRule", "color"];
public string displayName;
public string prefix;
public string suffix;
public ubyte friendlyFlags;
public string nametagVisibility;
public string collisionRule;
public ubyte color;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string displayName, string prefix=string.init, string suffix=string.init, ubyte friendlyFlags=ubyte.init, string nametagVisibility=string.init, string collisionRule=string.init, ubyte color=ubyte.init) {
this.displayName = displayName;
this.prefix = prefix;
this.suffix = suffix;
this.friendlyFlags = friendlyFlags;
this.nametagVisibility = nametagVisibility;
this.collisionRule = collisionRule;
this.color = color;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
mode = 2;
_encode!writeId();
writeBytes(varuint.encode(cast(uint)displayName.length)); writeString(displayName);
writeBytes(varuint.encode(cast(uint)prefix.length)); writeString(prefix);
writeBytes(varuint.encode(cast(uint)suffix.length)); writeString(suffix);
writeBigEndianUbyte(friendlyFlags);
writeBytes(varuint.encode(cast(uint)nametagVisibility.length)); writeString(nametagVisibility);
writeBytes(varuint.encode(cast(uint)collisionRule.length)); writeString(collisionRule);
writeBigEndianUbyte(color);
return _buffer;
}
public pure nothrow @safe void decode() {
uint zlcxe5bu=varuint.decode(_buffer, &_index); displayName=readString(zlcxe5bu);
uint cjzl=varuint.decode(_buffer, &_index); prefix=readString(cjzl);
uint cvzl=varuint.decode(_buffer, &_index); suffix=readString(cvzl);
friendlyFlags=readBigEndianUbyte();
uint bfzrzzcl=varuint.decode(_buffer, &_index); nametagVisibility=readString(bfzrzzcl);
uint y9bla9uv=varuint.decode(_buffer, &_index); collisionRule=readString(y9bla9uv);
color=readBigEndianUbyte();
}
public override string toString() {
return "Teams.UpdateTeamInfo(displayName: " ~ std.conv.to!string(this.displayName) ~ ", prefix: " ~ std.conv.to!string(this.prefix) ~ ", suffix: " ~ std.conv.to!string(this.suffix) ~ ", friendlyFlags: " ~ std.conv.to!string(this.friendlyFlags) ~ ", nametagVisibility: " ~ std.conv.to!string(this.nametagVisibility) ~ ", collisionRule: " ~ std.conv.to!string(this.collisionRule) ~ ", color: " ~ std.conv.to!string(this.color) ~ ")";
}
}
public class AddPlayers {
public enum typeof(mode) MODE = 3;
public enum string[] FIELDS = ["players"];
public string[] players;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string[] players) {
this.players = players;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
mode = 3;
_encode!writeId();
writeBytes(varuint.encode(cast(uint)players.length)); foreach(cxevc;players){ writeBytes(varuint.encode(cast(uint)cxevc.length)); writeString(cxevc); }
return _buffer;
}
public pure nothrow @safe void decode() {
players.length=varuint.decode(_buffer, &_index); foreach(ref cxevc;players){ uint yhdm=varuint.decode(_buffer, &_index); cxevc=readString(yhdm); }
}
public override string toString() {
return "Teams.AddPlayers(players: " ~ std.conv.to!string(this.players) ~ ")";
}
}
public class RemovePlayers {
public enum typeof(mode) MODE = 4;
public enum string[] FIELDS = ["players"];
public string[] players;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string[] players) {
this.players = players;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
mode = 4;
_encode!writeId();
writeBytes(varuint.encode(cast(uint)players.length)); foreach(cxevc;players){ writeBytes(varuint.encode(cast(uint)cxevc.length)); writeString(cxevc); }
return _buffer;
}
public pure nothrow @safe void decode() {
players.length=varuint.decode(_buffer, &_index); foreach(ref cxevc;players){ uint yhdm=varuint.decode(_buffer, &_index); cxevc=readString(yhdm); }
}
public override string toString() {
return "Teams.RemovePlayers(players: " ~ std.conv.to!string(this.players) ~ ")";
}
}
}
class UpdateScore : Buffer {
public enum uint ID = 66;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// action
public enum ubyte UPDATE = 0;
public enum ubyte REMOVE = 1;
public enum string[] FIELDS = ["scoreName", "action", "objectiveName", "value"];
public string scoreName;
public ubyte action;
public string objectiveName;
public uint value;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string scoreName, ubyte action=ubyte.init, string objectiveName=string.init, uint value=uint.init) {
this.scoreName = scoreName;
this.action = action;
this.objectiveName = objectiveName;
this.value = value;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(cast(uint)scoreName.length)); writeString(scoreName);
writeBigEndianUbyte(action);
writeBytes(varuint.encode(cast(uint)objectiveName.length)); writeString(objectiveName);
if(action==0){ writeBytes(varuint.encode(value)); }
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
uint cncvy1=varuint.decode(_buffer, &_index); scoreName=readString(cncvy1);
action=readBigEndianUbyte();
uint bjznaztf=varuint.decode(_buffer, &_index); objectiveName=readString(bjznaztf);
if(action==0){ value=varuint.decode(_buffer, &_index); }
}
public static pure nothrow @safe UpdateScore fromBuffer(bool readId=true)(ubyte[] buffer) {
UpdateScore ret = new UpdateScore();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "UpdateScore(scoreName: " ~ std.conv.to!string(this.scoreName) ~ ", action: " ~ std.conv.to!string(this.action) ~ ", objectiveName: " ~ std.conv.to!string(this.objectiveName) ~ ", value: " ~ std.conv.to!string(this.value) ~ ")";
}
}
class SpawnPosition : Buffer {
public enum uint ID = 67;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["position"];
public ulong position;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ulong position) {
this.position = position;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUlong(position);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
position=readBigEndianUlong();
}
public static pure nothrow @safe SpawnPosition fromBuffer(bool readId=true)(ubyte[] buffer) {
SpawnPosition ret = new SpawnPosition();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "SpawnPosition(position: " ~ std.conv.to!string(this.position) ~ ")";
}
}
class TimeUpdate : Buffer {
public enum uint ID = 68;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["worldAge", "time"];
public ulong worldAge;
public long time;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(ulong worldAge, long time=long.init) {
this.worldAge = worldAge;
this.time = time;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBigEndianUlong(worldAge);
writeBigEndianLong(time);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
worldAge=readBigEndianUlong();
time=readBigEndianLong();
}
public static pure nothrow @safe TimeUpdate fromBuffer(bool readId=true)(ubyte[] buffer) {
TimeUpdate ret = new TimeUpdate();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "TimeUpdate(worldAge: " ~ std.conv.to!string(this.worldAge) ~ ", time: " ~ std.conv.to!string(this.time) ~ ")";
}
}
class Title : Buffer {
public enum uint ID = 69;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["action"];
public uint action;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint action) {
this.action = action;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(action));
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
action=varuint.decode(_buffer, &_index);
}
public static pure nothrow @safe Title fromBuffer(bool readId=true)(ubyte[] buffer) {
Title ret = new Title();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "Title(action: " ~ std.conv.to!string(this.action) ~ ")";
}
alias _encode = encode;
enum string variantField = "action";
alias Variants = TypeTuple!(SetTitle, SetSubtitle, SetActionBar, SetTimings, Hide, Reset);
public class SetTitle {
public enum typeof(action) ACTION = 0;
public enum string[] FIELDS = ["text"];
public string text;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string text) {
this.text = text;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 0;
_encode!writeId();
writeBytes(varuint.encode(cast(uint)text.length)); writeString(text);
return _buffer;
}
public pure nothrow @safe void decode() {
uint dvd=varuint.decode(_buffer, &_index); text=readString(dvd);
}
public override string toString() {
return "Title.SetTitle(text: " ~ std.conv.to!string(this.text) ~ ")";
}
}
public class SetSubtitle {
public enum typeof(action) ACTION = 1;
public enum string[] FIELDS = ["text"];
public string text;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string text) {
this.text = text;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 1;
_encode!writeId();
writeBytes(varuint.encode(cast(uint)text.length)); writeString(text);
return _buffer;
}
public pure nothrow @safe void decode() {
uint dvd=varuint.decode(_buffer, &_index); text=readString(dvd);
}
public override string toString() {
return "Title.SetSubtitle(text: " ~ std.conv.to!string(this.text) ~ ")";
}
}
public class SetActionBar {
public enum typeof(action) ACTION = 2;
public enum string[] FIELDS = ["text"];
public string text;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string text) {
this.text = text;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 2;
_encode!writeId();
writeBytes(varuint.encode(cast(uint)text.length)); writeString(text);
return _buffer;
}
public pure nothrow @safe void decode() {
uint dvd=varuint.decode(_buffer, &_index); text=readString(dvd);
}
public override string toString() {
return "Title.SetActionBar(text: " ~ std.conv.to!string(this.text) ~ ")";
}
}
public class SetTimings {
public enum typeof(action) ACTION = 3;
public enum string[] FIELDS = ["fadeIn", "stay", "fadeOut"];
public uint fadeIn;
public uint stay;
public uint fadeOut;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint fadeIn, uint stay=uint.init, uint fadeOut=uint.init) {
this.fadeIn = fadeIn;
this.stay = stay;
this.fadeOut = fadeOut;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 3;
_encode!writeId();
writeBigEndianUint(fadeIn);
writeBigEndianUint(stay);
writeBigEndianUint(fadeOut);
return _buffer;
}
public pure nothrow @safe void decode() {
fadeIn=readBigEndianUint();
stay=readBigEndianUint();
fadeOut=readBigEndianUint();
}
public override string toString() {
return "Title.SetTimings(fadeIn: " ~ std.conv.to!string(this.fadeIn) ~ ", stay: " ~ std.conv.to!string(this.stay) ~ ", fadeOut: " ~ std.conv.to!string(this.fadeOut) ~ ")";
}
}
public class Hide {
public enum typeof(action) ACTION = 4;
public enum string[] FIELDS = [];
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 4;
_encode!writeId();
return _buffer;
}
public pure nothrow @safe void decode() {
}
public override string toString() {
return "Title.Hide()";
}
}
public class Reset {
public enum typeof(action) ACTION = 5;
public enum string[] FIELDS = [];
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
action = 5;
_encode!writeId();
return _buffer;
}
public pure nothrow @safe void decode() {
}
public override string toString() {
return "Title.Reset()";
}
}
}
class SoundEffect : Buffer {
public enum uint ID = 70;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["soundId", "category", "position", "volume", "pitch"];
public uint soundId;
public uint category;
public Tuple!(int, "x", int, "y", int, "z") position;
public float volume;
public float pitch;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint soundId, uint category=uint.init, Tuple!(int, "x", int, "y", int, "z") position=Tuple!(int, "x", int, "y", int, "z").init, float volume=float.init, float pitch=float.init) {
this.soundId = soundId;
this.category = category;
this.position = position;
this.volume = volume;
this.pitch = pitch;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(soundId));
writeBytes(varuint.encode(category));
writeBigEndianInt(position.x); writeBigEndianInt(position.y); writeBigEndianInt(position.z);
writeBigEndianFloat(volume);
writeBigEndianFloat(pitch);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
soundId=varuint.decode(_buffer, &_index);
category=varuint.decode(_buffer, &_index);
position.x=readBigEndianInt(); position.y=readBigEndianInt(); position.z=readBigEndianInt();
volume=readBigEndianFloat();
pitch=readBigEndianFloat();
}
public static pure nothrow @safe SoundEffect fromBuffer(bool readId=true)(ubyte[] buffer) {
SoundEffect ret = new SoundEffect();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "SoundEffect(soundId: " ~ std.conv.to!string(this.soundId) ~ ", category: " ~ std.conv.to!string(this.category) ~ ", position: " ~ std.conv.to!string(this.position) ~ ", volume: " ~ std.conv.to!string(this.volume) ~ ", pitch: " ~ std.conv.to!string(this.pitch) ~ ")";
}
}
class PlayerListHeaderAndFooter : Buffer {
public enum uint ID = 71;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["header", "footer"];
public string header;
public string footer;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(string header, string footer=string.init) {
this.header = header;
this.footer = footer;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(cast(uint)header.length)); writeString(header);
writeBytes(varuint.encode(cast(uint)footer.length)); writeString(footer);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
uint avzv=varuint.decode(_buffer, &_index); header=readString(avzv);
uint z9dv=varuint.decode(_buffer, &_index); footer=readString(z9dv);
}
public static pure nothrow @safe PlayerListHeaderAndFooter fromBuffer(bool readId=true)(ubyte[] buffer) {
PlayerListHeaderAndFooter ret = new PlayerListHeaderAndFooter();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "PlayerListHeaderAndFooter(header: " ~ std.conv.to!string(this.header) ~ ", footer: " ~ std.conv.to!string(this.footer) ~ ")";
}
}
class CollectItem : Buffer {
public enum uint ID = 72;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["collected", "collector", "count"];
public uint collected;
public uint collector;
public uint count;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint collected, uint collector=uint.init, uint count=uint.init) {
this.collected = collected;
this.collector = collector;
this.count = count;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(collected));
writeBytes(varuint.encode(collector));
writeBytes(varuint.encode(count));
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
collected=varuint.decode(_buffer, &_index);
collector=varuint.decode(_buffer, &_index);
count=varuint.decode(_buffer, &_index);
}
public static pure nothrow @safe CollectItem fromBuffer(bool readId=true)(ubyte[] buffer) {
CollectItem ret = new CollectItem();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "CollectItem(collected: " ~ std.conv.to!string(this.collected) ~ ", collector: " ~ std.conv.to!string(this.collector) ~ ", count: " ~ std.conv.to!string(this.count) ~ ")";
}
}
class EntityTeleport : Buffer {
public enum uint ID = 73;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId", "position", "yaw", "pitch", "onGround"];
public uint entityId;
public Tuple!(double, "x", double, "y", double, "z") position;
public ubyte yaw;
public ubyte pitch;
public bool onGround;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, Tuple!(double, "x", double, "y", double, "z") position=Tuple!(double, "x", double, "y", double, "z").init, ubyte yaw=ubyte.init, ubyte pitch=ubyte.init, bool onGround=bool.init) {
this.entityId = entityId;
this.position = position;
this.yaw = yaw;
this.pitch = pitch;
this.onGround = onGround;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBigEndianDouble(position.x); writeBigEndianDouble(position.y); writeBigEndianDouble(position.z);
writeBigEndianUbyte(yaw);
writeBigEndianUbyte(pitch);
writeBigEndianBool(onGround);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
position.x=readBigEndianDouble(); position.y=readBigEndianDouble(); position.z=readBigEndianDouble();
yaw=readBigEndianUbyte();
pitch=readBigEndianUbyte();
onGround=readBigEndianBool();
}
public static pure nothrow @safe EntityTeleport fromBuffer(bool readId=true)(ubyte[] buffer) {
EntityTeleport ret = new EntityTeleport();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "EntityTeleport(entityId: " ~ std.conv.to!string(this.entityId) ~ ", position: " ~ std.conv.to!string(this.position) ~ ", yaw: " ~ std.conv.to!string(this.yaw) ~ ", pitch: " ~ std.conv.to!string(this.pitch) ~ ", onGround: " ~ std.conv.to!string(this.onGround) ~ ")";
}
}
class EntityProperties : Buffer {
public enum uint ID = 74;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
public enum string[] FIELDS = ["entityId", "attributes"];
public uint entityId;
public sul.protocol.java315.types.Attribute[] attributes;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, sul.protocol.java315.types.Attribute[] attributes=(sul.protocol.java315.types.Attribute[]).init) {
this.entityId = entityId;
this.attributes = attributes;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBigEndianUint(cast(uint)attributes.length); foreach(yrcldrc;attributes){ yrcldrc.encode(bufferInstance); }
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
attributes.length=readBigEndianUint(); foreach(ref yrcldrc;attributes){ yrcldrc.decode(bufferInstance); }
}
public static pure nothrow @safe EntityProperties fromBuffer(bool readId=true)(ubyte[] buffer) {
EntityProperties ret = new EntityProperties();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "EntityProperties(entityId: " ~ std.conv.to!string(this.entityId) ~ ", attributes: " ~ std.conv.to!string(this.attributes) ~ ")";
}
}
class EntityEffect : Buffer {
public enum uint ID = 75;
public enum bool CLIENTBOUND = true;
public enum bool SERVERBOUND = false;
// flags
public enum ubyte AMBIENT = 1;
public enum ubyte SHOW_PARTICLES = 2;
public enum string[] FIELDS = ["entityId", "effectId", "amplifier", "duration", "flags"];
public uint entityId;
public ubyte effectId;
public ubyte amplifier;
public uint duration;
public ubyte flags;
public pure nothrow @safe @nogc this() {}
public pure nothrow @safe @nogc this(uint entityId, ubyte effectId=ubyte.init, ubyte amplifier=ubyte.init, uint duration=uint.init, ubyte flags=ubyte.init) {
this.entityId = entityId;
this.effectId = effectId;
this.amplifier = amplifier;
this.duration = duration;
this.flags = flags;
}
public pure nothrow @safe ubyte[] encode(bool writeId=true)() {
_buffer.length = 0;
static if(writeId){ writeBytes(varuint.encode(ID)); }
writeBytes(varuint.encode(entityId));
writeBigEndianUbyte(effectId);
writeBigEndianUbyte(amplifier);
writeBytes(varuint.encode(duration));
writeBigEndianUbyte(flags);
return _buffer;
}
public pure nothrow @safe void decode(bool readId=true)() {
static if(readId){ uint _id; _id=varuint.decode(_buffer, &_index); }
entityId=varuint.decode(_buffer, &_index);
effectId=readBigEndianUbyte();
amplifier=readBigEndianUbyte();
duration=varuint.decode(_buffer, &_index);
flags=readBigEndianUbyte();
}
public static pure nothrow @safe EntityEffect fromBuffer(bool readId=true)(ubyte[] buffer) {
EntityEffect ret = new EntityEffect();
ret._buffer = buffer;
ret.decode!readId();
return ret;
}
public override string toString() {
return "EntityEffect(entityId: " ~ std.conv.to!string(this.entityId) ~ ", effectId: " ~ std.conv.to!string(this.effectId) ~ ", amplifier: " ~ std.conv.to!string(this.amplifier) ~ ", duration: " ~ std.conv.to!string(this.duration) ~ ", flags: " ~ std.conv.to!string(this.flags) ~ ")";
}
}
|
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/dinterpret.d, _dinterpret.d)
* Documentation: https://dlang.org/phobos/dmd_dinterpret.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/dinterpret.d
*/
module dmd.dinterpret;
import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string;
import dmd.apply;
import dmd.arraytypes;
import dmd.attrib;
import dmd.builtin;
import dmd.constfold;
import dmd.ctfeexpr;
import dmd.dclass;
import dmd.declaration;
import dmd.dstruct;
import dmd.dsymbol;
import dmd.dsymbolsem;
import dmd.dtemplate;
import dmd.errors;
import dmd.expression;
import dmd.expressionsem;
import dmd.func;
import dmd.globals;
import dmd.id;
import dmd.identifier;
import dmd.init;
import dmd.initsem;
import dmd.mtype;
import dmd.root.rmem;
import dmd.root.array;
import dmd.root.region;
import dmd.root.rootobject;
import dmd.statement;
import dmd.tokens;
import dmd.utf;
import dmd.visitor;
/*************************************
* Entry point for CTFE.
* A compile-time result is required. Give an error if not possible.
*
* `e` must be semantically valid expression. In other words, it should not
* contain any `ErrorExp`s in it. But, CTFE interpretation will cross over
* functions and may invoke a function that contains `ErrorStatement` in its body.
* If that, the "CTFE failed because of previous errors" error is raised.
*/
public Expression ctfeInterpret(Expression e)
{
switch (e.op)
{
case TOK.int64:
case TOK.float64:
case TOK.complex80:
case TOK.null_:
case TOK.void_:
case TOK.string_:
case TOK.this_:
case TOK.super_:
case TOK.type:
case TOK.typeid_:
if (e.type.ty == Terror)
return new ErrorExp();
goto case TOK.error;
case TOK.error:
return e;
default:
break;
}
assert(e.type); // https://issues.dlang.org/show_bug.cgi?id=14642
//assert(e.type.ty != Terror); // FIXME
if (e.type.ty == Terror)
return new ErrorExp();
auto rgnpos = ctfeGlobals.region.savePos();
Expression result = interpret(e, null);
result = copyRegionExp(result);
if (!CTFEExp.isCantExp(result))
result = scrubReturnValue(e.loc, result);
if (CTFEExp.isCantExp(result))
result = new ErrorExp();
ctfeGlobals.region.release(rgnpos);
return result;
}
/* Run CTFE on the expression, but allow the expression to be a TypeExp
* or a tuple containing a TypeExp. (This is required by pragma(msg)).
*/
public Expression ctfeInterpretForPragmaMsg(Expression e)
{
if (e.op == TOK.error || e.op == TOK.type)
return e;
// It's also OK for it to be a function declaration (happens only with
// __traits(getOverloads))
if (auto ve = e.isVarExp())
if (ve.var.isFuncDeclaration())
{
return e;
}
auto tup = e.isTupleExp();
if (!tup)
return e.ctfeInterpret();
// Tuples need to be treated separately, since they are
// allowed to contain a TypeExp in this case.
Expressions* expsx = null;
foreach (i, g; *tup.exps)
{
auto h = ctfeInterpretForPragmaMsg(g);
if (h != g)
{
if (!expsx)
{
expsx = tup.exps.copy();
}
(*expsx)[i] = h;
}
}
if (expsx)
{
auto te = new TupleExp(e.loc, expsx);
expandTuples(te.exps);
te.type = new TypeTuple(te.exps);
return te;
}
return e;
}
public extern (C++) Expression getValue(VarDeclaration vd)
{
return ctfeGlobals.stack.getValue(vd);
}
/*************************************************
* Allocate an Expression in the ctfe region.
* Params:
* T = type of Expression to allocate
* args = arguments to Expression's constructor
* Returns:
* allocated Expression
*/
T ctfeEmplaceExp(T : Expression, Args...)(Args args)
{
if (mem.isGCEnabled)
return new T(args);
auto p = ctfeGlobals.region.malloc(__traits(classInstanceSize, T));
emplaceExp!T(p, args);
return cast(T)p;
}
// CTFE diagnostic information
public extern (C++) void printCtfePerformanceStats()
{
debug (SHOWPERFORMANCE)
{
printf(" ---- CTFE Performance ----\n");
printf("max call depth = %d\tmax stack = %d\n", ctfeGlobals.maxCallDepth, ctfeGlobals.stack.maxStackUsage());
printf("array allocs = %d\tassignments = %d\n\n", ctfeGlobals.numArrayAllocs, ctfeGlobals.numAssignments);
}
}
/**************************
*/
void incArrayAllocs()
{
++ctfeGlobals.numArrayAllocs;
}
/* ================================================ Implementation ======================================= */
private:
/***************
* Collect together globals used by CTFE
*/
struct CtfeGlobals
{
Region region;
CtfeStack stack;
int callDepth = 0; // current number of recursive calls
// When printing a stack trace, suppress this number of calls
int stackTraceCallsToSuppress = 0;
int maxCallDepth = 0; // highest number of recursive calls
int numArrayAllocs = 0; // Number of allocated arrays
int numAssignments = 0; // total number of assignments executed
}
__gshared CtfeGlobals ctfeGlobals;
enum CtfeGoal : int
{
ctfeNeedRvalue, // Must return an Rvalue (== CTFE value)
ctfeNeedLvalue, // Must return an Lvalue (== CTFE reference)
ctfeNeedNothing, // The return value is not required
}
alias ctfeNeedRvalue = CtfeGoal.ctfeNeedRvalue;
alias ctfeNeedLvalue = CtfeGoal.ctfeNeedLvalue;
alias ctfeNeedNothing = CtfeGoal.ctfeNeedNothing;
//debug = LOG;
//debug = LOGASSIGN;
//debug = LOGCOMPILE;
//debug = SHOWPERFORMANCE;
// Maximum allowable recursive function calls in CTFE
enum CTFE_RECURSION_LIMIT = 1000;
/**
The values of all CTFE variables
*/
struct CtfeStack
{
private:
/* The stack. Every declaration we encounter is pushed here,
* together with the VarDeclaration, and the previous
* stack address of that variable, so that we can restore it
* when we leave the stack frame.
* Note that when a function is forward referenced, the interpreter must
* run semantic3, and that may start CTFE again with a NULL istate. Thus
* the stack might not be empty when CTFE begins.
*
* Ctfe Stack addresses are just 0-based integers, but we save
* them as 'void *' because Array can only do pointers.
*/
Expressions values; // values on the stack
VarDeclarations vars; // corresponding variables
Array!(void*) savedId; // id of the previous state of that var
Array!(void*) frames; // all previous frame pointers
Expressions savedThis; // all previous values of localThis
/* Global constants get saved here after evaluation, so we never
* have to redo them. This saves a lot of time and memory.
*/
Expressions globalValues; // values of global constants
size_t framepointer; // current frame pointer
size_t maxStackPointer; // most stack we've ever used
Expression localThis; // value of 'this', or NULL if none
public:
extern (C++) size_t stackPointer()
{
return values.dim;
}
// The current value of 'this', or NULL if none
extern (C++) Expression getThis()
{
return localThis;
}
// Largest number of stack positions we've used
extern (C++) size_t maxStackUsage()
{
return maxStackPointer;
}
// Start a new stack frame, using the provided 'this'.
extern (C++) void startFrame(Expression thisexp)
{
frames.push(cast(void*)cast(size_t)framepointer);
savedThis.push(localThis);
framepointer = stackPointer();
localThis = thisexp;
}
extern (C++) void endFrame()
{
size_t oldframe = cast(size_t)frames[frames.dim - 1];
localThis = savedThis[savedThis.dim - 1];
popAll(framepointer);
framepointer = oldframe;
frames.setDim(frames.dim - 1);
savedThis.setDim(savedThis.dim - 1);
}
extern (C++) bool isInCurrentFrame(VarDeclaration v)
{
if (v.isDataseg() && !v.isCTFE())
return false; // It's a global
return v.ctfeAdrOnStack >= framepointer;
}
extern (C++) Expression getValue(VarDeclaration v)
{
if ((v.isDataseg() || v.storage_class & STC.manifest) && !v.isCTFE())
{
assert(v.ctfeAdrOnStack < globalValues.dim);
return globalValues[v.ctfeAdrOnStack];
}
assert(v.ctfeAdrOnStack < stackPointer());
return values[v.ctfeAdrOnStack];
}
extern (C++) void setValue(VarDeclaration v, Expression e)
{
assert(!v.isDataseg() || v.isCTFE());
assert(v.ctfeAdrOnStack < stackPointer());
values[v.ctfeAdrOnStack] = e;
}
extern (C++) void push(VarDeclaration v)
{
assert(!v.isDataseg() || v.isCTFE());
if (v.ctfeAdrOnStack != VarDeclaration.AdrOnStackNone && v.ctfeAdrOnStack >= framepointer)
{
// Already exists in this frame, reuse it.
values[v.ctfeAdrOnStack] = null;
return;
}
savedId.push(cast(void*)cast(size_t)v.ctfeAdrOnStack);
v.ctfeAdrOnStack = cast(uint)values.dim;
vars.push(v);
values.push(null);
}
extern (C++) void pop(VarDeclaration v)
{
assert(!v.isDataseg() || v.isCTFE());
assert(!(v.storage_class & (STC.ref_ | STC.out_)));
const oldid = v.ctfeAdrOnStack;
v.ctfeAdrOnStack = cast(uint)cast(size_t)savedId[oldid];
if (v.ctfeAdrOnStack == values.dim - 1)
{
values.pop();
vars.pop();
savedId.pop();
}
}
extern (C++) void popAll(size_t stackpointer)
{
if (stackPointer() > maxStackPointer)
maxStackPointer = stackPointer();
assert(values.dim >= stackpointer);
for (size_t i = stackpointer; i < values.dim; ++i)
{
VarDeclaration v = vars[i];
v.ctfeAdrOnStack = cast(uint)cast(size_t)savedId[i];
}
values.setDim(stackpointer);
vars.setDim(stackpointer);
savedId.setDim(stackpointer);
}
extern (C++) void saveGlobalConstant(VarDeclaration v, Expression e)
{
assert(v._init && (v.isConst() || v.isImmutable() || v.storage_class & STC.manifest) && !v.isCTFE());
v.ctfeAdrOnStack = cast(uint)globalValues.dim;
globalValues.push(copyRegionExp(e));
}
}
private struct InterState
{
InterState* caller; // calling function's InterState
FuncDeclaration fd; // function being interpreted
Statement start; // if !=NULL, start execution at this statement
/* target of CTFEExp result; also
* target of labelled CTFEExp or
* CTFEExp. (null if no label).
*/
Statement gotoTarget;
}
/*************************************
* Attempt to interpret a function given the arguments.
* Params:
* pue = storage for result
* fd = function being called
* istate = state for calling function (NULL if none)
* arguments = function arguments
* thisarg = 'this', if a needThis() function, NULL if not.
*
* Returns:
* result expression if successful, TOK.cantExpression if not,
* or CTFEExp if function returned void.
*/
private Expression interpretFunction(UnionExp* pue, FuncDeclaration fd, InterState* istate, Expressions* arguments, Expression thisarg)
{
debug (LOG)
{
printf("\n********\n%s FuncDeclaration::interpret(istate = %p) %s\n", fd.loc.toChars(), istate, fd.toChars());
}
assert(pue);
if (fd.semanticRun == PASS.semantic3)
{
fd.error("circular dependency. Functions cannot be interpreted while being compiled");
return CTFEExp.cantexp;
}
if (!fd.functionSemantic3())
return CTFEExp.cantexp;
if (fd.semanticRun < PASS.semantic3done)
return CTFEExp.cantexp;
Type tb = fd.type.toBasetype();
assert(tb.ty == Tfunction);
TypeFunction tf = cast(TypeFunction)tb;
if (tf.parameterList.varargs != VarArg.none && arguments &&
((fd.parameters && arguments.dim != fd.parameters.dim) || (!fd.parameters && arguments.dim)))
{
fd.error("C-style variadic functions are not yet implemented in CTFE");
return CTFEExp.cantexp;
}
// Nested functions always inherit the 'this' pointer from the parent,
// except for delegates. (Note that the 'this' pointer may be null).
// Func literals report isNested() even if they are in global scope,
// so we need to check that the parent is a function.
if (fd.isNested() && fd.toParentLocal().isFuncDeclaration() && !thisarg && istate)
thisarg = ctfeGlobals.stack.getThis();
if (fd.needThis() && !thisarg)
{
// error, no this. Prevent segfault.
// Here should be unreachable by the strict 'this' check in front-end.
fd.error("need `this` to access member `%s`", fd.toChars());
return CTFEExp.cantexp;
}
// Place to hold all the arguments to the function while
// we are evaluating them.
size_t dim = arguments ? arguments.dim : 0;
assert((fd.parameters ? fd.parameters.dim : 0) == dim);
/* Evaluate all the arguments to the function,
* store the results in eargs[]
*/
Expressions eargs = Expressions(dim);
for (size_t i = 0; i < dim; i++)
{
Expression earg = (*arguments)[i];
Parameter fparam = tf.parameterList[i];
if (fparam.storageClass & (STC.out_ | STC.ref_))
{
if (!istate && (fparam.storageClass & STC.out_))
{
// initializing an out parameter involves writing to it.
earg.error("global `%s` cannot be passed as an `out` parameter at compile time", earg.toChars());
return CTFEExp.cantexp;
}
// Convert all reference arguments into lvalue references
earg = interpretRegion(earg, istate, ctfeNeedLvalue);
if (CTFEExp.isCantExp(earg))
return earg;
}
else if (fparam.storageClass & STC.lazy_)
{
}
else
{
/* Value parameters
*/
Type ta = fparam.type.toBasetype();
if (ta.ty == Tsarray)
if (auto eaddr = earg.isAddrExp())
{
/* Static arrays are passed by a simple pointer.
* Skip past this to get at the actual arg.
*/
earg = eaddr.e1;
}
earg = interpretRegion(earg, istate);
if (CTFEExp.isCantExp(earg))
return earg;
/* Struct literals are passed by value, but we don't need to
* copy them if they are passed as const
*/
if (earg.op == TOK.structLiteral && !(fparam.storageClass & (STC.const_ | STC.immutable_)))
earg = copyLiteral(earg).copy();
}
if (earg.op == TOK.thrownException)
{
if (istate)
return earg;
(cast(ThrownExceptionExp)earg).generateUncaughtError();
return CTFEExp.cantexp;
}
eargs[i] = earg;
}
// Now that we've evaluated all the arguments, we can start the frame
// (this is the moment when the 'call' actually takes place).
InterState istatex;
istatex.caller = istate;
istatex.fd = fd;
if (fd.isThis2)
{
Expression arg0 = thisarg;
if (arg0 && arg0.type.ty == Tstruct)
{
Type t = arg0.type.pointerTo();
arg0 = ctfeEmplaceExp!AddrExp(arg0.loc, arg0);
arg0.type = t;
}
auto elements = new Expressions(2);
(*elements)[0] = arg0;
(*elements)[1] = ctfeGlobals.stack.getThis();
Type t2 = Type.tvoidptr.sarrayOf(2);
const loc = thisarg ? thisarg.loc : fd.loc;
thisarg = ctfeEmplaceExp!ArrayLiteralExp(loc, t2, elements);
thisarg = ctfeEmplaceExp!AddrExp(loc, thisarg);
thisarg.type = t2.pointerTo();
}
ctfeGlobals.stack.startFrame(thisarg);
if (fd.vthis && thisarg)
{
ctfeGlobals.stack.push(fd.vthis);
setValue(fd.vthis, thisarg);
}
for (size_t i = 0; i < dim; i++)
{
Expression earg = eargs[i];
Parameter fparam = tf.parameterList[i];
VarDeclaration v = (*fd.parameters)[i];
debug (LOG)
{
printf("arg[%d] = %s\n", i, earg.toChars());
}
ctfeGlobals.stack.push(v);
if ((fparam.storageClass & (STC.out_ | STC.ref_)) && earg.op == TOK.variable &&
(cast(VarExp)earg).var.toParent2() == fd)
{
VarDeclaration vx = (cast(VarExp)earg).var.isVarDeclaration();
if (!vx)
{
fd.error("cannot interpret `%s` as a `ref` parameter", earg.toChars());
return CTFEExp.cantexp;
}
/* vx is a variable that is declared in fd.
* It means that fd is recursively called. e.g.
*
* void fd(int n, ref int v = dummy) {
* int vx;
* if (n == 1) fd(2, vx);
* }
* fd(1);
*
* The old value of vx on the stack in fd(1)
* should be saved at the start of fd(2, vx) call.
*/
const oldadr = vx.ctfeAdrOnStack;
ctfeGlobals.stack.push(vx);
assert(!hasValue(vx)); // vx is made uninitialized
// https://issues.dlang.org/show_bug.cgi?id=14299
// v.ctfeAdrOnStack should be saved already
// in the stack before the overwrite.
v.ctfeAdrOnStack = oldadr;
assert(hasValue(v)); // ref parameter v should refer existing value.
}
else
{
// Value parameters and non-trivial references
setValueWithoutChecking(v, earg);
}
debug (LOG)
{
printf("interpreted arg[%d] = %s\n", i, earg.toChars());
showCtfeExpr(earg);
}
debug (LOGASSIGN)
{
printf("interpreted arg[%d] = %s\n", i, earg.toChars());
showCtfeExpr(earg);
}
}
if (fd.vresult)
ctfeGlobals.stack.push(fd.vresult);
// Enter the function
++ctfeGlobals.callDepth;
if (ctfeGlobals.callDepth > ctfeGlobals.maxCallDepth)
ctfeGlobals.maxCallDepth = ctfeGlobals.callDepth;
Expression e = null;
while (1)
{
if (ctfeGlobals.callDepth > CTFE_RECURSION_LIMIT)
{
// This is a compiler error. It must not be suppressed.
global.gag = 0;
fd.error("CTFE recursion limit exceeded");
e = CTFEExp.cantexp;
break;
}
e = interpret(pue, fd.fbody, &istatex);
if (CTFEExp.isCantExp(e))
{
debug (LOG)
{
printf("function body failed to interpret\n");
}
}
if (istatex.start)
{
fd.error("CTFE internal error: failed to resume at statement `%s`", istatex.start.toChars());
return CTFEExp.cantexp;
}
/* This is how we deal with a recursive statement AST
* that has arbitrary goto statements in it.
* Bubble up a 'result' which is the target of the goto
* statement, then go recursively down the AST looking
* for that statement, then execute starting there.
*/
if (CTFEExp.isGotoExp(e))
{
istatex.start = istatex.gotoTarget; // set starting statement
istatex.gotoTarget = null;
}
else
{
assert(!e || (e.op != TOK.continue_ && e.op != TOK.break_));
break;
}
}
// If fell off the end of a void function, return void
if (!e && tf.next.ty == Tvoid)
e = CTFEExp.voidexp;
if (tf.isref && e.op == TOK.variable && (cast(VarExp)e).var == fd.vthis)
e = thisarg;
if (tf.isref && fd.isThis2 && e.op == TOK.index)
{
auto ie = cast(IndexExp)e;
auto pe = ie.e1.isPtrExp();
auto ve = !pe ? null : pe.e1.isVarExp();
if (ve && ve.var == fd.vthis)
{
auto ne = ie.e2.isIntegerExp();
assert(ne);
assert(thisarg.op == TOK.address);
e = (cast(AddrExp)thisarg).e1;
e = (*(cast(ArrayLiteralExp)e).elements)[cast(size_t)ne.getInteger()];
if (e.op == TOK.address)
{
e = (cast(AddrExp)e).e1;
}
}
}
assert(e !is null);
// Leave the function
--ctfeGlobals.callDepth;
ctfeGlobals.stack.endFrame();
// If it generated an uncaught exception, report error.
if (!istate && e.op == TOK.thrownException)
{
if (e == pue.exp())
e = pue.copy();
(cast(ThrownExceptionExp)e).generateUncaughtError();
e = CTFEExp.cantexp;
}
return e;
}
private extern (C++) final class Interpreter : Visitor
{
alias visit = Visitor.visit;
public:
InterState* istate;
CtfeGoal goal;
Expression result;
UnionExp* pue; // storage for `result`
extern (D) this(UnionExp* pue, InterState* istate, CtfeGoal goal)
{
this.pue = pue;
this.istate = istate;
this.goal = goal;
}
// If e is TOK.throw_exception or TOK.cantExpression,
// set it to 'result' and returns true.
bool exceptionOrCant(Expression e)
{
if (exceptionOrCantInterpret(e))
{
// Make sure e is not pointing to a stack temporary
result = (e.op == TOK.cantExpression) ? CTFEExp.cantexp : e;
return true;
}
return false;
}
static Expressions* copyArrayOnWrite(Expressions* exps, Expressions* original)
{
if (exps is original)
{
if (!original)
exps = new Expressions();
else
exps = original.copy();
++ctfeGlobals.numArrayAllocs;
}
return exps;
}
/******************************** Statement ***************************/
override void visit(Statement s)
{
debug (LOG)
{
printf("%s Statement::interpret()\n", s.loc.toChars());
}
if (istate.start)
{
if (istate.start != s)
return;
istate.start = null;
}
s.error("statement `%s` cannot be interpreted at compile time", s.toChars());
result = CTFEExp.cantexp;
}
override void visit(ExpStatement s)
{
debug (LOG)
{
printf("%s ExpStatement::interpret(%s)\n", s.loc.toChars(), s.exp ? s.exp.toChars() : "");
}
if (istate.start)
{
if (istate.start != s)
return;
istate.start = null;
}
Expression e = interpret(pue, s.exp, istate, ctfeNeedNothing);
if (exceptionOrCant(e))
return;
}
override void visit(CompoundStatement s)
{
debug (LOG)
{
printf("%s CompoundStatement::interpret()\n", s.loc.toChars());
}
if (istate.start == s)
istate.start = null;
const dim = s.statements ? s.statements.dim : 0;
foreach (i; 0 .. dim)
{
Statement sx = (*s.statements)[i];
result = interpret(pue, sx, istate);
if (result)
break;
}
debug (LOG)
{
printf("%s -CompoundStatement::interpret() %p\n", s.loc.toChars(), result);
}
}
override void visit(UnrolledLoopStatement s)
{
debug (LOG)
{
printf("%s UnrolledLoopStatement::interpret()\n", s.loc.toChars());
}
if (istate.start == s)
istate.start = null;
const dim = s.statements ? s.statements.dim : 0;
foreach (i; 0 .. dim)
{
Statement sx = (*s.statements)[i];
Expression e = interpret(pue, sx, istate);
if (!e) // succeeds to interpret, or goto target was not found
continue;
if (exceptionOrCant(e))
return;
if (e.op == TOK.break_)
{
if (istate.gotoTarget && istate.gotoTarget != s)
{
result = e; // break at a higher level
return;
}
istate.gotoTarget = null;
result = null;
return;
}
if (e.op == TOK.continue_)
{
if (istate.gotoTarget && istate.gotoTarget != s)
{
result = e; // continue at a higher level
return;
}
istate.gotoTarget = null;
continue;
}
// expression from return statement, or thrown exception
result = e;
break;
}
}
override void visit(IfStatement s)
{
debug (LOG)
{
printf("%s IfStatement::interpret(%s)\n", s.loc.toChars(), s.condition.toChars());
}
if (istate.start == s)
istate.start = null;
if (istate.start)
{
Expression e = null;
e = interpret(s.ifbody, istate);
if (!e && istate.start)
e = interpret(s.elsebody, istate);
result = e;
return;
}
UnionExp ue = void;
Expression e = interpret(&ue, s.condition, istate);
assert(e);
if (exceptionOrCant(e))
return;
if (isTrueBool(e))
result = interpret(pue, s.ifbody, istate);
else if (e.isBool(false))
result = interpret(pue, s.elsebody, istate);
else
{
// no error, or assert(0)?
result = CTFEExp.cantexp;
}
}
override void visit(ScopeStatement s)
{
debug (LOG)
{
printf("%s ScopeStatement::interpret()\n", s.loc.toChars());
}
if (istate.start == s)
istate.start = null;
result = interpret(pue, s.statement, istate);
}
/**
Given an expression e which is about to be returned from the current
function, generate an error if it contains pointers to local variables.
Only checks expressions passed by value (pointers to local variables
may already be stored in members of classes, arrays, or AAs which
were passed as mutable function parameters).
Returns:
true if it is safe to return, false if an error was generated.
*/
static bool stopPointersEscaping(const ref Loc loc, Expression e)
{
if (!e.type.hasPointers())
return true;
if (isPointer(e.type))
{
Expression x = e;
if (auto eaddr = e.isAddrExp())
x = eaddr.e1;
VarDeclaration v;
while (x.op == TOK.variable && (v = (cast(VarExp)x).var.isVarDeclaration()) !is null)
{
if (v.storage_class & STC.ref_)
{
x = getValue(v);
if (auto eaddr = e.isAddrExp())
eaddr.e1 = x;
continue;
}
if (ctfeGlobals.stack.isInCurrentFrame(v))
{
error(loc, "returning a pointer to a local stack variable");
return false;
}
else
break;
}
// TODO: If it is a TOK.dotVariable or TOK.index, we should check that it is not
// pointing to a local struct or static array.
}
if (auto se = e.isStructLiteralExp())
{
return stopPointersEscapingFromArray(loc, se.elements);
}
if (auto ale = e.isArrayLiteralExp())
{
return stopPointersEscapingFromArray(loc, ale.elements);
}
if (auto aae = e.isAssocArrayLiteralExp())
{
if (!stopPointersEscapingFromArray(loc, aae.keys))
return false;
return stopPointersEscapingFromArray(loc, aae.values);
}
return true;
}
// Check all elements of an array for escaping local variables. Return false if error
static bool stopPointersEscapingFromArray(const ref Loc loc, Expressions* elems)
{
foreach (e; *elems)
{
if (e && !stopPointersEscaping(loc, e))
return false;
}
return true;
}
override void visit(ReturnStatement s)
{
debug (LOG)
{
printf("%s ReturnStatement::interpret(%s)\n", s.loc.toChars(), s.exp ? s.exp.toChars() : "");
}
if (istate.start)
{
if (istate.start != s)
return;
istate.start = null;
}
if (!s.exp)
{
result = CTFEExp.voidexp;
return;
}
assert(istate && istate.fd && istate.fd.type && istate.fd.type.ty == Tfunction);
TypeFunction tf = cast(TypeFunction)istate.fd.type;
/* If the function returns a ref AND it's been called from an assignment,
* we need to return an lvalue. Otherwise, just do an (rvalue) interpret.
*/
if (tf.isref)
{
result = interpret(pue, s.exp, istate, ctfeNeedLvalue);
return;
}
if (tf.next && tf.next.ty == Tdelegate && istate.fd.closureVars.dim > 0)
{
// To support this, we need to copy all the closure vars
// into the delegate literal.
s.error("closures are not yet supported in CTFE");
result = CTFEExp.cantexp;
return;
}
// We need to treat pointers specially, because TOK.symbolOffset can be used to
// return a value OR a pointer
Expression e = interpret(pue, s.exp, istate);
if (exceptionOrCant(e))
return;
// Disallow returning pointers to stack-allocated variables (bug 7876)
if (!stopPointersEscaping(s.loc, e))
{
result = CTFEExp.cantexp;
return;
}
if (needToCopyLiteral(e))
e = copyLiteral(e).copy();
debug (LOGASSIGN)
{
printf("RETURN %s\n", s.loc.toChars());
showCtfeExpr(e);
}
result = e;
}
static Statement findGotoTarget(InterState* istate, Identifier ident)
{
Statement target = null;
if (ident)
{
LabelDsymbol label = istate.fd.searchLabel(ident);
assert(label && label.statement);
LabelStatement ls = label.statement;
target = ls.gotoTarget ? ls.gotoTarget : ls.statement;
}
return target;
}
override void visit(BreakStatement s)
{
debug (LOG)
{
printf("%s BreakStatement::interpret()\n", s.loc.toChars());
}
if (istate.start)
{
if (istate.start != s)
return;
istate.start = null;
}
istate.gotoTarget = findGotoTarget(istate, s.ident);
result = CTFEExp.breakexp;
}
override void visit(ContinueStatement s)
{
debug (LOG)
{
printf("%s ContinueStatement::interpret()\n", s.loc.toChars());
}
if (istate.start)
{
if (istate.start != s)
return;
istate.start = null;
}
istate.gotoTarget = findGotoTarget(istate, s.ident);
result = CTFEExp.continueexp;
}
override void visit(WhileStatement s)
{
debug (LOG)
{
printf("WhileStatement::interpret()\n");
}
assert(0); // rewritten to ForStatement
}
override void visit(DoStatement s)
{
debug (LOG)
{
printf("%s DoStatement::interpret()\n", s.loc.toChars());
}
if (istate.start == s)
istate.start = null;
while (1)
{
Expression e = interpret(s._body, istate);
if (!e && istate.start) // goto target was not found
return;
assert(!istate.start);
if (exceptionOrCant(e))
return;
if (e && e.op == TOK.break_)
{
if (istate.gotoTarget && istate.gotoTarget != s)
{
result = e; // break at a higher level
return;
}
istate.gotoTarget = null;
break;
}
if (e && e.op == TOK.continue_)
{
if (istate.gotoTarget && istate.gotoTarget != s)
{
result = e; // continue at a higher level
return;
}
istate.gotoTarget = null;
e = null;
}
if (e)
{
result = e; // bubbled up from ReturnStatement
return;
}
UnionExp ue = void;
e = interpret(&ue, s.condition, istate);
if (exceptionOrCant(e))
return;
if (!e.isConst())
{
result = CTFEExp.cantexp;
return;
}
if (e.isBool(false))
break;
assert(isTrueBool(e));
}
assert(result is null);
}
override void visit(ForStatement s)
{
debug (LOG)
{
printf("%s ForStatement::interpret()\n", s.loc.toChars());
}
if (istate.start == s)
istate.start = null;
UnionExp ueinit = void;
Expression ei = interpret(&ueinit, s._init, istate);
if (exceptionOrCant(ei))
return;
assert(!ei); // s.init never returns from function, or jumps out from it
while (1)
{
if (s.condition && !istate.start)
{
UnionExp ue = void;
Expression e = interpret(&ue, s.condition, istate);
if (exceptionOrCant(e))
return;
if (e.isBool(false))
break;
assert(isTrueBool(e));
}
Expression e = interpret(pue, s._body, istate);
if (!e && istate.start) // goto target was not found
return;
assert(!istate.start);
if (exceptionOrCant(e))
return;
if (e && e.op == TOK.break_)
{
if (istate.gotoTarget && istate.gotoTarget != s)
{
result = e; // break at a higher level
return;
}
istate.gotoTarget = null;
break;
}
if (e && e.op == TOK.continue_)
{
if (istate.gotoTarget && istate.gotoTarget != s)
{
result = e; // continue at a higher level
return;
}
istate.gotoTarget = null;
e = null;
}
if (e)
{
result = e; // bubbled up from ReturnStatement
return;
}
UnionExp uei = void;
e = interpret(&uei, s.increment, istate, ctfeNeedNothing);
if (exceptionOrCant(e))
return;
}
assert(result is null);
}
override void visit(ForeachStatement s)
{
assert(0); // rewritten to ForStatement
}
override void visit(ForeachRangeStatement s)
{
assert(0); // rewritten to ForStatement
}
override void visit(SwitchStatement s)
{
debug (LOG)
{
printf("%s SwitchStatement::interpret()\n", s.loc.toChars());
}
if (istate.start == s)
istate.start = null;
if (istate.start)
{
Expression e = interpret(s._body, istate);
if (istate.start) // goto target was not found
return;
if (exceptionOrCant(e))
return;
if (e && e.op == TOK.break_)
{
if (istate.gotoTarget && istate.gotoTarget != s)
{
result = e; // break at a higher level
return;
}
istate.gotoTarget = null;
e = null;
}
result = e;
return;
}
UnionExp uecond = void;
Expression econdition = interpret(&uecond, s.condition, istate);
if (exceptionOrCant(econdition))
return;
Statement scase = null;
if (s.cases)
foreach (cs; *s.cases)
{
UnionExp uecase = void;
Expression ecase = interpret(&uecase, cs.exp, istate);
if (exceptionOrCant(ecase))
return;
if (ctfeEqual(cs.exp.loc, TOK.equal, econdition, ecase))
{
scase = cs;
break;
}
}
if (!scase)
{
if (s.hasNoDefault)
s.error("no `default` or `case` for `%s` in `switch` statement", econdition.toChars());
scase = s.sdefault;
}
assert(scase);
/* Jump to scase
*/
istate.start = scase;
Expression e = interpret(pue, s._body, istate);
assert(!istate.start); // jump must not fail
if (e && e.op == TOK.break_)
{
if (istate.gotoTarget && istate.gotoTarget != s)
{
result = e; // break at a higher level
return;
}
istate.gotoTarget = null;
e = null;
}
result = e;
}
override void visit(CaseStatement s)
{
debug (LOG)
{
printf("%s CaseStatement::interpret(%s) this = %p\n", s.loc.toChars(), s.exp.toChars(), s);
}
if (istate.start == s)
istate.start = null;
result = interpret(pue, s.statement, istate);
}
override void visit(DefaultStatement s)
{
debug (LOG)
{
printf("%s DefaultStatement::interpret()\n", s.loc.toChars());
}
if (istate.start == s)
istate.start = null;
result = interpret(pue, s.statement, istate);
}
override void visit(GotoStatement s)
{
debug (LOG)
{
printf("%s GotoStatement::interpret()\n", s.loc.toChars());
}
if (istate.start)
{
if (istate.start != s)
return;
istate.start = null;
}
assert(s.label && s.label.statement);
istate.gotoTarget = s.label.statement;
result = CTFEExp.gotoexp;
}
override void visit(GotoCaseStatement s)
{
debug (LOG)
{
printf("%s GotoCaseStatement::interpret()\n", s.loc.toChars());
}
if (istate.start)
{
if (istate.start != s)
return;
istate.start = null;
}
assert(s.cs);
istate.gotoTarget = s.cs;
result = CTFEExp.gotoexp;
}
override void visit(GotoDefaultStatement s)
{
debug (LOG)
{
printf("%s GotoDefaultStatement::interpret()\n", s.loc.toChars());
}
if (istate.start)
{
if (istate.start != s)
return;
istate.start = null;
}
assert(s.sw && s.sw.sdefault);
istate.gotoTarget = s.sw.sdefault;
result = CTFEExp.gotoexp;
}
override void visit(LabelStatement s)
{
debug (LOG)
{
printf("%s LabelStatement::interpret()\n", s.loc.toChars());
}
if (istate.start == s)
istate.start = null;
result = interpret(pue, s.statement, istate);
}
override void visit(TryCatchStatement s)
{
debug (LOG)
{
printf("%s TryCatchStatement::interpret()\n", s.loc.toChars());
}
if (istate.start == s)
istate.start = null;
if (istate.start)
{
Expression e = null;
e = interpret(pue, s._body, istate);
foreach (ca; *s.catches)
{
if (e || !istate.start) // goto target was found
break;
e = interpret(pue, ca.handler, istate);
}
result = e;
return;
}
Expression e = interpret(s._body, istate);
// An exception was thrown
if (e && e.op == TOK.thrownException)
{
ThrownExceptionExp ex = cast(ThrownExceptionExp)e;
Type extype = ex.thrown.originalClass().type;
// Search for an appropriate catch clause.
foreach (ca; *s.catches)
{
Type catype = ca.type;
if (!catype.equals(extype) && !catype.isBaseOf(extype, null))
continue;
// Execute the handler
if (ca.var)
{
ctfeGlobals.stack.push(ca.var);
setValue(ca.var, ex.thrown);
}
e = interpret(ca.handler, istate);
if (CTFEExp.isGotoExp(e))
{
/* This is an optimization that relies on the locality of the jump target.
* If the label is in the same catch handler, the following scan
* would find it quickly and can reduce jump cost.
* Otherwise, the catch block may be unnnecessary scanned again
* so it would make CTFE speed slower.
*/
InterState istatex = *istate;
istatex.start = istate.gotoTarget; // set starting statement
istatex.gotoTarget = null;
Expression eh = interpret(ca.handler, &istatex);
if (!istatex.start)
{
istate.gotoTarget = null;
e = eh;
}
}
break;
}
}
result = e;
}
static bool isAnErrorException(ClassDeclaration cd)
{
return cd == ClassDeclaration.errorException || ClassDeclaration.errorException.isBaseOf(cd, null);
}
static ThrownExceptionExp chainExceptions(ThrownExceptionExp oldest, ThrownExceptionExp newest)
{
debug (LOG)
{
printf("Collided exceptions %s %s\n", oldest.thrown.toChars(), newest.thrown.toChars());
}
// Little sanity check to make sure it's really a Throwable
ClassReferenceExp boss = oldest.thrown;
const next = 4; // index of Throwable.next
assert((*boss.value.elements)[next].type.ty == Tclass); // Throwable.next
ClassReferenceExp collateral = newest.thrown;
if (isAnErrorException(collateral.originalClass()) && !isAnErrorException(boss.originalClass()))
{
/* Find the index of the Error.bypassException field
*/
auto bypass = next + 1;
if ((*collateral.value.elements)[bypass].type.ty == Tuns32)
bypass += 1; // skip over _refcount field
assert((*collateral.value.elements)[bypass].type.ty == Tclass);
// The new exception bypass the existing chain
(*collateral.value.elements)[bypass] = boss;
return newest;
}
while ((*boss.value.elements)[next].op == TOK.classReference)
{
boss = cast(ClassReferenceExp)(*boss.value.elements)[next];
}
(*boss.value.elements)[next] = collateral;
return oldest;
}
override void visit(TryFinallyStatement s)
{
debug (LOG)
{
printf("%s TryFinallyStatement::interpret()\n", s.loc.toChars());
}
if (istate.start == s)
istate.start = null;
if (istate.start)
{
Expression e = null;
e = interpret(pue, s._body, istate);
// Jump into/out from finalbody is disabled in semantic analysis.
// and jump inside will be handled by the ScopeStatement == finalbody.
result = e;
return;
}
Expression ex = interpret(s._body, istate);
if (CTFEExp.isCantExp(ex))
{
result = ex;
return;
}
while (CTFEExp.isGotoExp(ex))
{
// If the goto target is within the body, we must not interpret the finally statement,
// because that will call destructors for objects within the scope, which we should not do.
InterState istatex = *istate;
istatex.start = istate.gotoTarget; // set starting statement
istatex.gotoTarget = null;
Expression bex = interpret(s._body, &istatex);
if (istatex.start)
{
// The goto target is outside the current scope.
break;
}
// The goto target was within the body.
if (CTFEExp.isCantExp(bex))
{
result = bex;
return;
}
*istate = istatex;
ex = bex;
}
Expression ey = interpret(s.finalbody, istate);
if (CTFEExp.isCantExp(ey))
{
result = ey;
return;
}
if (ey && ey.op == TOK.thrownException)
{
// Check for collided exceptions
if (ex && ex.op == TOK.thrownException)
ex = chainExceptions(cast(ThrownExceptionExp)ex, cast(ThrownExceptionExp)ey);
else
ex = ey;
}
result = ex;
}
override void visit(ThrowStatement s)
{
debug (LOG)
{
printf("%s ThrowStatement::interpret()\n", s.loc.toChars());
}
if (istate.start)
{
if (istate.start != s)
return;
istate.start = null;
}
Expression e = interpretRegion(s.exp, istate);
if (exceptionOrCant(e))
return;
assert(e.op == TOK.classReference);
result = ctfeEmplaceExp!ThrownExceptionExp(s.loc, e.isClassReferenceExp());
}
override void visit(ScopeGuardStatement s)
{
assert(0);
}
override void visit(WithStatement s)
{
debug (LOG)
{
printf("%s WithStatement::interpret()\n", s.loc.toChars());
}
if (istate.start == s)
istate.start = null;
if (istate.start)
{
result = s._body ? interpret(s._body, istate) : null;
return;
}
// If it is with(Enum) {...}, just execute the body.
if (s.exp.op == TOK.scope_ || s.exp.op == TOK.type)
{
result = interpret(pue, s._body, istate);
return;
}
Expression e = interpret(s.exp, istate);
if (exceptionOrCant(e))
return;
if (s.wthis.type.ty == Tpointer && s.exp.type.ty != Tpointer)
{
e = ctfeEmplaceExp!AddrExp(s.loc, e, s.wthis.type);
}
ctfeGlobals.stack.push(s.wthis);
setValue(s.wthis, e);
e = interpret(s._body, istate);
if (CTFEExp.isGotoExp(e))
{
/* This is an optimization that relies on the locality of the jump target.
* If the label is in the same WithStatement, the following scan
* would find it quickly and can reduce jump cost.
* Otherwise, the statement body may be unnnecessary scanned again
* so it would make CTFE speed slower.
*/
InterState istatex = *istate;
istatex.start = istate.gotoTarget; // set starting statement
istatex.gotoTarget = null;
Expression ex = interpret(s._body, &istatex);
if (!istatex.start)
{
istate.gotoTarget = null;
e = ex;
}
}
ctfeGlobals.stack.pop(s.wthis);
result = e;
}
override void visit(AsmStatement s)
{
debug (LOG)
{
printf("%s AsmStatement::interpret()\n", s.loc.toChars());
}
if (istate.start)
{
if (istate.start != s)
return;
istate.start = null;
}
s.error("`asm` statements cannot be interpreted at compile time");
result = CTFEExp.cantexp;
}
override void visit(ImportStatement s)
{
debug (LOG)
{
printf("ImportStatement::interpret()\n");
}
if (istate.start)
{
if (istate.start != s)
return;
istate.start = null;
}
}
/******************************** Expression ***************************/
override void visit(Expression e)
{
debug (LOG)
{
printf("%s Expression::interpret() '%s' %s\n", e.loc.toChars(), Token.toChars(e.op), e.toChars());
printf("type = %s\n", e.type.toChars());
showCtfeExpr(e);
}
e.error("cannot interpret `%s` at compile time", e.toChars());
result = CTFEExp.cantexp;
}
override void visit(TypeExp e)
{
debug (LOG)
{
printf("%s TypeExp.interpret() %s\n", e.loc.toChars(), e.toChars());
}
result = e;
}
override void visit(ThisExp e)
{
debug (LOG)
{
printf("%s ThisExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
if (goal == ctfeNeedLvalue)
{
// We might end up here with istate being zero
// https://issues.dlang.org/show_bug.cgi?id=16382
if (istate && istate.fd.vthis)
{
result = ctfeEmplaceExp!VarExp(e.loc, istate.fd.vthis);
if (istate.fd.isThis2)
{
result = ctfeEmplaceExp!PtrExp(e.loc, result);
result.type = Type.tvoidptr.sarrayOf(2);
result = ctfeEmplaceExp!IndexExp(e.loc, result, IntegerExp.literal!0);
}
result.type = e.type;
}
else
result = e;
return;
}
result = ctfeGlobals.stack.getThis();
if (result)
{
if (istate && istate.fd.isThis2)
{
assert(result.op == TOK.address);
result = (cast(AddrExp)result).e1;
assert(result.op == TOK.arrayLiteral);
result = (*(cast(ArrayLiteralExp)result).elements)[0];
if (e.type.ty == Tstruct)
{
result = (cast(AddrExp)result).e1;
}
return;
}
assert(result.op == TOK.structLiteral || result.op == TOK.classReference || result.op == TOK.type);
return;
}
e.error("value of `this` is not known at compile time");
result = CTFEExp.cantexp;
}
override void visit(NullExp e)
{
result = e;
}
override void visit(IntegerExp e)
{
debug (LOG)
{
printf("%s IntegerExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
result = e;
}
override void visit(RealExp e)
{
debug (LOG)
{
printf("%s RealExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
result = e;
}
override void visit(ComplexExp e)
{
result = e;
}
override void visit(StringExp e)
{
debug (LOG)
{
printf("%s StringExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
/* Attempts to modify string literals are prevented
* in BinExp::interpretAssignCommon.
*/
result = e;
}
override void visit(FuncExp e)
{
debug (LOG)
{
printf("%s FuncExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
result = e;
}
override void visit(SymOffExp e)
{
debug (LOG)
{
printf("%s SymOffExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
if (e.var.isFuncDeclaration() && e.offset == 0)
{
result = e;
return;
}
if (isTypeInfo_Class(e.type) && e.offset == 0)
{
result = e;
return;
}
if (e.type.ty != Tpointer)
{
// Probably impossible
e.error("cannot interpret `%s` at compile time", e.toChars());
result = CTFEExp.cantexp;
return;
}
Type pointee = (cast(TypePointer)e.type).next;
if (e.var.isThreadlocal())
{
e.error("cannot take address of thread-local variable %s at compile time", e.var.toChars());
result = CTFEExp.cantexp;
return;
}
// Check for taking an address of a shared variable.
// If the shared variable is an array, the offset might not be zero.
Type fromType = null;
if (e.var.type.ty == Tarray || e.var.type.ty == Tsarray)
{
fromType = (cast(TypeArray)e.var.type).next;
}
if (e.var.isDataseg() && ((e.offset == 0 && isSafePointerCast(e.var.type, pointee)) || (fromType && isSafePointerCast(fromType, pointee))))
{
result = e;
return;
}
Expression val = getVarExp(e.loc, istate, e.var, goal);
if (exceptionOrCant(val))
return;
if (val.type.ty == Tarray || val.type.ty == Tsarray)
{
// Check for unsupported type painting operations
Type elemtype = (cast(TypeArray)val.type).next;
d_uns64 elemsize = elemtype.size();
// It's OK to cast from fixed length to dynamic array, eg &int[3] to int[]*
if (val.type.ty == Tsarray && pointee.ty == Tarray && elemsize == pointee.nextOf().size())
{
emplaceExp!(AddrExp)(pue, e.loc, val, e.type);
result = pue.exp();
return;
}
// It's OK to cast from fixed length to fixed length array, eg &int[n] to int[d]*.
if (val.type.ty == Tsarray && pointee.ty == Tsarray && elemsize == pointee.nextOf().size())
{
size_t d = cast(size_t)(cast(TypeSArray)pointee).dim.toInteger();
Expression elwr = ctfeEmplaceExp!IntegerExp(e.loc, e.offset / elemsize, Type.tsize_t);
Expression eupr = ctfeEmplaceExp!IntegerExp(e.loc, e.offset / elemsize + d, Type.tsize_t);
// Create a CTFE pointer &val[ofs..ofs+d]
auto se = ctfeEmplaceExp!SliceExp(e.loc, val, elwr, eupr);
se.type = pointee;
emplaceExp!(AddrExp)(pue, e.loc, se, e.type);
result = pue.exp();
return;
}
if (!isSafePointerCast(elemtype, pointee))
{
// It's also OK to cast from &string to string*.
if (e.offset == 0 && isSafePointerCast(e.var.type, pointee))
{
// Create a CTFE pointer &var
auto ve = ctfeEmplaceExp!VarExp(e.loc, e.var);
ve.type = elemtype;
emplaceExp!(AddrExp)(pue, e.loc, ve, e.type);
result = pue.exp();
return;
}
e.error("reinterpreting cast from `%s` to `%s` is not supported in CTFE", val.type.toChars(), e.type.toChars());
result = CTFEExp.cantexp;
return;
}
const dinteger_t sz = pointee.size();
dinteger_t indx = e.offset / sz;
assert(sz * indx == e.offset);
Expression aggregate = null;
if (val.op == TOK.arrayLiteral || val.op == TOK.string_)
{
aggregate = val;
}
else if (auto se = val.isSliceExp())
{
aggregate = se.e1;
UnionExp uelwr = void;
Expression lwr = interpret(&uelwr, se.lwr, istate);
indx += lwr.toInteger();
}
if (aggregate)
{
// Create a CTFE pointer &aggregate[ofs]
auto ofs = ctfeEmplaceExp!IntegerExp(e.loc, indx, Type.tsize_t);
auto ei = ctfeEmplaceExp!IndexExp(e.loc, aggregate, ofs);
ei.type = elemtype;
emplaceExp!(AddrExp)(pue, e.loc, ei, e.type);
result = pue.exp();
return;
}
}
else if (e.offset == 0 && isSafePointerCast(e.var.type, pointee))
{
// Create a CTFE pointer &var
auto ve = ctfeEmplaceExp!VarExp(e.loc, e.var);
ve.type = e.var.type;
emplaceExp!(AddrExp)(pue, e.loc, ve, e.type);
result = pue.exp();
return;
}
e.error("cannot convert `&%s` to `%s` at compile time", e.var.type.toChars(), e.type.toChars());
result = CTFEExp.cantexp;
}
override void visit(AddrExp e)
{
debug (LOG)
{
printf("%s AddrExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
if (auto ve = e.e1.isVarExp())
{
Declaration decl = ve.var;
// We cannot take the address of an imported symbol at compile time
if (decl.isImportedSymbol()) {
e.error("cannot take address of imported symbol `%s` at compile time", decl.toChars());
result = CTFEExp.cantexp;
return;
}
if (decl.isDataseg()) {
// Normally this is already done by optimize()
// Do it here in case optimize(WANTvalue) wasn't run before CTFE
emplaceExp!(SymOffExp)(pue, e.loc, (cast(VarExp)e.e1).var, 0);
result = pue.exp();
result.type = e.type;
return;
}
}
auto er = interpret(e.e1, istate, ctfeNeedLvalue);
if (auto ve = er.isVarExp())
if (ve.var == istate.fd.vthis)
er = interpret(er, istate);
if (exceptionOrCant(er))
return;
// Return a simplified address expression
emplaceExp!(AddrExp)(pue, e.loc, er, e.type);
result = pue.exp();
}
override void visit(DelegateExp e)
{
debug (LOG)
{
printf("%s DelegateExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
// TODO: Really we should create a CTFE-only delegate expression
// of a pointer and a funcptr.
// If it is &nestedfunc, just return it
// TODO: We should save the context pointer
if (auto ve1 = e.e1.isVarExp())
if (ve1.var == e.func)
{
result = e;
return;
}
auto er = interpret(pue, e.e1, istate);
if (exceptionOrCant(er))
return;
if (er == e.e1)
{
// If it has already been CTFE'd, just return it
result = e;
}
else
{
er = (er == pue.exp()) ? pue.copy() : er;
emplaceExp!(DelegateExp)(pue, e.loc, er, e.func, false);
result = pue.exp();
result.type = e.type;
}
}
static Expression getVarExp(const ref Loc loc, InterState* istate, Declaration d, CtfeGoal goal)
{
Expression e = CTFEExp.cantexp;
if (VarDeclaration v = d.isVarDeclaration())
{
/* Magic variable __ctfe always returns true when interpreting
*/
if (v.ident == Id.ctfe)
return IntegerExp.createBool(true);
if (!v.originalType && v.semanticRun < PASS.semanticdone) // semantic() not yet run
{
v.dsymbolSemantic(null);
if (v.type.ty == Terror)
return CTFEExp.cantexp;
}
if ((v.isConst() || v.isImmutable() || v.storage_class & STC.manifest) && !hasValue(v) && v._init && !v.isCTFE())
{
if (v.inuse)
{
error(loc, "circular initialization of %s `%s`", v.kind(), v.toPrettyChars());
return CTFEExp.cantexp;
}
if (v._scope)
{
v.inuse++;
v._init = v._init.initializerSemantic(v._scope, v.type, INITinterpret); // might not be run on aggregate members
v.inuse--;
}
e = v._init.initializerToExpression(v.type);
if (!e)
return CTFEExp.cantexp;
assert(e.type);
if (e.op == TOK.construct || e.op == TOK.blit)
{
AssignExp ae = cast(AssignExp)e;
e = ae.e2;
}
if (e.op == TOK.error)
{
// FIXME: Ultimately all errors should be detected in prior semantic analysis stage.
}
else if (v.isDataseg() || (v.storage_class & STC.manifest))
{
/* https://issues.dlang.org/show_bug.cgi?id=14304
* e is a value that is not yet owned by CTFE.
* Mark as "cached", and use it directly during interpretation.
*/
e = scrubCacheValue(e);
ctfeGlobals.stack.saveGlobalConstant(v, e);
}
else
{
v.inuse++;
e = interpret(e, istate);
v.inuse--;
if (CTFEExp.isCantExp(e) && !global.gag && !ctfeGlobals.stackTraceCallsToSuppress)
errorSupplemental(loc, "while evaluating %s.init", v.toChars());
if (exceptionOrCantInterpret(e))
return e;
}
}
else if (v.isCTFE() && !hasValue(v))
{
if (v._init && v.type.size() != 0)
{
if (v._init.isVoidInitializer())
{
// var should have been initialized when it was created
error(loc, "CTFE internal error: trying to access uninitialized var");
assert(0);
}
e = v._init.initializerToExpression();
}
else
e = v.type.defaultInitLiteral(e.loc);
e = interpret(e, istate);
}
else if (!(v.isDataseg() || v.storage_class & STC.manifest) && !v.isCTFE() && !istate)
{
error(loc, "variable `%s` cannot be read at compile time", v.toChars());
return CTFEExp.cantexp;
}
else
{
e = hasValue(v) ? getValue(v) : null;
if (!e && !v.isCTFE() && v.isDataseg())
{
error(loc, "static variable `%s` cannot be read at compile time", v.toChars());
return CTFEExp.cantexp;
}
if (!e)
{
assert(!(v._init && v._init.isVoidInitializer()));
// CTFE initiated from inside a function
error(loc, "variable `%s` cannot be read at compile time", v.toChars());
return CTFEExp.cantexp;
}
if (auto vie = e.isVoidInitExp())
{
error(loc, "cannot read uninitialized variable `%s` in ctfe", v.toPrettyChars());
errorSupplemental(vie.var.loc, "`%s` was uninitialized and used before set", vie.var.toChars());
return CTFEExp.cantexp;
}
if (goal != ctfeNeedLvalue && (v.isRef() || v.isOut()))
e = interpret(e, istate, goal);
}
if (!e)
e = CTFEExp.cantexp;
}
else if (SymbolDeclaration s = d.isSymbolDeclaration())
{
// Struct static initializers, for example
e = s.dsym.type.defaultInitLiteral(loc);
if (e.op == TOK.error)
error(loc, "CTFE failed because of previous errors in `%s.init`", s.toChars());
e = e.expressionSemantic(null);
if (e.op == TOK.error)
e = CTFEExp.cantexp;
else // Convert NULL to CTFEExp
e = interpret(e, istate, goal);
}
else
error(loc, "cannot interpret declaration `%s` at compile time", d.toChars());
return e;
}
override void visit(VarExp e)
{
debug (LOG)
{
printf("%s VarExp::interpret() `%s`, goal = %d\n", e.loc.toChars(), e.toChars(), goal);
}
if (e.var.isFuncDeclaration())
{
result = e;
return;
}
if (goal == ctfeNeedLvalue)
{
VarDeclaration v = e.var.isVarDeclaration();
if (v && !v.isDataseg() && !v.isCTFE() && !istate)
{
e.error("variable `%s` cannot be read at compile time", v.toChars());
result = CTFEExp.cantexp;
return;
}
if (v && !hasValue(v))
{
if (!v.isCTFE() && v.isDataseg())
e.error("static variable `%s` cannot be read at compile time", v.toChars());
else // CTFE initiated from inside a function
e.error("variable `%s` cannot be read at compile time", v.toChars());
result = CTFEExp.cantexp;
return;
}
if (v && (v.storage_class & (STC.out_ | STC.ref_)) && hasValue(v))
{
// Strip off the nest of ref variables
Expression ev = getValue(v);
if (ev.op == TOK.variable ||
ev.op == TOK.index ||
ev.op == TOK.slice ||
ev.op == TOK.dotVariable)
{
result = interpret(pue, ev, istate, goal);
return;
}
}
result = e;
return;
}
result = getVarExp(e.loc, istate, e.var, goal);
if (exceptionOrCant(result))
return;
if ((e.var.storage_class & (STC.ref_ | STC.out_)) == 0 && e.type.baseElemOf().ty != Tstruct)
{
/* Ultimately, STC.ref_|STC.out_ check should be enough to see the
* necessity of type repainting. But currently front-end paints
* non-ref struct variables by the const type.
*
* auto foo(ref const S cs);
* S s;
* foo(s); // VarExp('s') will have const(S)
*/
// A VarExp may include an implicit cast. It must be done explicitly.
result = paintTypeOntoLiteral(pue, e.type, result);
}
}
override void visit(DeclarationExp e)
{
debug (LOG)
{
printf("%s DeclarationExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
Dsymbol s = e.declaration;
if (VarDeclaration v = s.isVarDeclaration())
{
if (TupleDeclaration td = v.toAlias().isTupleDeclaration())
{
result = null;
// Reserve stack space for all tuple members
if (!td.objects)
return;
foreach (o; *td.objects)
{
Expression ex = isExpression(o);
DsymbolExp ds = ex ? ex.isDsymbolExp() : null;
VarDeclaration v2 = ds ? ds.s.isVarDeclaration() : null;
assert(v2);
if (v2.isDataseg() && !v2.isCTFE())
continue;
ctfeGlobals.stack.push(v2);
if (v2._init)
{
Expression einit;
if (ExpInitializer ie = v2._init.isExpInitializer())
{
einit = interpretRegion(ie.exp, istate, goal);
if (exceptionOrCant(einit))
return;
}
else if (v2._init.isVoidInitializer())
{
einit = voidInitLiteral(v2.type, v2).copy();
}
else
{
e.error("declaration `%s` is not yet implemented in CTFE", e.toChars());
result = CTFEExp.cantexp;
return;
}
setValue(v2, einit);
}
}
return;
}
if (v.isStatic())
{
// Just ignore static variables which aren't read or written yet
result = null;
return;
}
if (!(v.isDataseg() || v.storage_class & STC.manifest) || v.isCTFE())
ctfeGlobals.stack.push(v);
if (v._init)
{
if (ExpInitializer ie = v._init.isExpInitializer())
{
result = interpretRegion(ie.exp, istate, goal);
}
else if (v._init.isVoidInitializer())
{
result = voidInitLiteral(v.type, v).copy();
// There is no AssignExp for void initializers,
// so set it here.
setValue(v, result);
}
else
{
e.error("declaration `%s` is not yet implemented in CTFE", e.toChars());
result = CTFEExp.cantexp;
}
}
else if (v.type.size() == 0)
{
// Zero-length arrays don't need an initializer
result = v.type.defaultInitLiteral(e.loc);
}
else
{
e.error("variable `%s` cannot be modified at compile time", v.toChars());
result = CTFEExp.cantexp;
}
return;
}
if (s.isAttribDeclaration() || s.isTemplateMixin() || s.isTupleDeclaration())
{
// Check for static struct declarations, which aren't executable
AttribDeclaration ad = e.declaration.isAttribDeclaration();
if (ad && ad.decl && ad.decl.dim == 1)
{
Dsymbol sparent = (*ad.decl)[0];
if (sparent.isAggregateDeclaration() || sparent.isTemplateDeclaration() || sparent.isAliasDeclaration())
{
result = null;
return; // static (template) struct declaration. Nothing to do.
}
}
// These can be made to work, too lazy now
e.error("declaration `%s` is not yet implemented in CTFE", e.toChars());
result = CTFEExp.cantexp;
return;
}
// Others should not contain executable code, so are trivial to evaluate
result = null;
debug (LOG)
{
printf("-DeclarationExp::interpret(%s): %p\n", e.toChars(), result);
}
}
override void visit(TypeidExp e)
{
debug (LOG)
{
printf("%s TypeidExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
if (Type t = isType(e.obj))
{
result = e;
return;
}
if (Expression ex = isExpression(e.obj))
{
result = interpret(pue, ex, istate);
if (exceptionOrCant(ex))
return;
if (result.op == TOK.null_)
{
e.error("null pointer dereference evaluating typeid. `%s` is `null`", ex.toChars());
result = CTFEExp.cantexp;
return;
}
if (result.op != TOK.classReference)
{
e.error("CTFE internal error: determining classinfo");
result = CTFEExp.cantexp;
return;
}
ClassDeclaration cd = (cast(ClassReferenceExp)result).originalClass();
assert(cd);
emplaceExp!(TypeidExp)(pue, e.loc, cd.type);
result = pue.exp();
result.type = e.type;
return;
}
visit(cast(Expression)e);
}
override void visit(TupleExp e)
{
debug (LOG)
{
printf("%s TupleExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
if (exceptionOrCant(interpretRegion(e.e0, istate, ctfeNeedNothing)))
return;
auto expsx = e.exps;
foreach (i, exp; *expsx)
{
Expression ex = interpretRegion(exp, istate);
if (exceptionOrCant(ex))
return;
// A tuple of assignments can contain void (Bug 5676).
if (goal == ctfeNeedNothing)
continue;
if (ex.op == TOK.voidExpression)
{
e.error("CTFE internal error: void element `%s` in tuple", exp.toChars());
assert(0);
}
/* If any changes, do Copy On Write
*/
if (ex !is exp)
{
expsx = copyArrayOnWrite(expsx, e.exps);
(*expsx)[i] = copyRegionExp(ex);
}
}
if (expsx !is e.exps)
{
expandTuples(expsx);
emplaceExp!(TupleExp)(pue, e.loc, expsx);
result = pue.exp();
result.type = new TypeTuple(expsx);
}
else
result = e;
}
override void visit(ArrayLiteralExp e)
{
debug (LOG)
{
printf("%s ArrayLiteralExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
if (e.ownedByCtfe >= OwnedBy.ctfe) // We've already interpreted all the elements
{
result = e;
return;
}
Type tn = e.type.toBasetype().nextOf().toBasetype();
bool wantCopy = (tn.ty == Tsarray || tn.ty == Tstruct);
auto basis = interpretRegion(e.basis, istate);
if (exceptionOrCant(basis))
return;
auto expsx = e.elements;
size_t dim = expsx ? expsx.dim : 0;
for (size_t i = 0; i < dim; i++)
{
Expression exp = (*expsx)[i];
Expression ex;
if (!exp)
{
ex = copyLiteral(basis).copy();
}
else
{
// segfault bug 6250
assert(exp.op != TOK.index || (cast(IndexExp)exp).e1 != e);
ex = interpretRegion(exp, istate);
if (exceptionOrCant(ex))
return;
/* Each elements should have distinct CTFE memory.
* int[1] z = 7;
* int[1][] pieces = [z,z]; // here
*/
if (wantCopy)
ex = copyLiteral(ex).copy();
}
/* If any changes, do Copy On Write
*/
if (ex !is exp)
{
expsx = copyArrayOnWrite(expsx, e.elements);
(*expsx)[i] = ex;
}
}
if (expsx !is e.elements)
{
// todo: all tuple expansions should go in semantic phase.
expandTuples(expsx);
if (expsx.dim != dim)
{
e.error("CTFE internal error: invalid array literal");
result = CTFEExp.cantexp;
return;
}
emplaceExp!(ArrayLiteralExp)(pue, e.loc, e.type, basis, expsx);
auto ale = cast(ArrayLiteralExp)pue.exp();
ale.ownedByCtfe = OwnedBy.ctfe;
result = ale;
}
else if ((cast(TypeNext)e.type).next.mod & (MODFlags.const_ | MODFlags.immutable_))
{
// If it's immutable, we don't need to dup it
result = e;
}
else
{
*pue = copyLiteral(e);
result = pue.exp();
}
}
override void visit(AssocArrayLiteralExp e)
{
debug (LOG)
{
printf("%s AssocArrayLiteralExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
if (e.ownedByCtfe >= OwnedBy.ctfe) // We've already interpreted all the elements
{
result = e;
return;
}
auto keysx = e.keys;
auto valuesx = e.values;
foreach (i, ekey; *keysx)
{
auto evalue = (*valuesx)[i];
auto ek = interpretRegion(ekey, istate);
if (exceptionOrCant(ek))
return;
auto ev = interpretRegion(evalue, istate);
if (exceptionOrCant(ev))
return;
/* If any changes, do Copy On Write
*/
if (ek !is ekey ||
ev !is evalue)
{
keysx = copyArrayOnWrite(keysx, e.keys);
valuesx = copyArrayOnWrite(valuesx, e.values);
(*keysx)[i] = ek;
(*valuesx)[i] = ev;
}
}
if (keysx !is e.keys)
expandTuples(keysx);
if (valuesx !is e.values)
expandTuples(valuesx);
if (keysx.dim != valuesx.dim)
{
e.error("CTFE internal error: invalid AA");
result = CTFEExp.cantexp;
return;
}
/* Remove duplicate keys
*/
for (size_t i = 1; i < keysx.dim; i++)
{
auto ekey = (*keysx)[i - 1];
for (size_t j = i; j < keysx.dim; j++)
{
auto ekey2 = (*keysx)[j];
if (!ctfeEqual(e.loc, TOK.equal, ekey, ekey2))
continue;
// Remove ekey
keysx = copyArrayOnWrite(keysx, e.keys);
valuesx = copyArrayOnWrite(valuesx, e.values);
keysx.remove(i - 1);
valuesx.remove(i - 1);
i -= 1; // redo the i'th iteration
break;
}
}
if (keysx !is e.keys ||
valuesx !is e.values)
{
assert(keysx !is e.keys &&
valuesx !is e.values);
auto aae = ctfeEmplaceExp!AssocArrayLiteralExp(e.loc, keysx, valuesx);
aae.type = e.type;
aae.ownedByCtfe = OwnedBy.ctfe;
result = aae;
}
else
{
*pue = copyLiteral(e);
result = pue.exp();
}
}
override void visit(StructLiteralExp e)
{
debug (LOG)
{
printf("%s StructLiteralExp::interpret() %s ownedByCtfe = %d\n", e.loc.toChars(), e.toChars(), e.ownedByCtfe);
}
if (e.ownedByCtfe >= OwnedBy.ctfe)
{
result = e;
return;
}
size_t dim = e.elements ? e.elements.dim : 0;
auto expsx = e.elements;
if (dim != e.sd.fields.dim)
{
// guaranteed by AggregateDeclaration.fill and TypeStruct.defaultInitLiteral
const nvthis = e.sd.fields.dim - e.sd.nonHiddenFields();
assert(e.sd.fields.dim - dim == nvthis);
/* If a nested struct has no initialized hidden pointer,
* set it to null to match the runtime behaviour.
*/
foreach (const i; 0 .. nvthis)
{
auto ne = ctfeEmplaceExp!NullExp(e.loc);
auto vthis = i == 0 ? e.sd.vthis : e.sd.vthis2;
ne.type = vthis.type;
expsx = copyArrayOnWrite(expsx, e.elements);
expsx.push(ne);
++dim;
}
}
assert(dim == e.sd.fields.dim);
foreach (i; 0 .. dim)
{
auto v = e.sd.fields[i];
Expression exp = (*expsx)[i];
Expression ex;
if (!exp)
{
ex = voidInitLiteral(v.type, v).copy();
}
else
{
ex = interpretRegion(exp, istate);
if (exceptionOrCant(ex))
return;
if ((v.type.ty != ex.type.ty) && v.type.ty == Tsarray)
{
// Block assignment from inside struct literals
auto tsa = cast(TypeSArray)v.type;
auto len = cast(size_t)tsa.dim.toInteger();
UnionExp ue = void;
ex = createBlockDuplicatedArrayLiteral(&ue, ex.loc, v.type, ex, len);
if (ex == ue.exp())
ex = ue.copy();
}
}
/* If any changes, do Copy On Write
*/
if (ex !is exp)
{
expsx = copyArrayOnWrite(expsx, e.elements);
(*expsx)[i] = ex;
}
}
if (expsx !is e.elements)
{
expandTuples(expsx);
if (expsx.dim != e.sd.fields.dim)
{
e.error("CTFE internal error: invalid struct literal");
result = CTFEExp.cantexp;
return;
}
emplaceExp!(StructLiteralExp)(pue, e.loc, e.sd, expsx);
auto sle = cast(StructLiteralExp)pue.exp();
sle.type = e.type;
sle.ownedByCtfe = OwnedBy.ctfe;
sle.origin = e.origin;
result = sle;
}
else
{
*pue = copyLiteral(e);
result = pue.exp();
}
}
// Create an array literal of type 'newtype' with dimensions given by
// 'arguments'[argnum..$]
static Expression recursivelyCreateArrayLiteral(UnionExp* pue, const ref Loc loc, Type newtype, InterState* istate, Expressions* arguments, int argnum)
{
Expression lenExpr = interpret(pue, (*arguments)[argnum], istate);
if (exceptionOrCantInterpret(lenExpr))
return lenExpr;
size_t len = cast(size_t)lenExpr.toInteger();
Type elemType = (cast(TypeArray)newtype).next;
if (elemType.ty == Tarray && argnum < arguments.dim - 1)
{
Expression elem = recursivelyCreateArrayLiteral(pue, loc, elemType, istate, arguments, argnum + 1);
if (exceptionOrCantInterpret(elem))
return elem;
auto elements = new Expressions(len);
foreach (ref element; *elements)
element = copyLiteral(elem).copy();
emplaceExp!(ArrayLiteralExp)(pue, loc, newtype, elements);
auto ae = cast(ArrayLiteralExp)pue.exp();
ae.ownedByCtfe = OwnedBy.ctfe;
return ae;
}
assert(argnum == arguments.dim - 1);
if (elemType.ty == Tchar || elemType.ty == Twchar || elemType.ty == Tdchar)
{
const ch = cast(dchar)elemType.defaultInitLiteral(loc).toInteger();
const sz = cast(ubyte)elemType.size();
return createBlockDuplicatedStringLiteral(pue, loc, newtype, ch, len, sz);
}
else
{
auto el = interpret(elemType.defaultInitLiteral(loc), istate);
return createBlockDuplicatedArrayLiteral(pue, loc, newtype, el, len);
}
}
override void visit(NewExp e)
{
debug (LOG)
{
printf("%s NewExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
if (e.allocator)
{
e.error("member allocators not supported by CTFE");
result = CTFEExp.cantexp;
return;
}
Expression epre = interpret(pue, e.argprefix, istate, ctfeNeedNothing);
if (exceptionOrCant(epre))
return;
if (e.newtype.ty == Tarray && e.arguments)
{
result = recursivelyCreateArrayLiteral(pue, e.loc, e.newtype, istate, e.arguments, 0);
return;
}
if (auto ts = e.newtype.toBasetype().isTypeStruct())
{
if (e.member)
{
Expression se = e.newtype.defaultInitLiteral(e.loc);
se = interpret(se, istate);
if (exceptionOrCant(se))
return;
result = interpretFunction(pue, e.member, istate, e.arguments, se);
// Repaint as same as CallExp::interpret() does.
result.loc = e.loc;
}
else
{
StructDeclaration sd = ts.sym;
auto exps = new Expressions();
exps.reserve(sd.fields.dim);
if (e.arguments)
{
exps.setDim(e.arguments.dim);
foreach (i, ex; *e.arguments)
{
ex = interpretRegion(ex, istate);
if (exceptionOrCant(ex))
return;
(*exps)[i] = ex;
}
}
sd.fill(e.loc, exps, false);
auto se = ctfeEmplaceExp!StructLiteralExp(e.loc, sd, exps, e.newtype);
se.origin = se;
se.type = e.newtype;
se.ownedByCtfe = OwnedBy.ctfe;
result = interpret(pue, se, istate);
}
if (exceptionOrCant(result))
return;
Expression ev = (result == pue.exp()) ? pue.copy() : result;
emplaceExp!(AddrExp)(pue, e.loc, ev, e.type);
result = pue.exp();
return;
}
if (auto tc = e.newtype.toBasetype().isTypeClass())
{
ClassDeclaration cd = tc.sym;
size_t totalFieldCount = 0;
for (ClassDeclaration c = cd; c; c = c.baseClass)
totalFieldCount += c.fields.dim;
auto elems = new Expressions(totalFieldCount);
size_t fieldsSoFar = totalFieldCount;
for (ClassDeclaration c = cd; c; c = c.baseClass)
{
fieldsSoFar -= c.fields.dim;
foreach (i, v; c.fields)
{
if (v.inuse)
{
e.error("circular reference to `%s`", v.toPrettyChars());
result = CTFEExp.cantexp;
return;
}
Expression m;
if (v._init)
{
if (v._init.isVoidInitializer())
m = voidInitLiteral(v.type, v).copy();
else
m = v.getConstInitializer(true);
}
else
m = v.type.defaultInitLiteral(e.loc);
if (exceptionOrCant(m))
return;
(*elems)[fieldsSoFar + i] = copyLiteral(m).copy();
}
}
// Hack: we store a ClassDeclaration instead of a StructDeclaration.
// We probably won't get away with this.
// auto se = new StructLiteralExp(e.loc, cast(StructDeclaration)cd, elems, e.newtype);
auto se = ctfeEmplaceExp!StructLiteralExp(e.loc, cast(StructDeclaration)cd, elems, e.newtype);
se.origin = se;
se.ownedByCtfe = OwnedBy.ctfe;
emplaceExp!(ClassReferenceExp)(pue, e.loc, se, e.type);
Expression eref = pue.exp();
if (e.member)
{
// Call constructor
if (!e.member.fbody)
{
Expression ctorfail = evaluateIfBuiltin(pue, istate, e.loc, e.member, e.arguments, eref);
if (ctorfail)
{
if (exceptionOrCant(ctorfail))
return;
result = eref;
return;
}
e.member.error("`%s` cannot be constructed at compile time, because the constructor has no available source code", e.newtype.toChars());
result = CTFEExp.cantexp;
return;
}
UnionExp ue = void;
Expression ctorfail = interpretFunction(&ue, e.member, istate, e.arguments, eref);
if (exceptionOrCant(ctorfail))
return;
/* https://issues.dlang.org/show_bug.cgi?id=14465
* Repaint the loc, because a super() call
* in the constructor modifies the loc of ClassReferenceExp
* in CallExp::interpret().
*/
eref.loc = e.loc;
}
result = eref;
return;
}
if (e.newtype.toBasetype().isscalar())
{
Expression newval;
if (e.arguments && e.arguments.dim)
newval = (*e.arguments)[0];
else
newval = e.newtype.defaultInitLiteral(e.loc);
newval = interpretRegion(newval, istate);
if (exceptionOrCant(newval))
return;
// Create a CTFE pointer &[newval][0]
auto elements = new Expressions(1);
(*elements)[0] = newval;
auto ae = ctfeEmplaceExp!ArrayLiteralExp(e.loc, e.newtype.arrayOf(), elements);
ae.ownedByCtfe = OwnedBy.ctfe;
auto ei = ctfeEmplaceExp!IndexExp(e.loc, ae, ctfeEmplaceExp!IntegerExp(Loc.initial, 0, Type.tsize_t));
ei.type = e.newtype;
emplaceExp!(AddrExp)(pue, e.loc, ei, e.type);
result = pue.exp();
return;
}
e.error("cannot interpret `%s` at compile time", e.toChars());
result = CTFEExp.cantexp;
}
override void visit(UnaExp e)
{
debug (LOG)
{
printf("%s UnaExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
UnionExp ue = void;
Expression e1 = interpret(&ue, e.e1, istate);
if (exceptionOrCant(e1))
return;
switch (e.op)
{
case TOK.negate:
*pue = Neg(e.type, e1);
break;
case TOK.tilde:
*pue = Com(e.type, e1);
break;
case TOK.not:
*pue = Not(e.type, e1);
break;
default:
assert(0);
}
result = (*pue).exp();
}
override void visit(DotTypeExp e)
{
debug (LOG)
{
printf("%s DotTypeExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
UnionExp ue = void;
Expression e1 = interpret(&ue, e.e1, istate);
if (exceptionOrCant(e1))
return;
if (e1 == e.e1)
result = e; // optimize: reuse this CTFE reference
else
{
auto edt = cast(DotTypeExp)e.copy();
edt.e1 = (e1 == ue.exp()) ? e1.copy() : e1; // don't return pointer to ue
result = edt;
}
}
extern (D) private void interpretCommon(BinExp e, fp_t fp)
{
debug (LOG)
{
printf("%s BinExp::interpretCommon() %s\n", e.loc.toChars(), e.toChars());
}
if (e.e1.type.ty == Tpointer && e.e2.type.ty == Tpointer && e.op == TOK.min)
{
UnionExp ue1 = void;
Expression e1 = interpret(&ue1, e.e1, istate);
if (exceptionOrCant(e1))
return;
UnionExp ue2 = void;
Expression e2 = interpret(&ue2, e.e2, istate);
if (exceptionOrCant(e2))
return;
*pue = pointerDifference(e.loc, e.type, e1, e2);
result = (*pue).exp();
return;
}
if (e.e1.type.ty == Tpointer && e.e2.type.isintegral())
{
UnionExp ue1 = void;
Expression e1 = interpret(&ue1, e.e1, istate);
if (exceptionOrCant(e1))
return;
UnionExp ue2 = void;
Expression e2 = interpret(&ue2, e.e2, istate);
if (exceptionOrCant(e2))
return;
*pue = pointerArithmetic(e.loc, e.op, e.type, e1, e2);
result = (*pue).exp();
return;
}
if (e.e2.type.ty == Tpointer && e.e1.type.isintegral() && e.op == TOK.add)
{
UnionExp ue1 = void;
Expression e1 = interpret(&ue1, e.e1, istate);
if (exceptionOrCant(e1))
return;
UnionExp ue2 = void;
Expression e2 = interpret(&ue2, e.e2, istate);
if (exceptionOrCant(e2))
return;
*pue = pointerArithmetic(e.loc, e.op, e.type, e2, e1);
result = (*pue).exp();
return;
}
if (e.e1.type.ty == Tpointer || e.e2.type.ty == Tpointer)
{
e.error("pointer expression `%s` cannot be interpreted at compile time", e.toChars());
result = CTFEExp.cantexp;
return;
}
bool evalOperand(UnionExp* pue, Expression ex, out Expression er)
{
er = interpret(pue, ex, istate);
if (exceptionOrCant(er))
return false;
if (er.isConst() != 1)
{
if (er.op == TOK.arrayLiteral)
// Until we get it to work, issue a reasonable error message
e.error("cannot interpret array literal expression `%s` at compile time", e.toChars());
else
e.error("CTFE internal error: non-constant value `%s`", ex.toChars());
result = CTFEExp.cantexp;
return false;
}
return true;
}
UnionExp ue1 = void;
Expression e1;
if (!evalOperand(&ue1, e.e1, e1))
return;
UnionExp ue2 = void;
Expression e2;
if (!evalOperand(&ue2, e.e2, e2))
return;
if (e.op == TOK.rightShift || e.op == TOK.leftShift || e.op == TOK.unsignedRightShift)
{
const sinteger_t i2 = e2.toInteger();
const d_uns64 sz = e1.type.size() * 8;
if (i2 < 0 || i2 >= sz)
{
e.error("shift by %lld is outside the range 0..%llu", i2, cast(ulong)sz - 1);
result = CTFEExp.cantexp;
return;
}
}
*pue = (*fp)(e.loc, e.type, e1, e2);
result = (*pue).exp();
if (CTFEExp.isCantExp(result))
e.error("`%s` cannot be interpreted at compile time", e.toChars());
}
extern (D) private void interpretCompareCommon(BinExp e, fp2_t fp)
{
debug (LOG)
{
printf("%s BinExp::interpretCompareCommon() %s\n", e.loc.toChars(), e.toChars());
}
UnionExp ue1 = void;
UnionExp ue2 = void;
if (e.e1.type.ty == Tpointer && e.e2.type.ty == Tpointer)
{
Expression e1 = interpret(&ue1, e.e1, istate);
if (exceptionOrCant(e1))
return;
Expression e2 = interpret(&ue2, e.e2, istate);
if (exceptionOrCant(e2))
return;
//printf("e1 = %s %s, e2 = %s %s\n", e1.type.toChars(), e1.toChars(), e2.type.toChars(), e2.toChars());
dinteger_t ofs1, ofs2;
Expression agg1 = getAggregateFromPointer(e1, &ofs1);
Expression agg2 = getAggregateFromPointer(e2, &ofs2);
//printf("agg1 = %p %s, agg2 = %p %s\n", agg1, agg1.toChars(), agg2, agg2.toChars());
const cmp = comparePointers(e.op, agg1, ofs1, agg2, ofs2);
if (cmp == -1)
{
char dir = (e.op == TOK.greaterThan || e.op == TOK.greaterOrEqual) ? '<' : '>';
e.error("the ordering of pointers to unrelated memory blocks is indeterminate in CTFE. To check if they point to the same memory block, use both `>` and `<` inside `&&` or `||`, eg `%s && %s %c= %s + 1`", e.toChars(), e.e1.toChars(), dir, e.e2.toChars());
result = CTFEExp.cantexp;
return;
}
if (e.type.equals(Type.tbool))
result = IntegerExp.createBool(cmp != 0);
else
{
emplaceExp!(IntegerExp)(pue, e.loc, cmp, e.type);
result = (*pue).exp();
}
return;
}
Expression e1 = interpret(&ue1, e.e1, istate);
if (exceptionOrCant(e1))
return;
if (!isCtfeComparable(e1))
{
e.error("cannot compare `%s` at compile time", e1.toChars());
result = CTFEExp.cantexp;
return;
}
Expression e2 = interpret(&ue2, e.e2, istate);
if (exceptionOrCant(e2))
return;
if (!isCtfeComparable(e2))
{
e.error("cannot compare `%s` at compile time", e2.toChars());
result = CTFEExp.cantexp;
return;
}
const cmp = (*fp)(e.loc, e.op, e1, e2);
if (e.type.equals(Type.tbool))
result = IntegerExp.createBool(cmp);
else
{
emplaceExp!(IntegerExp)(pue, e.loc, cmp, e.type);
result = (*pue).exp();
}
}
override void visit(BinExp e)
{
switch (e.op)
{
case TOK.add:
interpretCommon(e, &Add);
return;
case TOK.min:
interpretCommon(e, &Min);
return;
case TOK.mul:
interpretCommon(e, &Mul);
return;
case TOK.div:
interpretCommon(e, &Div);
return;
case TOK.mod:
interpretCommon(e, &Mod);
return;
case TOK.leftShift:
interpretCommon(e, &Shl);
return;
case TOK.rightShift:
interpretCommon(e, &Shr);
return;
case TOK.unsignedRightShift:
interpretCommon(e, &Ushr);
return;
case TOK.and:
interpretCommon(e, &And);
return;
case TOK.or:
interpretCommon(e, &Or);
return;
case TOK.xor:
interpretCommon(e, &Xor);
return;
case TOK.pow:
interpretCommon(e, &Pow);
return;
case TOK.equal:
case TOK.notEqual:
interpretCompareCommon(e, &ctfeEqual);
return;
case TOK.identity:
case TOK.notIdentity:
interpretCompareCommon(e, &ctfeIdentity);
return;
case TOK.lessThan:
case TOK.lessOrEqual:
case TOK.greaterThan:
case TOK.greaterOrEqual:
interpretCompareCommon(e, &ctfeCmp);
return;
default:
printf("be = '%s' %s at [%s]\n", Token.toChars(e.op), e.toChars(), e.loc.toChars());
assert(0);
}
}
/* Helper functions for BinExp::interpretAssignCommon
*/
// Returns the variable which is eventually modified, or NULL if an rvalue.
// thisval is the current value of 'this'.
static VarDeclaration findParentVar(Expression e)
{
for (;;)
{
if (auto ve = e.isVarExp())
{
VarDeclaration v = ve.var.isVarDeclaration();
assert(v);
return v;
}
if (auto ie = e.isIndexExp())
e = ie.e1;
else if (auto dve = e.isDotVarExp())
e = dve.e1;
else if (auto dtie = e.isDotTemplateInstanceExp())
e = dtie.e1;
else if (auto se = e.isSliceExp())
e = se.e1;
else
return null;
}
}
extern (D) private void interpretAssignCommon(BinExp e, fp_t fp, int post = 0)
{
debug (LOG)
{
printf("%s BinExp::interpretAssignCommon() %s\n", e.loc.toChars(), e.toChars());
}
result = CTFEExp.cantexp;
Expression e1 = e.e1;
if (!istate)
{
e.error("value of `%s` is not known at compile time", e1.toChars());
return;
}
++ctfeGlobals.numAssignments;
/* Before we begin, we need to know if this is a reference assignment
* (dynamic array, AA, or class) or a value assignment.
* Determining this for slice assignments are tricky: we need to know
* if it is a block assignment (a[] = e) rather than a direct slice
* assignment (a[] = b[]). Note that initializers of multi-dimensional
* static arrays can have 2D block assignments (eg, int[7][7] x = 6;).
* So we need to recurse to determine if it is a block assignment.
*/
bool isBlockAssignment = false;
if (e1.op == TOK.slice)
{
// a[] = e can have const e. So we compare the naked types.
Type tdst = e1.type.toBasetype();
Type tsrc = e.e2.type.toBasetype();
while (tdst.ty == Tsarray || tdst.ty == Tarray)
{
tdst = (cast(TypeArray)tdst).next.toBasetype();
if (tsrc.equivalent(tdst))
{
isBlockAssignment = true;
break;
}
}
}
// ---------------------------------------
// Deal with reference assignment
// ---------------------------------------
// If it is a construction of a ref variable, it is a ref assignment
if ((e.op == TOK.construct || e.op == TOK.blit) &&
((cast(AssignExp)e).memset & MemorySet.referenceInit))
{
assert(!fp);
Expression newval = interpretRegion(e.e2, istate, ctfeNeedLvalue);
if (exceptionOrCant(newval))
return;
VarDeclaration v = (cast(VarExp)e1).var.isVarDeclaration();
setValue(v, newval);
// Get the value to return. Note that 'newval' is an Lvalue,
// so if we need an Rvalue, we have to interpret again.
if (goal == ctfeNeedRvalue)
result = interpretRegion(newval, istate);
else
result = e1; // VarExp is a CTFE reference
return;
}
if (fp)
{
while (e1.op == TOK.cast_)
{
CastExp ce = cast(CastExp)e1;
e1 = ce.e1;
}
}
// ---------------------------------------
// Interpret left hand side
// ---------------------------------------
AssocArrayLiteralExp existingAA = null;
Expression lastIndex = null;
Expression oldval = null;
if (e1.op == TOK.index && (cast(IndexExp)e1).e1.type.toBasetype().ty == Taarray)
{
// ---------------------------------------
// Deal with AA index assignment
// ---------------------------------------
/* This needs special treatment if the AA doesn't exist yet.
* There are two special cases:
* (1) If the AA is itself an index of another AA, we may need to create
* multiple nested AA literals before we can insert the new value.
* (2) If the ultimate AA is null, no insertion happens at all. Instead,
* we create nested AA literals, and change it into a assignment.
*/
IndexExp ie = cast(IndexExp)e1;
int depth = 0; // how many nested AA indices are there?
while (ie.e1.op == TOK.index && (cast(IndexExp)ie.e1).e1.type.toBasetype().ty == Taarray)
{
assert(ie.modifiable);
ie = cast(IndexExp)ie.e1;
++depth;
}
// Get the AA value to be modified.
Expression aggregate = interpretRegion(ie.e1, istate);
if (exceptionOrCant(aggregate))
return;
if ((existingAA = aggregate.isAssocArrayLiteralExp()) !is null)
{
// Normal case, ultimate parent AA already exists
// We need to walk from the deepest index up, checking that an AA literal
// already exists on each level.
lastIndex = interpretRegion((cast(IndexExp)e1).e2, istate);
lastIndex = resolveSlice(lastIndex); // only happens with AA assignment
if (exceptionOrCant(lastIndex))
return;
while (depth > 0)
{
// Walk the syntax tree to find the indexExp at this depth
IndexExp xe = cast(IndexExp)e1;
foreach (d; 0 .. depth)
xe = cast(IndexExp)xe.e1;
Expression ekey = interpretRegion(xe.e2, istate);
if (exceptionOrCant(ekey))
return;
UnionExp ekeyTmp = void;
ekey = resolveSlice(ekey, &ekeyTmp); // only happens with AA assignment
// Look up this index in it up in the existing AA, to get the next level of AA.
AssocArrayLiteralExp newAA = cast(AssocArrayLiteralExp)findKeyInAA(e.loc, existingAA, ekey);
if (exceptionOrCant(newAA))
return;
if (!newAA)
{
// Doesn't exist yet, create an empty AA...
auto keysx = new Expressions();
auto valuesx = new Expressions();
newAA = ctfeEmplaceExp!AssocArrayLiteralExp(e.loc, keysx, valuesx);
newAA.type = xe.type;
newAA.ownedByCtfe = OwnedBy.ctfe;
//... and insert it into the existing AA.
existingAA.keys.push(ekey);
existingAA.values.push(newAA);
}
existingAA = newAA;
--depth;
}
if (fp)
{
oldval = findKeyInAA(e.loc, existingAA, lastIndex);
if (!oldval)
oldval = copyLiteral(e.e1.type.defaultInitLiteral(e.loc)).copy();
}
}
else
{
/* The AA is currently null. 'aggregate' is actually a reference to
* whatever contains it. It could be anything: var, dotvarexp, ...
* We rewrite the assignment from:
* aa[i][j] op= newval;
* into:
* aa = [i:[j:T.init]];
* aa[j] op= newval;
*/
oldval = copyLiteral(e.e1.type.defaultInitLiteral(e.loc)).copy();
Expression newaae = oldval;
while (e1.op == TOK.index && (cast(IndexExp)e1).e1.type.toBasetype().ty == Taarray)
{
Expression ekey = interpretRegion((cast(IndexExp)e1).e2, istate);
if (exceptionOrCant(ekey))
return;
ekey = resolveSlice(ekey); // only happens with AA assignment
auto keysx = new Expressions();
auto valuesx = new Expressions();
keysx.push(ekey);
valuesx.push(newaae);
auto aae = ctfeEmplaceExp!AssocArrayLiteralExp(e.loc, keysx, valuesx);
aae.type = (cast(IndexExp)e1).e1.type;
aae.ownedByCtfe = OwnedBy.ctfe;
if (!existingAA)
{
existingAA = aae;
lastIndex = ekey;
}
newaae = aae;
e1 = (cast(IndexExp)e1).e1;
}
// We must set to aggregate with newaae
e1 = interpretRegion(e1, istate, ctfeNeedLvalue);
if (exceptionOrCant(e1))
return;
e1 = assignToLvalue(e, e1, newaae);
if (exceptionOrCant(e1))
return;
}
assert(existingAA && lastIndex);
e1 = null; // stomp
}
else if (e1.op == TOK.arrayLength)
{
oldval = interpretRegion(e1, istate);
if (exceptionOrCant(oldval))
return;
}
else if (e.op == TOK.construct || e.op == TOK.blit)
{
// Unless we have a simple var assignment, we're
// only modifying part of the variable. So we need to make sure
// that the parent variable exists.
VarDeclaration ultimateVar = findParentVar(e1);
if (auto ve = e1.isVarExp())
{
VarDeclaration v = ve.var.isVarDeclaration();
assert(v);
if (v.storage_class & STC.out_)
goto L1;
}
else if (ultimateVar && !getValue(ultimateVar))
{
Expression ex = interpretRegion(ultimateVar.type.defaultInitLiteral(e.loc), istate);
if (exceptionOrCant(ex))
return;
setValue(ultimateVar, ex);
}
else
goto L1;
}
else
{
L1:
e1 = interpretRegion(e1, istate, ctfeNeedLvalue);
if (exceptionOrCant(e1))
return;
if (e1.op == TOK.index && (cast(IndexExp)e1).e1.type.toBasetype().ty == Taarray)
{
IndexExp ie = cast(IndexExp)e1;
assert(ie.e1.op == TOK.assocArrayLiteral);
existingAA = cast(AssocArrayLiteralExp)ie.e1;
lastIndex = ie.e2;
}
}
// ---------------------------------------
// Interpret right hand side
// ---------------------------------------
Expression newval = interpretRegion(e.e2, istate);
if (exceptionOrCant(newval))
return;
if (e.op == TOK.blit && newval.op == TOK.int64)
{
Type tbn = e.type.baseElemOf();
if (tbn.ty == Tstruct)
{
/* Look for special case of struct being initialized with 0.
*/
newval = e.type.defaultInitLiteral(e.loc);
if (newval.op == TOK.error)
{
result = CTFEExp.cantexp;
return;
}
newval = interpretRegion(newval, istate); // copy and set ownedByCtfe flag
if (exceptionOrCant(newval))
return;
}
}
// ----------------------------------------------------
// Deal with read-modify-write assignments.
// Set 'newval' to the final assignment value
// Also determine the return value (except for slice
// assignments, which are more complicated)
// ----------------------------------------------------
if (fp)
{
if (!oldval)
{
// Load the left hand side after interpreting the right hand side.
oldval = interpretRegion(e1, istate);
if (exceptionOrCant(oldval))
return;
}
if (e.e1.type.ty != Tpointer)
{
// ~= can create new values (see bug 6052)
if (e.op == TOK.concatenateAssign || e.op == TOK.concatenateElemAssign || e.op == TOK.concatenateDcharAssign)
{
// We need to dup it and repaint the type. For a dynamic array
// we can skip duplication, because it gets copied later anyway.
if (newval.type.ty != Tarray)
{
newval = copyLiteral(newval).copy();
newval.type = e.e2.type; // repaint type
}
else
{
newval = paintTypeOntoLiteral(e.e2.type, newval);
newval = resolveSlice(newval);
}
}
oldval = resolveSlice(oldval);
newval = (*fp)(e.loc, e.type, oldval, newval).copy();
}
else if (e.e2.type.isintegral() &&
(e.op == TOK.addAssign ||
e.op == TOK.minAssign ||
e.op == TOK.plusPlus ||
e.op == TOK.minusMinus))
{
newval = pointerArithmetic(e.loc, e.op, e.type, oldval, newval).copy();
}
else
{
e.error("pointer expression `%s` cannot be interpreted at compile time", e.toChars());
result = CTFEExp.cantexp;
return;
}
if (exceptionOrCant(newval))
{
if (CTFEExp.isCantExp(newval))
e.error("cannot interpret `%s` at compile time", e.toChars());
return;
}
}
if (existingAA)
{
if (existingAA.ownedByCtfe != OwnedBy.ctfe)
{
e.error("cannot modify read-only constant `%s`", existingAA.toChars());
result = CTFEExp.cantexp;
return;
}
//printf("\t+L%d existingAA = %s, lastIndex = %s, oldval = %s, newval = %s\n",
// __LINE__, existingAA.toChars(), lastIndex.toChars(), oldval ? oldval.toChars() : NULL, newval.toChars());
assignAssocArrayElement(e.loc, existingAA, lastIndex, newval);
// Determine the return value
result = ctfeCast(pue, e.loc, e.type, e.type, fp && post ? oldval : newval);
return;
}
if (e1.op == TOK.arrayLength)
{
/* Change the assignment from:
* arr.length = n;
* into:
* arr = new_length_array; (result is n)
*/
// Determine the return value
result = ctfeCast(pue, e.loc, e.type, e.type, fp && post ? oldval : newval);
if (exceptionOrCant(result))
return;
if (result == pue.exp())
result = pue.copy();
size_t oldlen = cast(size_t)oldval.toInteger();
size_t newlen = cast(size_t)newval.toInteger();
if (oldlen == newlen) // no change required -- we're done!
return;
// We have changed it into a reference assignment
// Note that returnValue is still the new length.
e1 = (cast(ArrayLengthExp)e1).e1;
Type t = e1.type.toBasetype();
if (t.ty != Tarray)
{
e.error("`%s` is not yet supported at compile time", e.toChars());
result = CTFEExp.cantexp;
return;
}
e1 = interpretRegion(e1, istate, ctfeNeedLvalue);
if (exceptionOrCant(e1))
return;
if (oldlen != 0) // Get the old array literal.
oldval = interpretRegion(e1, istate);
UnionExp utmp = void;
oldval = resolveSlice(oldval, &utmp);
newval = changeArrayLiteralLength(e.loc, cast(TypeArray)t, oldval, oldlen, newlen).copy();
e1 = assignToLvalue(e, e1, newval);
if (exceptionOrCant(e1))
return;
return;
}
if (!isBlockAssignment)
{
newval = ctfeCast(pue, e.loc, e.type, e.type, newval);
if (exceptionOrCant(newval))
return;
if (newval == pue.exp())
newval = pue.copy();
// Determine the return value
if (goal == ctfeNeedLvalue) // https://issues.dlang.org/show_bug.cgi?id=14371
result = e1;
else
{
result = ctfeCast(pue, e.loc, e.type, e.type, fp && post ? oldval : newval);
if (result == pue.exp())
result = pue.copy();
}
if (exceptionOrCant(result))
return;
}
if (exceptionOrCant(newval))
return;
debug (LOGASSIGN)
{
printf("ASSIGN: %s=%s\n", e1.toChars(), newval.toChars());
showCtfeExpr(newval);
}
/* Block assignment or element-wise assignment.
*/
if (e1.op == TOK.slice ||
e1.op == TOK.vector ||
e1.op == TOK.arrayLiteral ||
e1.op == TOK.string_ ||
e1.op == TOK.null_ && e1.type.toBasetype().ty == Tarray)
{
// Note that slice assignments don't support things like ++, so
// we don't need to remember 'returnValue'.
result = interpretAssignToSlice(pue, e, e1, newval, isBlockAssignment);
if (exceptionOrCant(result))
return;
if (auto se = e.e1.isSliceExp())
{
Expression e1x = interpretRegion(se.e1, istate, ctfeNeedLvalue);
if (auto dve = e1x.isDotVarExp())
{
auto ex = dve.e1;
auto sle = ex.op == TOK.structLiteral ? (cast(StructLiteralExp)ex)
: ex.op == TOK.classReference ? (cast(ClassReferenceExp)ex).value
: null;
auto v = dve.var.isVarDeclaration();
if (!sle || !v)
{
e.error("CTFE internal error: dotvar slice assignment");
result = CTFEExp.cantexp;
return;
}
stompOverlappedFields(sle, v);
}
}
return;
}
assert(result);
/* Assignment to a CTFE reference.
*/
if (Expression ex = assignToLvalue(e, e1, newval))
result = ex;
return;
}
/* Set all sibling fields which overlap with v to VoidExp.
*/
private void stompOverlappedFields(StructLiteralExp sle, VarDeclaration v)
{
if (!v.overlapped)
return;
foreach (size_t i, v2; sle.sd.fields)
{
if (v is v2 || !v.isOverlappedWith(v2))
continue;
auto e = (*sle.elements)[i];
if (e.op != TOK.void_)
(*sle.elements)[i] = voidInitLiteral(e.type, v).copy();
}
}
private Expression assignToLvalue(BinExp e, Expression e1, Expression newval)
{
VarDeclaration vd = null;
Expression* payload = null; // dead-store to prevent spurious warning
Expression oldval;
int from;
if (auto ve = e1.isVarExp())
{
vd = ve.var.isVarDeclaration();
oldval = getValue(vd);
}
else if (auto dve = e1.isDotVarExp())
{
/* Assignment to member variable of the form:
* e.v = newval
*/
auto ex = dve.e1;
auto sle = ex.op == TOK.structLiteral ? (cast(StructLiteralExp)ex)
: ex.op == TOK.classReference ? (cast(ClassReferenceExp)ex).value
: null;
auto v = (cast(DotVarExp)e1).var.isVarDeclaration();
if (!sle || !v)
{
e.error("CTFE internal error: dotvar assignment");
return CTFEExp.cantexp;
}
if (sle.ownedByCtfe != OwnedBy.ctfe)
{
e.error("cannot modify read-only constant `%s`", sle.toChars());
return CTFEExp.cantexp;
}
int fieldi = ex.op == TOK.structLiteral ? findFieldIndexByName(sle.sd, v)
: (cast(ClassReferenceExp)ex).findFieldIndexByName(v);
if (fieldi == -1)
{
e.error("CTFE internal error: cannot find field `%s` in `%s`", v.toChars(), ex.toChars());
return CTFEExp.cantexp;
}
assert(0 <= fieldi && fieldi < sle.elements.dim);
// If it's a union, set all other members of this union to void
stompOverlappedFields(sle, v);
payload = &(*sle.elements)[fieldi];
oldval = *payload;
}
else if (auto ie = e1.isIndexExp())
{
assert(ie.e1.type.toBasetype().ty != Taarray);
Expression aggregate;
uinteger_t indexToModify;
if (!resolveIndexing(ie, istate, &aggregate, &indexToModify, true))
{
return CTFEExp.cantexp;
}
size_t index = cast(size_t)indexToModify;
if (auto existingSE = aggregate.isStringExp())
{
if (existingSE.ownedByCtfe != OwnedBy.ctfe)
{
e.error("cannot modify read-only string literal `%s`", ie.e1.toChars());
return CTFEExp.cantexp;
}
existingSE.setCodeUnit(index, cast(dchar)newval.toInteger());
return null;
}
if (aggregate.op != TOK.arrayLiteral)
{
e.error("index assignment `%s` is not yet supported in CTFE ", e.toChars());
return CTFEExp.cantexp;
}
ArrayLiteralExp existingAE = cast(ArrayLiteralExp)aggregate;
if (existingAE.ownedByCtfe != OwnedBy.ctfe)
{
e.error("cannot modify read-only constant `%s`", existingAE.toChars());
return CTFEExp.cantexp;
}
payload = &(*existingAE.elements)[index];
oldval = *payload;
}
else
{
e.error("`%s` cannot be evaluated at compile time", e.toChars());
return CTFEExp.cantexp;
}
Type t1b = e1.type.toBasetype();
bool wantCopy = t1b.baseElemOf().ty == Tstruct;
if (newval.op == TOK.structLiteral && oldval)
{
assert(oldval.op == TOK.structLiteral || oldval.op == TOK.arrayLiteral || oldval.op == TOK.string_);
newval = copyLiteral(newval).copy();
assignInPlace(oldval, newval);
}
else if (wantCopy && e.op == TOK.assign)
{
// Currently postblit/destructor calls on static array are done
// in the druntime internal functions so they don't appear in AST.
// Therefore interpreter should handle them specially.
assert(oldval);
version (all) // todo: instead we can directly access to each elements of the slice
{
newval = resolveSlice(newval);
if (CTFEExp.isCantExp(newval))
{
e.error("CTFE internal error: assignment `%s`", e.toChars());
return CTFEExp.cantexp;
}
}
assert(oldval.op == TOK.arrayLiteral);
assert(newval.op == TOK.arrayLiteral);
Expressions* oldelems = (cast(ArrayLiteralExp)oldval).elements;
Expressions* newelems = (cast(ArrayLiteralExp)newval).elements;
assert(oldelems.dim == newelems.dim);
Type elemtype = oldval.type.nextOf();
foreach (i, ref oldelem; *oldelems)
{
Expression newelem = paintTypeOntoLiteral(elemtype, (*newelems)[i]);
// https://issues.dlang.org/show_bug.cgi?id=9245
if (e.e2.isLvalue())
{
if (Expression ex = evaluatePostblit(istate, newelem))
return ex;
}
// https://issues.dlang.org/show_bug.cgi?id=13661
if (Expression ex = evaluateDtor(istate, oldelem))
return ex;
oldelem = newelem;
}
}
else
{
// e1 has its own payload, so we have to create a new literal.
if (wantCopy)
newval = copyLiteral(newval).copy();
if (t1b.ty == Tsarray && e.op == TOK.construct && e.e2.isLvalue())
{
// https://issues.dlang.org/show_bug.cgi?id=9245
if (Expression ex = evaluatePostblit(istate, newval))
return ex;
}
oldval = newval;
}
if (vd)
setValue(vd, oldval);
else
*payload = oldval;
// Blit assignment should return the newly created value.
if (e.op == TOK.blit)
return oldval;
return null;
}
/*************
* Deal with assignments of the form:
* dest[] = newval
* dest[low..upp] = newval
* where newval has already been interpreted
*
* This could be a slice assignment or a block assignment, and
* dest could be either an array literal, or a string.
*
* Returns TOK.cantExpression on failure. If there are no errors,
* it returns aggregate[low..upp], except that as an optimisation,
* if goal == ctfeNeedNothing, it will return NULL
*/
private Expression interpretAssignToSlice(UnionExp* pue, BinExp e, Expression e1, Expression newval, bool isBlockAssignment)
{
dinteger_t lowerbound;
dinteger_t upperbound;
dinteger_t firstIndex;
Expression aggregate;
if (auto se = e1.isSliceExp())
{
// ------------------------------
// aggregate[] = newval
// aggregate[low..upp] = newval
// ------------------------------
version (all) // should be move in interpretAssignCommon as the evaluation of e1
{
Expression oldval = interpretRegion(se.e1, istate);
// Set the $ variable
uinteger_t dollar = resolveArrayLength(oldval);
if (se.lengthVar)
{
Expression dollarExp = ctfeEmplaceExp!IntegerExp(e1.loc, dollar, Type.tsize_t);
ctfeGlobals.stack.push(se.lengthVar);
setValue(se.lengthVar, dollarExp);
}
Expression lwr = interpretRegion(se.lwr, istate);
if (exceptionOrCantInterpret(lwr))
{
if (se.lengthVar)
ctfeGlobals.stack.pop(se.lengthVar);
return lwr;
}
Expression upr = interpretRegion(se.upr, istate);
if (exceptionOrCantInterpret(upr))
{
if (se.lengthVar)
ctfeGlobals.stack.pop(se.lengthVar);
return upr;
}
if (se.lengthVar)
ctfeGlobals.stack.pop(se.lengthVar); // $ is defined only in [L..U]
const dim = dollar;
lowerbound = lwr ? lwr.toInteger() : 0;
upperbound = upr ? upr.toInteger() : dim;
if (lowerbound < 0 || dim < upperbound)
{
e.error("array bounds `[0..%llu]` exceeded in slice `[%llu..%llu]`",
ulong(dim), ulong(lowerbound), ulong(upperbound));
return CTFEExp.cantexp;
}
}
aggregate = oldval;
firstIndex = lowerbound;
if (auto oldse = aggregate.isSliceExp())
{
// Slice of a slice --> change the bounds
if (oldse.upr.toInteger() < upperbound + oldse.lwr.toInteger())
{
e.error("slice `[%llu..%llu]` exceeds array bounds `[0..%llu]`",
ulong(lowerbound), ulong(upperbound), oldse.upr.toInteger() - oldse.lwr.toInteger());
return CTFEExp.cantexp;
}
aggregate = oldse.e1;
firstIndex = lowerbound + oldse.lwr.toInteger();
}
}
else
{
if (auto ale = e1.isArrayLiteralExp())
{
lowerbound = 0;
upperbound = ale.elements.dim;
}
else if (auto se = e1.isStringExp())
{
lowerbound = 0;
upperbound = se.len;
}
else if (e1.op == TOK.null_)
{
lowerbound = 0;
upperbound = 0;
}
else if (VectorExp ve = e1.isVectorExp())
{
// ve is not handled but a proper error message is returned
// this is to prevent https://issues.dlang.org/show_bug.cgi?id=20042
lowerbound = 0;
upperbound = ve.dim;
}
else
assert(0);
aggregate = e1;
firstIndex = lowerbound;
}
if (upperbound == lowerbound)
return newval;
// For slice assignment, we check that the lengths match.
if (!isBlockAssignment)
{
const srclen = resolveArrayLength(newval);
if (srclen != (upperbound - lowerbound))
{
e.error("array length mismatch assigning `[0..%llu]` to `[%llu..%llu]`",
ulong(srclen), ulong(lowerbound), ulong(upperbound));
return CTFEExp.cantexp;
}
}
if (auto existingSE = aggregate.isStringExp())
{
if (existingSE.ownedByCtfe != OwnedBy.ctfe)
{
e.error("cannot modify read-only string literal `%s`", existingSE.toChars());
return CTFEExp.cantexp;
}
if (auto se = newval.isSliceExp())
{
auto aggr2 = se.e1;
const srclower = se.lwr.toInteger();
const srcupper = se.upr.toInteger();
if (aggregate == aggr2 &&
lowerbound < srcupper && srclower < upperbound)
{
e.error("overlapping slice assignment `[%llu..%llu] = [%llu..%llu]`",
ulong(lowerbound), ulong(upperbound), ulong(srclower), ulong(srcupper));
return CTFEExp.cantexp;
}
version (all) // todo: instead we can directly access to each elements of the slice
{
Expression orignewval = newval;
newval = resolveSlice(newval);
if (CTFEExp.isCantExp(newval))
{
e.error("CTFE internal error: slice `%s`", orignewval.toChars());
return CTFEExp.cantexp;
}
}
assert(newval.op != TOK.slice);
}
if (auto se = newval.isStringExp())
{
sliceAssignStringFromString(existingSE, se, cast(size_t)firstIndex);
return newval;
}
if (auto ale = newval.isArrayLiteralExp())
{
/* Mixed slice: it was initialized as a string literal.
* Now a slice of it is being set with an array literal.
*/
sliceAssignStringFromArrayLiteral(existingSE, ale, cast(size_t)firstIndex);
return newval;
}
// String literal block slice assign
const value = cast(dchar)newval.toInteger();
foreach (i; 0 .. upperbound - lowerbound)
{
existingSE.setCodeUnit(cast(size_t)(i + firstIndex), value);
}
if (goal == ctfeNeedNothing)
return null; // avoid creating an unused literal
auto retslice = ctfeEmplaceExp!SliceExp(e.loc, existingSE,
ctfeEmplaceExp!IntegerExp(e.loc, firstIndex, Type.tsize_t),
ctfeEmplaceExp!IntegerExp(e.loc, firstIndex + upperbound - lowerbound, Type.tsize_t));
retslice.type = e.type;
return interpret(pue, retslice, istate);
}
if (auto existingAE = aggregate.isArrayLiteralExp())
{
if (existingAE.ownedByCtfe != OwnedBy.ctfe)
{
e.error("cannot modify read-only constant `%s`", existingAE.toChars());
return CTFEExp.cantexp;
}
if (newval.op == TOK.slice && !isBlockAssignment)
{
auto se = cast(SliceExp)newval;
auto aggr2 = se.e1;
const srclower = se.lwr.toInteger();
const srcupper = se.upr.toInteger();
const wantCopy = (newval.type.toBasetype().nextOf().baseElemOf().ty == Tstruct);
//printf("oldval = %p %s[%d..%u]\nnewval = %p %s[%llu..%llu] wantCopy = %d\n",
// aggregate, aggregate.toChars(), lowerbound, upperbound,
// aggr2, aggr2.toChars(), srclower, srcupper, wantCopy);
if (wantCopy)
{
// Currently overlapping for struct array is allowed.
// The order of elements processing depends on the overlapping.
// https://issues.dlang.org/show_bug.cgi?id=14024
assert(aggr2.op == TOK.arrayLiteral);
Expressions* oldelems = existingAE.elements;
Expressions* newelems = (cast(ArrayLiteralExp)aggr2).elements;
Type elemtype = aggregate.type.nextOf();
bool needsPostblit = e.e2.isLvalue();
if (aggregate == aggr2 && srclower < lowerbound && lowerbound < srcupper)
{
// reverse order
for (auto i = upperbound - lowerbound; 0 < i--;)
{
Expression oldelem = (*oldelems)[cast(size_t)(i + firstIndex)];
Expression newelem = (*newelems)[cast(size_t)(i + srclower)];
newelem = copyLiteral(newelem).copy();
newelem.type = elemtype;
if (needsPostblit)
{
if (Expression x = evaluatePostblit(istate, newelem))
return x;
}
if (Expression x = evaluateDtor(istate, oldelem))
return x;
(*oldelems)[cast(size_t)(lowerbound + i)] = newelem;
}
}
else
{
// normal order
for (auto i = 0; i < upperbound - lowerbound; i++)
{
Expression oldelem = (*oldelems)[cast(size_t)(i + firstIndex)];
Expression newelem = (*newelems)[cast(size_t)(i + srclower)];
newelem = copyLiteral(newelem).copy();
newelem.type = elemtype;
if (needsPostblit)
{
if (Expression x = evaluatePostblit(istate, newelem))
return x;
}
if (Expression x = evaluateDtor(istate, oldelem))
return x;
(*oldelems)[cast(size_t)(lowerbound + i)] = newelem;
}
}
//assert(0);
return newval; // oldval?
}
if (aggregate == aggr2 &&
lowerbound < srcupper && srclower < upperbound)
{
e.error("overlapping slice assignment `[%llu..%llu] = [%llu..%llu]`",
ulong(lowerbound), ulong(upperbound), ulong(srclower), ulong(srcupper));
return CTFEExp.cantexp;
}
version (all) // todo: instead we can directly access to each elements of the slice
{
Expression orignewval = newval;
newval = resolveSlice(newval);
if (CTFEExp.isCantExp(newval))
{
e.error("CTFE internal error: slice `%s`", orignewval.toChars());
return CTFEExp.cantexp;
}
}
// no overlapping
//length?
assert(newval.op != TOK.slice);
}
if (newval.op == TOK.string_ && !isBlockAssignment)
{
/* Mixed slice: it was initialized as an array literal of chars/integers.
* Now a slice of it is being set with a string.
*/
sliceAssignArrayLiteralFromString(existingAE, cast(StringExp)newval, cast(size_t)firstIndex);
return newval;
}
if (newval.op == TOK.arrayLiteral && !isBlockAssignment)
{
Expressions* oldelems = existingAE.elements;
Expressions* newelems = (cast(ArrayLiteralExp)newval).elements;
Type elemtype = existingAE.type.nextOf();
bool needsPostblit = e.op != TOK.blit && e.e2.isLvalue();
foreach (j, newelem; *newelems)
{
newelem = paintTypeOntoLiteral(elemtype, newelem);
if (needsPostblit)
{
Expression x = evaluatePostblit(istate, newelem);
if (exceptionOrCantInterpret(x))
return x;
}
(*oldelems)[cast(size_t)(j + firstIndex)] = newelem;
}
return newval;
}
/* Block assignment, initialization of static arrays
* x[] = newval
* x may be a multidimensional static array. (Note that this
* only happens with array literals, never with strings).
*/
struct RecursiveBlock
{
InterState* istate;
Expression newval;
bool refCopy;
bool needsPostblit;
bool needsDtor;
extern (C++) Expression assignTo(ArrayLiteralExp ae)
{
return assignTo(ae, 0, ae.elements.dim);
}
extern (C++) Expression assignTo(ArrayLiteralExp ae, size_t lwr, size_t upr)
{
Expressions* w = ae.elements;
assert(ae.type.ty == Tsarray || ae.type.ty == Tarray);
bool directblk = (cast(TypeArray)ae.type).next.equivalent(newval.type);
for (size_t k = lwr; k < upr; k++)
{
if (!directblk && (*w)[k].op == TOK.arrayLiteral)
{
// Multidimensional array block assign
if (Expression ex = assignTo(cast(ArrayLiteralExp)(*w)[k]))
return ex;
}
else if (refCopy)
{
(*w)[k] = newval;
}
else if (!needsPostblit && !needsDtor)
{
assignInPlace((*w)[k], newval);
}
else
{
Expression oldelem = (*w)[k];
Expression tmpelem = needsDtor ? copyLiteral(oldelem).copy() : null;
assignInPlace(oldelem, newval);
if (needsPostblit)
{
if (Expression ex = evaluatePostblit(istate, oldelem))
return ex;
}
if (needsDtor)
{
// https://issues.dlang.org/show_bug.cgi?id=14860
if (Expression ex = evaluateDtor(istate, tmpelem))
return ex;
}
}
}
return null;
}
}
Type tn = newval.type.toBasetype();
bool wantRef = (tn.ty == Tarray || isAssocArray(tn) || tn.ty == Tclass);
bool cow = newval.op != TOK.structLiteral && newval.op != TOK.arrayLiteral && newval.op != TOK.string_;
Type tb = tn.baseElemOf();
StructDeclaration sd = (tb.ty == Tstruct ? (cast(TypeStruct)tb).sym : null);
RecursiveBlock rb;
rb.istate = istate;
rb.newval = newval;
rb.refCopy = wantRef || cow;
rb.needsPostblit = sd && sd.postblit && e.op != TOK.blit && e.e2.isLvalue();
rb.needsDtor = sd && sd.dtor && e.op == TOK.assign;
if (Expression ex = rb.assignTo(existingAE, cast(size_t)lowerbound, cast(size_t)upperbound))
return ex;
if (goal == ctfeNeedNothing)
return null; // avoid creating an unused literal
auto retslice = ctfeEmplaceExp!SliceExp(e.loc, existingAE,
ctfeEmplaceExp!IntegerExp(e.loc, firstIndex, Type.tsize_t),
ctfeEmplaceExp!IntegerExp(e.loc, firstIndex + upperbound - lowerbound, Type.tsize_t));
retslice.type = e.type;
return interpret(pue, retslice, istate);
}
e.error("slice operation `%s = %s` cannot be evaluated at compile time", e1.toChars(), newval.toChars());
return CTFEExp.cantexp;
}
override void visit(AssignExp e)
{
interpretAssignCommon(e, null);
}
override void visit(BinAssignExp e)
{
switch (e.op)
{
case TOK.addAssign:
interpretAssignCommon(e, &Add);
return;
case TOK.minAssign:
interpretAssignCommon(e, &Min);
return;
case TOK.concatenateAssign:
case TOK.concatenateElemAssign:
case TOK.concatenateDcharAssign:
interpretAssignCommon(e, &ctfeCat);
return;
case TOK.mulAssign:
interpretAssignCommon(e, &Mul);
return;
case TOK.divAssign:
interpretAssignCommon(e, &Div);
return;
case TOK.modAssign:
interpretAssignCommon(e, &Mod);
return;
case TOK.leftShiftAssign:
interpretAssignCommon(e, &Shl);
return;
case TOK.rightShiftAssign:
interpretAssignCommon(e, &Shr);
return;
case TOK.unsignedRightShiftAssign:
interpretAssignCommon(e, &Ushr);
return;
case TOK.andAssign:
interpretAssignCommon(e, &And);
return;
case TOK.orAssign:
interpretAssignCommon(e, &Or);
return;
case TOK.xorAssign:
interpretAssignCommon(e, &Xor);
return;
case TOK.powAssign:
interpretAssignCommon(e, &Pow);
return;
default:
assert(0);
}
}
override void visit(PostExp e)
{
debug (LOG)
{
printf("%s PostExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
if (e.op == TOK.plusPlus)
interpretAssignCommon(e, &Add, 1);
else
interpretAssignCommon(e, &Min, 1);
debug (LOG)
{
if (CTFEExp.isCantExp(result))
printf("PostExp::interpret() CANT\n");
}
}
/* Return 1 if e is a p1 > p2 or p1 >= p2 pointer comparison;
* -1 if e is a p1 < p2 or p1 <= p2 pointer comparison;
* 0 otherwise
*/
static int isPointerCmpExp(Expression e, Expression* p1, Expression* p2)
{
int ret = 1;
while (e.op == TOK.not)
{
ret *= -1;
e = (cast(NotExp)e).e1;
}
switch (e.op)
{
case TOK.lessThan:
case TOK.lessOrEqual:
ret *= -1;
goto case; /+ fall through +/
case TOK.greaterThan:
case TOK.greaterOrEqual:
*p1 = (cast(BinExp)e).e1;
*p2 = (cast(BinExp)e).e2;
if (!(isPointer((*p1).type) && isPointer((*p2).type)))
ret = 0;
break;
default:
ret = 0;
break;
}
return ret;
}
/** If this is a four pointer relation, evaluate it, else return NULL.
*
* This is an expression of the form (p1 > q1 && p2 < q2) or (p1 < q1 || p2 > q2)
* where p1, p2 are expressions yielding pointers to memory block p,
* and q1, q2 are expressions yielding pointers to memory block q.
* This expression is valid even if p and q are independent memory
* blocks and are therefore not normally comparable; the && form returns true
* if [p1..p2] lies inside [q1..q2], and false otherwise; the || form returns
* true if [p1..p2] lies outside [q1..q2], and false otherwise.
*
* Within the expression, any ordering of p1, p2, q1, q2 is permissible;
* the comparison operators can be any of >, <, <=, >=, provided that
* both directions (p > q and p < q) are checked. Additionally the
* relational sub-expressions can be negated, eg
* (!(q1 < p1) && p2 <= q2) is valid.
*/
private void interpretFourPointerRelation(UnionExp* pue, BinExp e)
{
assert(e.op == TOK.andAnd || e.op == TOK.orOr);
/* It can only be an isInside expression, if both e1 and e2 are
* directional pointer comparisons.
* Note that this check can be made statically; it does not depends on
* any runtime values. This allows a JIT implementation to compile a
* special AndAndPossiblyInside, keeping the normal AndAnd case efficient.
*/
// Save the pointer expressions and the comparison directions,
// so we can use them later.
Expression p1 = null;
Expression p2 = null;
Expression p3 = null;
Expression p4 = null;
int dir1 = isPointerCmpExp(e.e1, &p1, &p2);
int dir2 = isPointerCmpExp(e.e2, &p3, &p4);
if (dir1 == 0 || dir2 == 0)
{
result = null;
return;
}
//printf("FourPointerRelation %s\n", toChars());
UnionExp ue1 = void;
UnionExp ue2 = void;
UnionExp ue3 = void;
UnionExp ue4 = void;
// Evaluate the first two pointers
p1 = interpret(&ue1, p1, istate);
if (exceptionOrCant(p1))
return;
p2 = interpret(&ue2, p2, istate);
if (exceptionOrCant(p2))
return;
dinteger_t ofs1, ofs2;
Expression agg1 = getAggregateFromPointer(p1, &ofs1);
Expression agg2 = getAggregateFromPointer(p2, &ofs2);
if (!pointToSameMemoryBlock(agg1, agg2) && agg1.op != TOK.null_ && agg2.op != TOK.null_)
{
// Here it is either CANT_INTERPRET,
// or an IsInside comparison returning false.
p3 = interpret(&ue3, p3, istate);
if (CTFEExp.isCantExp(p3))
return;
// Note that it is NOT legal for it to throw an exception!
Expression except = null;
if (exceptionOrCantInterpret(p3))
except = p3;
else
{
p4 = interpret(&ue4, p4, istate);
if (CTFEExp.isCantExp(p4))
{
result = p4;
return;
}
if (exceptionOrCantInterpret(p4))
except = p4;
}
if (except)
{
e.error("comparison `%s` of pointers to unrelated memory blocks remains indeterminate at compile time because exception `%s` was thrown while evaluating `%s`", e.e1.toChars(), except.toChars(), e.e2.toChars());
result = CTFEExp.cantexp;
return;
}
dinteger_t ofs3, ofs4;
Expression agg3 = getAggregateFromPointer(p3, &ofs3);
Expression agg4 = getAggregateFromPointer(p4, &ofs4);
// The valid cases are:
// p1 > p2 && p3 > p4 (same direction, also for < && <)
// p1 > p2 && p3 < p4 (different direction, also < && >)
// Changing any > into >= doesn't affect the result
if ((dir1 == dir2 && pointToSameMemoryBlock(agg1, agg4) && pointToSameMemoryBlock(agg2, agg3)) ||
(dir1 != dir2 && pointToSameMemoryBlock(agg1, agg3) && pointToSameMemoryBlock(agg2, agg4)))
{
// it's a legal two-sided comparison
emplaceExp!(IntegerExp)(pue, e.loc, (e.op == TOK.andAnd) ? 0 : 1, e.type);
result = pue.exp();
return;
}
// It's an invalid four-pointer comparison. Either the second
// comparison is in the same direction as the first, or else
// more than two memory blocks are involved (either two independent
// invalid comparisons are present, or else agg3 == agg4).
e.error("comparison `%s` of pointers to unrelated memory blocks is indeterminate at compile time, even when combined with `%s`.", e.e1.toChars(), e.e2.toChars());
result = CTFEExp.cantexp;
return;
}
// The first pointer expression didn't need special treatment, so we
// we need to interpret the entire expression exactly as a normal && or ||.
// This is easy because we haven't evaluated e2 at all yet, and we already
// know it will return a bool.
// But we mustn't evaluate the pointer expressions in e1 again, in case
// they have side-effects.
bool nott = false;
Expression ex = e.e1;
while (1)
{
if (auto ne = ex.isNotExp())
{
nott = !nott;
ex = ne.e1;
}
else
break;
}
/** Negate relational operator, eg >= becomes <
* Params:
* op = comparison operator to negate
* Returns:
* negate operator
*/
static TOK negateRelation(TOK op) pure
{
switch (op)
{
case TOK.greaterOrEqual: op = TOK.lessThan; break;
case TOK.greaterThan: op = TOK.lessOrEqual; break;
case TOK.lessOrEqual: op = TOK.greaterThan; break;
case TOK.lessThan: op = TOK.greaterOrEqual; break;
default: assert(0);
}
return op;
}
const TOK cmpop = nott ? negateRelation(ex.op) : ex.op;
const cmp = comparePointers(cmpop, agg1, ofs1, agg2, ofs2);
// We already know this is a valid comparison.
assert(cmp >= 0);
if (e.op == TOK.andAnd && cmp == 1 || e.op == TOK.orOr && cmp == 0)
{
result = interpret(pue, e.e2, istate);
return;
}
emplaceExp!(IntegerExp)(pue, e.loc, (e.op == TOK.andAnd) ? 0 : 1, e.type);
result = pue.exp();
}
override void visit(LogicalExp e)
{
debug (LOG)
{
printf("%s LogicalExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
// Check for an insidePointer expression, evaluate it if so
interpretFourPointerRelation(pue, e);
if (result)
return;
UnionExp ue1 = void;
result = interpret(&ue1, e.e1, istate);
if (exceptionOrCant(result))
return;
bool res;
const andand = e.op == TOK.andAnd;
if (andand ? result.isBool(false) : isTrueBool(result))
res = !andand;
else if (andand ? isTrueBool(result) : result.isBool(false))
{
UnionExp ue2 = void;
result = interpret(&ue2, e.e2, istate);
if (exceptionOrCant(result))
return;
if (result.op == TOK.voidExpression)
{
assert(e.type.ty == Tvoid);
result = null;
return;
}
if (result.isBool(false))
res = false;
else if (isTrueBool(result))
res = true;
else
{
e.error("`%s` does not evaluate to a `bool`", result.toChars());
result = CTFEExp.cantexp;
return;
}
}
else
{
e.error("`%s` cannot be interpreted as a `bool`", result.toChars());
result = CTFEExp.cantexp;
return;
}
if (goal != ctfeNeedNothing)
{
if (e.type.equals(Type.tbool))
result = IntegerExp.createBool(res);
else
{
emplaceExp!(IntegerExp)(pue, e.loc, res, e.type);
result = pue.exp();
}
}
}
// Print a stack trace, starting from callingExp which called fd.
// To shorten the stack trace, try to detect recursion.
private void showCtfeBackTrace(CallExp callingExp, FuncDeclaration fd)
{
if (ctfeGlobals.stackTraceCallsToSuppress > 0)
{
--ctfeGlobals.stackTraceCallsToSuppress;
return;
}
errorSupplemental(callingExp.loc, "called from here: `%s`", callingExp.toChars());
// Quit if it's not worth trying to compress the stack trace
if (ctfeGlobals.callDepth < 6 || global.params.verbose)
return;
// Recursion happens if the current function already exists in the call stack.
int numToSuppress = 0;
int recurseCount = 0;
int depthSoFar = 0;
InterState* lastRecurse = istate;
for (InterState* cur = istate; cur; cur = cur.caller)
{
if (cur.fd == fd)
{
++recurseCount;
numToSuppress = depthSoFar;
lastRecurse = cur;
}
++depthSoFar;
}
// We need at least three calls to the same function, to make compression worthwhile
if (recurseCount < 2)
return;
// We found a useful recursion. Print all the calls involved in the recursion
errorSupplemental(fd.loc, "%d recursive calls to function `%s`", recurseCount, fd.toChars());
for (InterState* cur = istate; cur.fd != fd; cur = cur.caller)
{
errorSupplemental(cur.fd.loc, "recursively called from function `%s`", cur.fd.toChars());
}
// We probably didn't enter the recursion in this function.
// Go deeper to find the real beginning.
InterState* cur = istate;
while (lastRecurse.caller && cur.fd == lastRecurse.caller.fd)
{
cur = cur.caller;
lastRecurse = lastRecurse.caller;
++numToSuppress;
}
ctfeGlobals.stackTraceCallsToSuppress = numToSuppress;
}
override void visit(CallExp e)
{
debug (LOG)
{
printf("%s CallExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
Expression pthis = null;
FuncDeclaration fd = null;
Expression ecall = interpretRegion(e.e1, istate);
if (exceptionOrCant(ecall))
return;
if (auto dve = ecall.isDotVarExp())
{
// Calling a member function
pthis = dve.e1;
fd = dve.var.isFuncDeclaration();
assert(fd);
if (auto dte = pthis.isDotTypeExp())
pthis = dte.e1;
}
else if (auto ve = ecall.isVarExp())
{
fd = ve.var.isFuncDeclaration();
assert(fd);
// If `_d_HookTraceImpl` is found, resolve the underlying hook and replace `e` and `fd` with it.
removeHookTraceImpl(e, fd);
if (fd.ident == Id.__ArrayPostblit || fd.ident == Id.__ArrayDtor)
{
assert(e.arguments.dim == 1);
Expression ea = (*e.arguments)[0];
// printf("1 ea = %s %s\n", ea.type.toChars(), ea.toChars());
if (auto se = ea.isSliceExp())
ea = se.e1;
if (auto ce = ea.isCastExp())
ea = ce.e1;
// printf("2 ea = %s, %s %s\n", ea.type.toChars(), Token.toChars(ea.op), ea.toChars());
if (ea.op == TOK.variable || ea.op == TOK.symbolOffset)
result = getVarExp(e.loc, istate, (cast(SymbolExp)ea).var, ctfeNeedRvalue);
else if (auto ae = ea.isAddrExp())
result = interpretRegion(ae.e1, istate);
// https://issues.dlang.org/show_bug.cgi?id=18871
// https://issues.dlang.org/show_bug.cgi?id=18819
else if (auto ale = ea.isArrayLiteralExp())
result = interpretRegion(ale, istate);
else
assert(0);
if (CTFEExp.isCantExp(result))
return;
if (fd.ident == Id.__ArrayPostblit)
result = evaluatePostblit(istate, result);
else
result = evaluateDtor(istate, result);
if (!result)
result = CTFEExp.voidexp;
return;
}
else if (fd.ident == Id._d_arraysetlengthT)
{
// In expressionsem.d `ea.length = eb;` got lowered to `_d_arraysetlengthT(ea, eb);`.
// The following code will rewrite it back to `ea.length = eb` and then interpret that expression.
assert(e.arguments.dim == 2);
Expression ea = (*e.arguments)[0];
Expression eb = (*e.arguments)[1];
auto ale = ctfeEmplaceExp!ArrayLengthExp(e.loc, ea);
ale.type = Type.tsize_t;
AssignExp ae = ctfeEmplaceExp!AssignExp(e.loc, ale, eb);
ae.type = ea.type;
// if (global.params.verbose)
// message("interpret %s =>\n %s", e.toChars(), ae.toChars());
result = interpretRegion(ae, istate);
return;
}
}
else if (auto soe = ecall.isSymOffExp())
{
fd = soe.var.isFuncDeclaration();
assert(fd && soe.offset == 0);
}
else if (auto de = ecall.isDelegateExp())
{
// Calling a delegate
fd = de.func;
pthis = de.e1;
// Special handling for: &nestedfunc --> DelegateExp(VarExp(nestedfunc), nestedfunc)
if (auto ve = pthis.isVarExp())
if (ve.var == fd)
pthis = null; // context is not necessary for CTFE
}
else if (auto fe = ecall.isFuncExp())
{
// Calling a delegate literal
fd = fe.fd;
}
else
{
// delegate.funcptr()
// others
e.error("cannot call `%s` at compile time", e.toChars());
result = CTFEExp.cantexp;
return;
}
if (!fd)
{
e.error("CTFE internal error: cannot evaluate `%s` at compile time", e.toChars());
result = CTFEExp.cantexp;
return;
}
if (pthis)
{
// Member function call
// Currently this is satisfied because closure is not yet supported.
assert(!fd.isNested() || fd.needThis());
if (pthis.op == TOK.typeid_)
{
pthis.error("static variable `%s` cannot be read at compile time", pthis.toChars());
result = CTFEExp.cantexp;
return;
}
assert(pthis);
if (pthis.op == TOK.null_)
{
assert(pthis.type.toBasetype().ty == Tclass);
e.error("function call through null class reference `%s`", pthis.toChars());
result = CTFEExp.cantexp;
return;
}
assert(pthis.op == TOK.structLiteral || pthis.op == TOK.classReference || pthis.op == TOK.type);
if (fd.isVirtual() && !e.directcall)
{
// Make a virtual function call.
// Get the function from the vtable of the original class
assert(pthis.op == TOK.classReference);
ClassDeclaration cd = (cast(ClassReferenceExp)pthis).originalClass();
// We can't just use the vtable index to look it up, because
// vtables for interfaces don't get populated until the glue layer.
fd = cd.findFunc(fd.ident, cast(TypeFunction)fd.type);
assert(fd);
}
}
if (fd && fd.semanticRun >= PASS.semantic3done && fd.semantic3Errors)
{
e.error("CTFE failed because of previous errors in `%s`", fd.toChars());
result = CTFEExp.cantexp;
return;
}
// Check for built-in functions
result = evaluateIfBuiltin(pue, istate, e.loc, fd, e.arguments, pthis);
if (result)
return;
if (!fd.fbody)
{
e.error("`%s` cannot be interpreted at compile time, because it has no available source code", fd.toChars());
result = CTFEExp.showcontext;
return;
}
result = interpretFunction(pue, fd, istate, e.arguments, pthis);
if (result.op == TOK.voidExpression)
return;
if (!exceptionOrCantInterpret(result))
{
if (goal != ctfeNeedLvalue) // Peel off CTFE reference if it's unnecessary
{
if (result == pue.exp())
result = pue.copy();
result = interpret(pue, result, istate);
}
}
if (!exceptionOrCantInterpret(result))
{
result = paintTypeOntoLiteral(pue, e.type, result);
result.loc = e.loc;
}
else if (CTFEExp.isCantExp(result) && !global.gag)
showCtfeBackTrace(e, fd); // Print a stack trace.
}
override void visit(CommaExp e)
{
debug (LOG)
{
printf("%s CommaExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
// If it creates a variable, and there's no context for
// the variable to be created in, we need to create one now.
InterState istateComma;
if (!istate && firstComma(e.e1).op == TOK.declaration)
{
ctfeGlobals.stack.startFrame(null);
istate = &istateComma;
}
void endTempStackFrame()
{
// If we created a temporary stack frame, end it now.
if (istate == &istateComma)
ctfeGlobals.stack.endFrame();
}
result = CTFEExp.cantexp;
// If the comma returns a temporary variable, it needs to be an lvalue
// (this is particularly important for struct constructors)
if (e.e1.op == TOK.declaration &&
e.e2.op == TOK.variable &&
(cast(DeclarationExp)e.e1).declaration == (cast(VarExp)e.e2).var &&
(cast(VarExp)e.e2).var.storage_class & STC.ctfe)
{
VarExp ve = cast(VarExp)e.e2;
VarDeclaration v = ve.var.isVarDeclaration();
ctfeGlobals.stack.push(v);
if (!v._init && !getValue(v))
{
setValue(v, copyLiteral(v.type.defaultInitLiteral(e.loc)).copy());
}
if (!getValue(v))
{
Expression newval = v._init.initializerToExpression();
// Bug 4027. Copy constructors are a weird case where the
// initializer is a void function (the variable is modified
// through a reference parameter instead).
newval = interpretRegion(newval, istate);
if (exceptionOrCant(newval))
return endTempStackFrame();
if (newval.op != TOK.voidExpression)
{
// v isn't necessarily null.
setValueWithoutChecking(v, copyLiteral(newval).copy());
}
}
}
else
{
UnionExp ue = void;
auto e1 = interpret(&ue, e.e1, istate, ctfeNeedNothing);
if (exceptionOrCant(e1))
return endTempStackFrame();
}
result = interpret(pue, e.e2, istate, goal);
return endTempStackFrame();
}
override void visit(CondExp e)
{
debug (LOG)
{
printf("%s CondExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
UnionExp uecond = void;
Expression econd;
econd = interpret(&uecond, e.econd, istate);
if (exceptionOrCant(econd))
return;
if (isPointer(e.econd.type))
{
if (econd.op != TOK.null_)
{
econd = IntegerExp.createBool(true);
}
}
if (isTrueBool(econd))
result = interpret(pue, e.e1, istate, goal);
else if (econd.isBool(false))
result = interpret(pue, e.e2, istate, goal);
else
{
e.error("`%s` does not evaluate to boolean result at compile time", e.econd.toChars());
result = CTFEExp.cantexp;
}
}
override void visit(ArrayLengthExp e)
{
debug (LOG)
{
printf("%s ArrayLengthExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
UnionExp ue1;
Expression e1 = interpret(&ue1, e.e1, istate);
assert(e1);
if (exceptionOrCant(e1))
return;
if (e1.op != TOK.string_ && e1.op != TOK.arrayLiteral && e1.op != TOK.slice && e1.op != TOK.null_)
{
e.error("`%s` cannot be evaluated at compile time", e.toChars());
result = CTFEExp.cantexp;
return;
}
emplaceExp!(IntegerExp)(pue, e.loc, resolveArrayLength(e1), e.type);
result = pue.exp();
}
/**
* Interpret the vector expression as an array literal.
* Params:
* pue = non-null pointer to temporary storage that can be used to store the return value
* e = Expression to interpret
* Returns:
* resulting array literal or 'e' if unable to interpret
*/
static Expression interpretVectorToArray(UnionExp* pue, VectorExp e)
{
if (auto ale = e.e1.isArrayLiteralExp())
return ale;
if (e.e1.op == TOK.int64 || e.e1.op == TOK.float64)
{
// Convert literal __vector(int) -> __vector([array])
auto elements = new Expressions(e.dim);
foreach (ref element; *elements)
element = copyLiteral(e.e1).copy();
auto type = (e.type.ty == Tvector) ? e.type.isTypeVector().basetype : e.type.isTypeSArray();
assert(type);
emplaceExp!(ArrayLiteralExp)(pue, e.loc, type, elements);
auto ale = cast(ArrayLiteralExp)pue.exp();
ale.ownedByCtfe = OwnedBy.ctfe;
return ale;
}
return e;
}
override void visit(VectorExp e)
{
debug (LOG)
{
printf("%s VectorExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
if (e.ownedByCtfe >= OwnedBy.ctfe) // We've already interpreted all the elements
{
result = e;
return;
}
Expression e1 = interpret(pue, e.e1, istate);
assert(e1);
if (exceptionOrCant(e1))
return;
if (e1.op != TOK.arrayLiteral && e1.op != TOK.int64 && e1.op != TOK.float64)
{
e.error("`%s` cannot be evaluated at compile time", e.toChars());
result = CTFEExp.cantexp;
return;
}
if (e1 == pue.exp())
e1 = pue.copy();
emplaceExp!(VectorExp)(pue, e.loc, e1, e.to);
auto ve = cast(VectorExp)pue.exp();
ve.type = e.type;
ve.dim = e.dim;
ve.ownedByCtfe = OwnedBy.ctfe;
result = ve;
}
override void visit(VectorArrayExp e)
{
debug (LOG)
{
printf("%s VectorArrayExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
Expression e1 = interpret(pue, e.e1, istate);
assert(e1);
if (exceptionOrCant(e1))
return;
if (auto ve = e1.isVectorExp())
{
result = interpretVectorToArray(pue, ve);
if (result.op != TOK.vector)
return;
}
e.error("`%s` cannot be evaluated at compile time", e.toChars());
result = CTFEExp.cantexp;
}
override void visit(DelegatePtrExp e)
{
debug (LOG)
{
printf("%s DelegatePtrExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
Expression e1 = interpret(pue, e.e1, istate);
assert(e1);
if (exceptionOrCant(e1))
return;
e.error("`%s` cannot be evaluated at compile time", e.toChars());
result = CTFEExp.cantexp;
}
override void visit(DelegateFuncptrExp e)
{
debug (LOG)
{
printf("%s DelegateFuncptrExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
Expression e1 = interpret(pue, e.e1, istate);
assert(e1);
if (exceptionOrCant(e1))
return;
e.error("`%s` cannot be evaluated at compile time", e.toChars());
result = CTFEExp.cantexp;
}
static bool resolveIndexing(IndexExp e, InterState* istate, Expression* pagg, uinteger_t* pidx, bool modify)
{
assert(e.e1.type.toBasetype().ty != Taarray);
if (e.e1.type.toBasetype().ty == Tpointer)
{
// Indexing a pointer. Note that there is no $ in this case.
Expression e1 = interpretRegion(e.e1, istate);
if (exceptionOrCantInterpret(e1))
return false;
Expression e2 = interpretRegion(e.e2, istate);
if (exceptionOrCantInterpret(e2))
return false;
sinteger_t indx = e2.toInteger();
dinteger_t ofs;
Expression agg = getAggregateFromPointer(e1, &ofs);
if (agg.op == TOK.null_)
{
e.error("cannot index through null pointer `%s`", e.e1.toChars());
return false;
}
if (agg.op == TOK.int64)
{
e.error("cannot index through invalid pointer `%s` of value `%s`", e.e1.toChars(), e1.toChars());
return false;
}
// Pointer to a non-array variable
if (agg.op == TOK.symbolOffset)
{
e.error("mutable variable `%s` cannot be %s at compile time, even through a pointer", cast(char*)(modify ? "modified" : "read"), (cast(SymOffExp)agg).var.toChars());
return false;
}
if (agg.op == TOK.arrayLiteral || agg.op == TOK.string_)
{
dinteger_t len = resolveArrayLength(agg);
if (ofs + indx >= len)
{
e.error("pointer index `[%lld]` exceeds allocated memory block `[0..%lld]`", ofs + indx, len);
return false;
}
}
else
{
if (ofs + indx != 0)
{
e.error("pointer index `[%lld]` lies outside memory block `[0..1]`", ofs + indx);
return false;
}
}
*pagg = agg;
*pidx = ofs + indx;
return true;
}
Expression e1 = interpretRegion(e.e1, istate);
if (exceptionOrCantInterpret(e1))
return false;
if (e1.op == TOK.null_)
{
e.error("cannot index null array `%s`", e.e1.toChars());
return false;
}
if (auto ve = e1.isVectorExp())
{
UnionExp ue = void;
e1 = interpretVectorToArray(&ue, ve);
e1 = (e1 == ue.exp()) ? ue.copy() : e1;
}
// Set the $ variable, and find the array literal to modify
dinteger_t len;
if (e1.op == TOK.variable && e1.type.toBasetype().ty == Tsarray)
len = e1.type.toBasetype().isTypeSArray().dim.toInteger();
else
{
if (e1.op != TOK.arrayLiteral && e1.op != TOK.string_ && e1.op != TOK.slice && e1.op != TOK.vector)
{
e.error("cannot determine length of `%s` at compile time", e.e1.toChars());
return false;
}
len = resolveArrayLength(e1);
}
if (e.lengthVar)
{
Expression dollarExp = ctfeEmplaceExp!IntegerExp(e.loc, len, Type.tsize_t);
ctfeGlobals.stack.push(e.lengthVar);
setValue(e.lengthVar, dollarExp);
}
Expression e2 = interpretRegion(e.e2, istate);
if (e.lengthVar)
ctfeGlobals.stack.pop(e.lengthVar); // $ is defined only inside []
if (exceptionOrCantInterpret(e2))
return false;
if (e2.op != TOK.int64)
{
e.error("CTFE internal error: non-integral index `[%s]`", e.e2.toChars());
return false;
}
if (auto se = e1.isSliceExp())
{
// Simplify index of slice: agg[lwr..upr][indx] --> agg[indx']
uinteger_t index = e2.toInteger();
uinteger_t ilwr = se.lwr.toInteger();
uinteger_t iupr = se.upr.toInteger();
if (index > iupr - ilwr)
{
e.error("index %llu exceeds array length %llu", index, iupr - ilwr);
return false;
}
*pagg = (cast(SliceExp)e1).e1;
*pidx = index + ilwr;
}
else
{
*pagg = e1;
*pidx = e2.toInteger();
if (len <= *pidx)
{
e.error("array index %lld is out of bounds `[0..%lld]`", *pidx, len);
return false;
}
}
return true;
}
override void visit(IndexExp e)
{
debug (LOG)
{
printf("%s IndexExp::interpret() %s, goal = %d\n", e.loc.toChars(), e.toChars(), goal);
}
if (e.e1.type.toBasetype().ty == Tpointer)
{
Expression agg;
uinteger_t indexToAccess;
if (!resolveIndexing(e, istate, &agg, &indexToAccess, false))
{
result = CTFEExp.cantexp;
return;
}
if (agg.op == TOK.arrayLiteral || agg.op == TOK.string_)
{
if (goal == ctfeNeedLvalue)
{
// if we need a reference, IndexExp shouldn't be interpreting
// the expression to a value, it should stay as a reference
emplaceExp!(IndexExp)(pue, e.loc, agg, ctfeEmplaceExp!IntegerExp(e.e2.loc, indexToAccess, e.e2.type));
result = pue.exp();
result.type = e.type;
return;
}
result = ctfeIndex(pue, e.loc, e.type, agg, indexToAccess);
return;
}
else
{
assert(indexToAccess == 0);
result = interpretRegion(agg, istate, goal);
if (exceptionOrCant(result))
return;
result = paintTypeOntoLiteral(pue, e.type, result);
return;
}
}
if (e.e1.type.toBasetype().ty == Taarray)
{
Expression e1 = interpretRegion(e.e1, istate);
if (exceptionOrCant(e1))
return;
if (e1.op == TOK.null_)
{
if (goal == ctfeNeedLvalue && e1.type.ty == Taarray && e.modifiable)
{
assert(0); // does not reach here?
}
e.error("cannot index null array `%s`", e.e1.toChars());
result = CTFEExp.cantexp;
return;
}
Expression e2 = interpretRegion(e.e2, istate);
if (exceptionOrCant(e2))
return;
if (goal == ctfeNeedLvalue)
{
// Pointer or reference of a scalar type
if (e1 == e.e1 && e2 == e.e2)
result = e;
else
{
emplaceExp!(IndexExp)(pue, e.loc, e1, e2);
result = pue.exp();
result.type = e.type;
}
return;
}
assert(e1.op == TOK.assocArrayLiteral);
UnionExp e2tmp = void;
e2 = resolveSlice(e2, &e2tmp);
result = findKeyInAA(e.loc, cast(AssocArrayLiteralExp)e1, e2);
if (!result)
{
e.error("key `%s` not found in associative array `%s`", e2.toChars(), e.e1.toChars());
result = CTFEExp.cantexp;
}
return;
}
Expression agg;
uinteger_t indexToAccess;
if (!resolveIndexing(e, istate, &agg, &indexToAccess, false))
{
result = CTFEExp.cantexp;
return;
}
if (goal == ctfeNeedLvalue)
{
Expression e2 = ctfeEmplaceExp!IntegerExp(e.e2.loc, indexToAccess, Type.tsize_t);
emplaceExp!(IndexExp)(pue, e.loc, agg, e2);
result = pue.exp();
result.type = e.type;
return;
}
result = ctfeIndex(pue, e.loc, e.type, agg, indexToAccess);
if (exceptionOrCant(result))
return;
if (result.op == TOK.void_)
{
e.error("`%s` is used before initialized", e.toChars());
errorSupplemental(result.loc, "originally uninitialized here");
result = CTFEExp.cantexp;
return;
}
if (result == pue.exp())
result = result.copy();
}
override void visit(SliceExp e)
{
debug (LOG)
{
printf("%s SliceExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
if (e.e1.type.toBasetype().ty == Tpointer)
{
// Slicing a pointer. Note that there is no $ in this case.
Expression e1 = interpretRegion(e.e1, istate);
if (exceptionOrCant(e1))
return;
if (e1.op == TOK.int64)
{
e.error("cannot slice invalid pointer `%s` of value `%s`", e.e1.toChars(), e1.toChars());
result = CTFEExp.cantexp;
return;
}
/* Evaluate lower and upper bounds of slice
*/
Expression lwr = interpretRegion(e.lwr, istate);
if (exceptionOrCant(lwr))
return;
Expression upr = interpretRegion(e.upr, istate);
if (exceptionOrCant(upr))
return;
uinteger_t ilwr = lwr.toInteger();
uinteger_t iupr = upr.toInteger();
dinteger_t ofs;
Expression agg = getAggregateFromPointer(e1, &ofs);
ilwr += ofs;
iupr += ofs;
if (agg.op == TOK.null_)
{
if (iupr == ilwr)
{
result = ctfeEmplaceExp!NullExp(e.loc);
result.type = e.type;
return;
}
e.error("cannot slice null pointer `%s`", e.e1.toChars());
result = CTFEExp.cantexp;
return;
}
if (agg.op == TOK.symbolOffset)
{
e.error("slicing pointers to static variables is not supported in CTFE");
result = CTFEExp.cantexp;
return;
}
if (agg.op != TOK.arrayLiteral && agg.op != TOK.string_)
{
e.error("pointer `%s` cannot be sliced at compile time (it does not point to an array)", e.e1.toChars());
result = CTFEExp.cantexp;
return;
}
assert(agg.op == TOK.arrayLiteral || agg.op == TOK.string_);
dinteger_t len = ArrayLength(Type.tsize_t, agg).exp().toInteger();
//Type *pointee = ((TypePointer *)agg.type)->next;
if (iupr > (len + 1) || iupr < ilwr)
{
e.error("pointer slice `[%lld..%lld]` exceeds allocated memory block `[0..%lld]`", ilwr, iupr, len);
result = CTFEExp.cantexp;
return;
}
if (ofs != 0)
{
lwr = ctfeEmplaceExp!IntegerExp(e.loc, ilwr, lwr.type);
upr = ctfeEmplaceExp!IntegerExp(e.loc, iupr, upr.type);
}
emplaceExp!(SliceExp)(pue, e.loc, agg, lwr, upr);
result = pue.exp();
result.type = e.type;
return;
}
CtfeGoal goal1 = ctfeNeedRvalue;
if (goal == ctfeNeedLvalue)
{
if (e.e1.type.toBasetype().ty == Tsarray)
if (auto ve = e.e1.isVarExp())
if (auto vd = ve.var.isVarDeclaration())
if (vd.storage_class & STC.ref_)
goal1 = ctfeNeedLvalue;
}
Expression e1 = interpret(e.e1, istate, goal1);
if (exceptionOrCant(e1))
return;
if (!e.lwr)
{
result = paintTypeOntoLiteral(pue, e.type, e1);
return;
}
if (auto ve = e1.isVectorExp())
{
e1 = interpretVectorToArray(pue, ve);
e1 = (e1 == pue.exp()) ? pue.copy() : e1;
}
/* Set dollar to the length of the array
*/
uinteger_t dollar;
if ((e1.op == TOK.variable || e1.op == TOK.dotVariable) && e1.type.toBasetype().ty == Tsarray)
dollar = e1.type.toBasetype().isTypeSArray().dim.toInteger();
else
{
if (e1.op != TOK.arrayLiteral && e1.op != TOK.string_ && e1.op != TOK.null_ && e1.op != TOK.slice && e1.op != TOK.vector)
{
e.error("cannot determine length of `%s` at compile time", e1.toChars());
result = CTFEExp.cantexp;
return;
}
dollar = resolveArrayLength(e1);
}
/* Set the $ variable
*/
if (e.lengthVar)
{
auto dollarExp = ctfeEmplaceExp!IntegerExp(e.loc, dollar, Type.tsize_t);
ctfeGlobals.stack.push(e.lengthVar);
setValue(e.lengthVar, dollarExp);
}
/* Evaluate lower and upper bounds of slice
*/
Expression lwr = interpretRegion(e.lwr, istate);
if (exceptionOrCant(lwr))
{
if (e.lengthVar)
ctfeGlobals.stack.pop(e.lengthVar);
return;
}
Expression upr = interpretRegion(e.upr, istate);
if (exceptionOrCant(upr))
{
if (e.lengthVar)
ctfeGlobals.stack.pop(e.lengthVar);
return;
}
if (e.lengthVar)
ctfeGlobals.stack.pop(e.lengthVar); // $ is defined only inside [L..U]
uinteger_t ilwr = lwr.toInteger();
uinteger_t iupr = upr.toInteger();
if (e1.op == TOK.null_)
{
if (ilwr == 0 && iupr == 0)
{
result = e1;
return;
}
e1.error("slice `[%llu..%llu]` is out of bounds", ilwr, iupr);
result = CTFEExp.cantexp;
return;
}
if (auto se = e1.isSliceExp())
{
// Simplify slice of slice:
// aggregate[lo1..up1][lwr..upr] ---> aggregate[lwr'..upr']
uinteger_t lo1 = se.lwr.toInteger();
uinteger_t up1 = se.upr.toInteger();
if (ilwr > iupr || iupr > up1 - lo1)
{
e.error("slice `[%llu..%llu]` exceeds array bounds `[%llu..%llu]`", ilwr, iupr, lo1, up1);
result = CTFEExp.cantexp;
return;
}
ilwr += lo1;
iupr += lo1;
emplaceExp!(SliceExp)(pue, e.loc, se.e1,
ctfeEmplaceExp!IntegerExp(e.loc, ilwr, lwr.type),
ctfeEmplaceExp!IntegerExp(e.loc, iupr, upr.type));
result = pue.exp();
result.type = e.type;
return;
}
if (e1.op == TOK.arrayLiteral || e1.op == TOK.string_)
{
if (iupr < ilwr || dollar < iupr)
{
e.error("slice `[%lld..%lld]` exceeds array bounds `[0..%lld]`", ilwr, iupr, dollar);
result = CTFEExp.cantexp;
return;
}
}
emplaceExp!(SliceExp)(pue, e.loc, e1, lwr, upr);
result = pue.exp();
result.type = e.type;
}
override void visit(InExp e)
{
debug (LOG)
{
printf("%s InExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
Expression e1 = interpretRegion(e.e1, istate);
if (exceptionOrCant(e1))
return;
Expression e2 = interpretRegion(e.e2, istate);
if (exceptionOrCant(e2))
return;
if (e2.op == TOK.null_)
{
emplaceExp!(NullExp)(pue, e.loc, e.type);
result = pue.exp();
return;
}
if (e2.op != TOK.assocArrayLiteral)
{
e.error("`%s` cannot be interpreted at compile time", e.toChars());
result = CTFEExp.cantexp;
return;
}
e1 = resolveSlice(e1);
result = findKeyInAA(e.loc, cast(AssocArrayLiteralExp)e2, e1);
if (exceptionOrCant(result))
return;
if (!result)
{
emplaceExp!(NullExp)(pue, e.loc, e.type);
result = pue.exp();
}
else
{
// Create a CTFE pointer &aa[index]
result = ctfeEmplaceExp!IndexExp(e.loc, e2, e1);
result.type = e.type.nextOf();
emplaceExp!(AddrExp)(pue, e.loc, result, e.type);
result = pue.exp();
}
}
override void visit(CatExp e)
{
debug (LOG)
{
printf("%s CatExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
UnionExp ue1 = void;
Expression e1 = interpret(&ue1, e.e1, istate);
if (exceptionOrCant(e1))
return;
UnionExp ue2 = void;
Expression e2 = interpret(&ue2, e.e2, istate);
if (exceptionOrCant(e2))
return;
UnionExp e1tmp = void;
e1 = resolveSlice(e1, &e1tmp);
UnionExp e2tmp = void;
e2 = resolveSlice(e2, &e2tmp);
/* e1 and e2 can't go on the stack because of x~[y] and [x]~y will
* result in [x,y] and then x or y is on the stack.
* But if they are both strings, we can, because it isn't the x~[y] case.
*/
if (!(e1.op == TOK.string_ && e2.op == TOK.string_))
{
if (e1 == ue1.exp())
e1 = ue1.copy();
if (e2 == ue2.exp())
e2 = ue2.copy();
}
*pue = ctfeCat(e.loc, e.type, e1, e2);
result = pue.exp();
if (CTFEExp.isCantExp(result))
{
e.error("`%s` cannot be interpreted at compile time", e.toChars());
return;
}
// We know we still own it, because we interpreted both e1 and e2
if (auto ale = result.isArrayLiteralExp())
{
ale.ownedByCtfe = OwnedBy.ctfe;
// https://issues.dlang.org/show_bug.cgi?id=14686
foreach (elem; *ale.elements)
{
Expression ex = evaluatePostblit(istate, elem);
if (exceptionOrCant(ex))
return;
}
}
else if (auto se = result.isStringExp())
se.ownedByCtfe = OwnedBy.ctfe;
}
override void visit(DeleteExp e)
{
debug (LOG)
{
printf("%s DeleteExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
result = interpretRegion(e.e1, istate);
if (exceptionOrCant(result))
return;
if (result.op == TOK.null_)
{
result = CTFEExp.voidexp;
return;
}
auto tb = e.e1.type.toBasetype();
switch (tb.ty)
{
case Tclass:
if (result.op != TOK.classReference)
{
e.error("`delete` on invalid class reference `%s`", result.toChars());
result = CTFEExp.cantexp;
return;
}
auto cre = cast(ClassReferenceExp)result;
auto cd = cre.originalClass();
if (cd.dtor)
{
result = interpretFunction(pue, cd.dtor, istate, null, cre);
if (exceptionOrCant(result))
return;
}
break;
case Tpointer:
tb = (cast(TypePointer)tb).next.toBasetype();
if (tb.ty == Tstruct)
{
if (result.op != TOK.address ||
(cast(AddrExp)result).e1.op != TOK.structLiteral)
{
e.error("`delete` on invalid struct pointer `%s`", result.toChars());
result = CTFEExp.cantexp;
return;
}
auto sd = (cast(TypeStruct)tb).sym;
auto sle = cast(StructLiteralExp)(cast(AddrExp)result).e1;
if (sd.dtor)
{
result = interpretFunction(pue, sd.dtor, istate, null, sle);
if (exceptionOrCant(result))
return;
}
}
break;
case Tarray:
auto tv = tb.nextOf().baseElemOf();
if (tv.ty == Tstruct)
{
if (result.op != TOK.arrayLiteral)
{
e.error("`delete` on invalid struct array `%s`", result.toChars());
result = CTFEExp.cantexp;
return;
}
auto sd = (cast(TypeStruct)tv).sym;
if (sd.dtor)
{
auto ale = cast(ArrayLiteralExp)result;
foreach (el; *ale.elements)
{
result = interpretFunction(pue, sd.dtor, istate, null, el);
if (exceptionOrCant(result))
return;
}
}
}
break;
default:
assert(0);
}
result = CTFEExp.voidexp;
}
override void visit(CastExp e)
{
debug (LOG)
{
printf("%s CastExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
Expression e1 = interpretRegion(e.e1, istate, goal);
if (exceptionOrCant(e1))
return;
// If the expression has been cast to void, do nothing.
if (e.to.ty == Tvoid)
{
result = CTFEExp.voidexp;
return;
}
if (e.to.ty == Tpointer && e1.op != TOK.null_)
{
Type pointee = (cast(TypePointer)e.type).next;
// Implement special cases of normally-unsafe casts
if (e1.op == TOK.int64)
{
// Happens with Windows HANDLEs, for example.
result = paintTypeOntoLiteral(pue, e.to, e1);
return;
}
bool castToSarrayPointer = false;
bool castBackFromVoid = false;
if (e1.type.ty == Tarray || e1.type.ty == Tsarray || e1.type.ty == Tpointer)
{
// Check for unsupported type painting operations
// For slices, we need the type being sliced,
// since it may have already been type painted
Type elemtype = e1.type.nextOf();
if (auto se = e1.isSliceExp())
elemtype = se.e1.type.nextOf();
// Allow casts from X* to void *, and X** to void** for any X.
// But don't allow cast from X* to void**.
// So, we strip all matching * from source and target to find X.
// Allow casts to X* from void* only if the 'void' was originally an X;
// we check this later on.
Type ultimatePointee = pointee;
Type ultimateSrc = elemtype;
while (ultimatePointee.ty == Tpointer && ultimateSrc.ty == Tpointer)
{
ultimatePointee = ultimatePointee.nextOf();
ultimateSrc = ultimateSrc.nextOf();
}
if (ultimatePointee.ty == Tsarray && ultimatePointee.nextOf().equivalent(ultimateSrc))
{
castToSarrayPointer = true;
}
else if (ultimatePointee.ty != Tvoid && ultimateSrc.ty != Tvoid && !isSafePointerCast(elemtype, pointee))
{
e.error("reinterpreting cast from `%s*` to `%s*` is not supported in CTFE", elemtype.toChars(), pointee.toChars());
result = CTFEExp.cantexp;
return;
}
if (ultimateSrc.ty == Tvoid)
castBackFromVoid = true;
}
if (auto se = e1.isSliceExp())
{
if (se.e1.op == TOK.null_)
{
result = paintTypeOntoLiteral(pue, e.type, se.e1);
return;
}
// Create a CTFE pointer &aggregate[1..2]
auto ei = ctfeEmplaceExp!IndexExp(e.loc, se.e1, se.lwr);
ei.type = e.type.nextOf();
emplaceExp!(AddrExp)(pue, e.loc, ei, e.type);
result = pue.exp();
return;
}
if (e1.op == TOK.arrayLiteral || e1.op == TOK.string_)
{
// Create a CTFE pointer &[1,2,3][0] or &"abc"[0]
auto ei = ctfeEmplaceExp!IndexExp(e.loc, e1, ctfeEmplaceExp!IntegerExp(e.loc, 0, Type.tsize_t));
ei.type = e.type.nextOf();
emplaceExp!(AddrExp)(pue, e.loc, ei, e.type);
result = pue.exp();
return;
}
if (e1.op == TOK.index && !(cast(IndexExp)e1).e1.type.equals(e1.type))
{
// type painting operation
IndexExp ie = cast(IndexExp)e1;
if (castBackFromVoid)
{
// get the original type. For strings, it's just the type...
Type origType = ie.e1.type.nextOf();
// ..but for arrays of type void*, it's the type of the element
if (ie.e1.op == TOK.arrayLiteral && ie.e2.op == TOK.int64)
{
ArrayLiteralExp ale = cast(ArrayLiteralExp)ie.e1;
const indx = cast(size_t)ie.e2.toInteger();
if (indx < ale.elements.dim)
{
if (Expression xx = (*ale.elements)[indx])
{
if (auto iex = xx.isIndexExp())
origType = iex.e1.type.nextOf();
else if (auto ae = xx.isAddrExp())
origType = ae.e1.type;
else if (auto ve = xx.isVarExp())
origType = ve.var.type;
}
}
}
if (!isSafePointerCast(origType, pointee))
{
e.error("using `void*` to reinterpret cast from `%s*` to `%s*` is not supported in CTFE", origType.toChars(), pointee.toChars());
result = CTFEExp.cantexp;
return;
}
}
emplaceExp!(IndexExp)(pue, e1.loc, ie.e1, ie.e2);
result = pue.exp();
result.type = e.type;
return;
}
if (auto ae = e1.isAddrExp())
{
Type origType = ae.e1.type;
if (isSafePointerCast(origType, pointee))
{
emplaceExp!(AddrExp)(pue, e.loc, ae.e1, e.type);
result = pue.exp();
return;
}
if (castToSarrayPointer && pointee.toBasetype().ty == Tsarray && ae.e1.op == TOK.index)
{
// &val[idx]
dinteger_t dim = (cast(TypeSArray)pointee.toBasetype()).dim.toInteger();
IndexExp ie = cast(IndexExp)ae.e1;
Expression lwr = ie.e2;
Expression upr = ctfeEmplaceExp!IntegerExp(ie.e2.loc, ie.e2.toInteger() + dim, Type.tsize_t);
// Create a CTFE pointer &val[idx..idx+dim]
auto er = ctfeEmplaceExp!SliceExp(e.loc, ie.e1, lwr, upr);
er.type = pointee;
emplaceExp!(AddrExp)(pue, e.loc, er, e.type);
result = pue.exp();
return;
}
}
if (e1.op == TOK.variable || e1.op == TOK.symbolOffset)
{
// type painting operation
Type origType = (cast(SymbolExp)e1).var.type;
if (castBackFromVoid && !isSafePointerCast(origType, pointee))
{
e.error("using `void*` to reinterpret cast from `%s*` to `%s*` is not supported in CTFE", origType.toChars(), pointee.toChars());
result = CTFEExp.cantexp;
return;
}
if (auto ve = e1.isVarExp())
emplaceExp!(VarExp)(pue, e.loc, ve.var);
else
emplaceExp!(SymOffExp)(pue, e.loc, (cast(SymOffExp)e1).var, (cast(SymOffExp)e1).offset);
result = pue.exp();
result.type = e.to;
return;
}
// Check if we have a null pointer (eg, inside a struct)
e1 = interpretRegion(e1, istate);
if (e1.op != TOK.null_)
{
e.error("pointer cast from `%s` to `%s` is not supported at compile time", e1.type.toChars(), e.to.toChars());
result = CTFEExp.cantexp;
return;
}
}
if (e.to.ty == Tsarray && e.e1.type.ty == Tvector)
{
// Special handling for: cast(float[4])__vector([w, x, y, z])
e1 = interpretRegion(e.e1, istate);
if (exceptionOrCant(e1))
return;
assert(e1.op == TOK.vector);
e1 = interpretVectorToArray(pue, e1.isVectorExp());
}
if (e.to.ty == Tarray && e1.op == TOK.slice)
{
// Note that the slice may be void[], so when checking for dangerous
// casts, we need to use the original type, which is se.e1.
SliceExp se = cast(SliceExp)e1;
if (!isSafePointerCast(se.e1.type.nextOf(), e.to.nextOf()))
{
e.error("array cast from `%s` to `%s` is not supported at compile time", se.e1.type.toChars(), e.to.toChars());
result = CTFEExp.cantexp;
return;
}
emplaceExp!(SliceExp)(pue, e1.loc, se.e1, se.lwr, se.upr);
result = pue.exp();
result.type = e.to;
return;
}
// Disallow array type painting, except for conversions between built-in
// types of identical size.
if ((e.to.ty == Tsarray || e.to.ty == Tarray) && (e1.type.ty == Tsarray || e1.type.ty == Tarray) && !isSafePointerCast(e1.type.nextOf(), e.to.nextOf()))
{
e.error("array cast from `%s` to `%s` is not supported at compile time", e1.type.toChars(), e.to.toChars());
result = CTFEExp.cantexp;
return;
}
if (e.to.ty == Tsarray)
e1 = resolveSlice(e1);
if (e.to.toBasetype().ty == Tbool && e1.type.ty == Tpointer)
{
emplaceExp!(IntegerExp)(pue, e.loc, e1.op != TOK.null_, e.to);
result = pue.exp();
return;
}
result = ctfeCast(pue, e.loc, e.type, e.to, e1);
}
override void visit(AssertExp e)
{
debug (LOG)
{
printf("%s AssertExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
Expression e1 = interpret(pue, e.e1, istate);
if (exceptionOrCant(e1))
return;
if (isTrueBool(e1))
{
}
else if (e1.isBool(false))
{
if (e.msg)
{
UnionExp ue = void;
result = interpret(&ue, e.msg, istate);
if (exceptionOrCant(result))
return;
e.error("`%s`", result.toChars());
}
else
e.error("`%s` failed", e.toChars());
result = CTFEExp.cantexp;
return;
}
else
{
e.error("`%s` is not a compile time boolean expression", e1.toChars());
result = CTFEExp.cantexp;
return;
}
result = e1;
return;
}
override void visit(PtrExp e)
{
debug (LOG)
{
printf("%s PtrExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
// Check for int<->float and long<->double casts.
if (auto soe1 = e.e1.isSymOffExp())
if (soe1.offset == 0 && soe1.var.isVarDeclaration() && isFloatIntPaint(e.type, soe1.var.type))
{
// *(cast(int*)&v), where v is a float variable
result = paintFloatInt(pue, getVarExp(e.loc, istate, soe1.var, ctfeNeedRvalue), e.type);
return;
}
if (auto ce1 = e.e1.isCastExp())
if (auto ae11 = ce1.e1.isAddrExp())
{
// *(cast(int*)&x), where x is a float expression
Expression x = ae11.e1;
if (isFloatIntPaint(e.type, x.type))
{
result = paintFloatInt(pue, interpretRegion(x, istate), e.type);
return;
}
}
// Constant fold *(&structliteral + offset)
if (auto ae = e.e1.isAddExp())
{
if (ae.e1.op == TOK.address && ae.e2.op == TOK.int64)
{
AddrExp ade = cast(AddrExp)ae.e1;
Expression ex = interpretRegion(ade.e1, istate);
if (exceptionOrCant(ex))
return;
if (auto se = ex.isStructLiteralExp())
{
dinteger_t offset = ae.e2.toInteger();
result = se.getField(e.type, cast(uint)offset);
if (result)
return;
}
}
}
// It's possible we have an array bounds error. We need to make sure it
// errors with this line number, not the one where the pointer was set.
result = interpretRegion(e.e1, istate);
if (exceptionOrCant(result))
return;
if (result.op == TOK.function_)
return;
if (auto soe = result.isSymOffExp())
{
if (soe.offset == 0 && soe.var.isFuncDeclaration())
return;
e.error("cannot dereference pointer to static variable `%s` at compile time", soe.var.toChars());
result = CTFEExp.cantexp;
return;
}
if (result.op != TOK.address)
{
if (result.op == TOK.null_)
e.error("dereference of null pointer `%s`", e.e1.toChars());
else
e.error("dereference of invalid pointer `%s`", result.toChars());
result = CTFEExp.cantexp;
return;
}
// *(&x) ==> x
result = (cast(AddrExp)result).e1;
if (result.op == TOK.slice && e.type.toBasetype().ty == Tsarray)
{
/* aggr[lwr..upr]
* upr may exceed the upper boundary of aggr, but the check is deferred
* until those out-of-bounds elements will be touched.
*/
return;
}
result = interpret(pue, result, istate, goal);
if (exceptionOrCant(result))
return;
debug (LOG)
{
if (CTFEExp.isCantExp(result))
printf("PtrExp::interpret() %s = CTFEExp::cantexp\n", e.toChars());
}
}
override void visit(DotVarExp e)
{
debug (LOG)
{
printf("%s DotVarExp::interpret() %s, goal = %d\n", e.loc.toChars(), e.toChars(), goal);
}
Expression ex = interpretRegion(e.e1, istate);
if (exceptionOrCant(ex))
return;
if (FuncDeclaration f = e.var.isFuncDeclaration())
{
if (ex == e.e1)
result = e; // optimize: reuse this CTFE reference
else
{
emplaceExp!(DotVarExp)(pue, e.loc, ex, f, false);
result = pue.exp();
result.type = e.type;
}
return;
}
VarDeclaration v = e.var.isVarDeclaration();
if (!v)
{
e.error("CTFE internal error: `%s`", e.toChars());
result = CTFEExp.cantexp;
return;
}
if (ex.op == TOK.null_)
{
if (ex.type.toBasetype().ty == Tclass)
e.error("class `%s` is `null` and cannot be dereferenced", e.e1.toChars());
else
e.error("CTFE internal error: null this `%s`", e.e1.toChars());
result = CTFEExp.cantexp;
return;
}
if (ex.op != TOK.structLiteral && ex.op != TOK.classReference)
{
e.error("`%s.%s` is not yet implemented at compile time", e.e1.toChars(), e.var.toChars());
result = CTFEExp.cantexp;
return;
}
StructLiteralExp se;
int i;
// We can't use getField, because it makes a copy
if (ex.op == TOK.classReference)
{
se = (cast(ClassReferenceExp)ex).value;
i = (cast(ClassReferenceExp)ex).findFieldIndexByName(v);
}
else
{
se = cast(StructLiteralExp)ex;
i = findFieldIndexByName(se.sd, v);
}
if (i == -1)
{
e.error("couldn't find field `%s` of type `%s` in `%s`", v.toChars(), e.type.toChars(), se.toChars());
result = CTFEExp.cantexp;
return;
}
if (goal == ctfeNeedLvalue)
{
Expression ev = (*se.elements)[i];
if (!ev || ev.op == TOK.void_)
(*se.elements)[i] = voidInitLiteral(e.type, v).copy();
// just return the (simplified) dotvar expression as a CTFE reference
if (e.e1 == ex)
result = e;
else
{
emplaceExp!(DotVarExp)(pue, e.loc, ex, v);
result = pue.exp();
result.type = e.type;
}
return;
}
result = (*se.elements)[i];
if (!result)
{
// https://issues.dlang.org/show_bug.cgi?id=19897
// Zero-length fields don't have an initializer.
if (v.type.size() == 0)
result = voidInitLiteral(e.type, v).copy();
else
{
e.error("Internal Compiler Error: null field `%s`", v.toChars());
result = CTFEExp.cantexp;
return;
}
}
if (auto vie = result.isVoidInitExp())
{
const s = vie.var.toChars();
if (v.overlapped)
{
e.error("reinterpretation through overlapped field `%s` is not allowed in CTFE", s);
result = CTFEExp.cantexp;
return;
}
e.error("cannot read uninitialized variable `%s` in CTFE", s);
result = CTFEExp.cantexp;
return;
}
if (v.type.ty != result.type.ty && v.type.ty == Tsarray)
{
// Block assignment from inside struct literals
auto tsa = cast(TypeSArray)v.type;
auto len = cast(size_t)tsa.dim.toInteger();
UnionExp ue = void;
result = createBlockDuplicatedArrayLiteral(&ue, ex.loc, v.type, ex, len);
if (result == ue.exp())
result = ue.copy();
(*se.elements)[i] = result;
}
debug (LOG)
{
if (CTFEExp.isCantExp(result))
printf("DotVarExp::interpret() %s = CTFEExp::cantexp\n", e.toChars());
}
}
override void visit(RemoveExp e)
{
debug (LOG)
{
printf("%s RemoveExp::interpret() %s\n", e.loc.toChars(), e.toChars());
}
Expression agg = interpret(e.e1, istate);
if (exceptionOrCant(agg))
return;
Expression index = interpret(e.e2, istate);
if (exceptionOrCant(index))
return;
if (agg.op == TOK.null_)
{
result = CTFEExp.voidexp;
return;
}
AssocArrayLiteralExp aae = agg.isAssocArrayLiteralExp();
Expressions* keysx = aae.keys;
Expressions* valuesx = aae.values;
size_t removed = 0;
foreach (j, evalue; *valuesx)
{
Expression ekey = (*keysx)[j];
int eq = ctfeEqual(e.loc, TOK.equal, ekey, index);
if (eq)
++removed;
else if (removed != 0)
{
(*keysx)[j - removed] = ekey;
(*valuesx)[j - removed] = evalue;
}
}
valuesx.dim = valuesx.dim - removed;
keysx.dim = keysx.dim - removed;
result = IntegerExp.createBool(removed != 0);
}
override void visit(ClassReferenceExp e)
{
//printf("ClassReferenceExp::interpret() %s\n", e.value.toChars());
result = e;
}
override void visit(VoidInitExp e)
{
e.error("CTFE internal error: trying to read uninitialized variable");
assert(0);
}
override void visit(ThrownExceptionExp e)
{
assert(0); // This should never be interpreted
}
}
/********************************************
* Interpret the expression.
* Params:
* pue = non-null pointer to temporary storage that can be used to store the return value
* e = Expression to interpret
* istate = context
* goal = what the result will be used for
* Returns:
* resulting expression
*/
Expression interpret(UnionExp* pue, Expression e, InterState* istate, CtfeGoal goal = ctfeNeedRvalue)
{
if (!e)
return null;
scope Interpreter v = new Interpreter(pue, istate, goal);
e.accept(v);
Expression ex = v.result;
assert(goal == ctfeNeedNothing || ex !is null);
return ex;
}
///
Expression interpret(Expression e, InterState* istate, CtfeGoal goal = ctfeNeedRvalue)
{
UnionExp ue = void;
auto result = interpret(&ue, e, istate, goal);
if (result == ue.exp())
result = ue.copy();
return result;
}
/*****************************
* Same as interpret(), but return result allocated in Region.
* Params:
* e = Expression to interpret
* istate = context
* goal = what the result will be used for
* Returns:
* resulting expression
*/
Expression interpretRegion(Expression e, InterState* istate, CtfeGoal goal = ctfeNeedRvalue)
{
UnionExp ue = void;
auto result = interpret(&ue, e, istate, goal);
auto uexp = ue.exp();
if (result != uexp)
return result;
if (mem.isGCEnabled)
return ue.copy();
// mimicking UnionExp.copy, but with region allocation
switch (uexp.op)
{
case TOK.cantExpression: return CTFEExp.cantexp;
case TOK.voidExpression: return CTFEExp.voidexp;
case TOK.break_: return CTFEExp.breakexp;
case TOK.continue_: return CTFEExp.continueexp;
case TOK.goto_: return CTFEExp.gotoexp;
default: break;
}
auto p = ctfeGlobals.region.malloc(uexp.size);
return cast(Expression)memcpy(p, cast(void*)uexp, uexp.size);
}
/***********************************
* Interpret the statement.
* Params:
* pue = non-null pointer to temporary storage that can be used to store the return value
* s = Statement to interpret
* istate = context
* Returns:
* NULL continue to next statement
* TOK.cantExpression cannot interpret statement at compile time
* !NULL expression from return statement, or thrown exception
*/
Expression interpret(UnionExp* pue, Statement s, InterState* istate)
{
if (!s)
return null;
scope Interpreter v = new Interpreter(pue, istate, ctfeNeedNothing);
s.accept(v);
return v.result;
}
///
Expression interpret(Statement s, InterState* istate)
{
UnionExp ue = void;
auto result = interpret(&ue, s, istate);
if (result == ue.exp())
result = ue.copy();
return result;
}
/**
* All results destined for use outside of CTFE need to have their CTFE-specific
* features removed.
* In particular,
* 1. all slices must be resolved.
* 2. all .ownedByCtfe set to OwnedBy.code
*/
private Expression scrubReturnValue(const ref Loc loc, Expression e)
{
/* Returns: true if e is void,
* or is an array literal or struct literal of void elements.
*/
static bool isVoid(const Expression e, bool checkArrayType = false) pure
{
if (e.op == TOK.void_)
return true;
static bool isEntirelyVoid(const Expressions* elems)
{
foreach (e; *elems)
{
// It can be NULL for performance reasons,
// see StructLiteralExp::interpret().
if (e && !isVoid(e))
return false;
}
return true;
}
if (auto sle = e.isStructLiteralExp())
return isEntirelyVoid(sle.elements);
if (checkArrayType && e.type.ty != Tsarray)
return false;
if (auto ale = e.isArrayLiteralExp())
return isEntirelyVoid(ale.elements);
return false;
}
/* Scrub all elements of elems[].
* Returns: null for success, error Expression for failure
*/
Expression scrubArray(Expressions* elems, bool structlit = false)
{
foreach (ref e; *elems)
{
// It can be NULL for performance reasons,
// see StructLiteralExp::interpret().
if (!e)
continue;
// A struct .init may contain void members.
// Static array members are a weird special case https://issues.dlang.org/show_bug.cgi?id=10994
if (structlit && isVoid(e, true))
{
e = null;
}
else
{
e = scrubReturnValue(loc, e);
if (CTFEExp.isCantExp(e) || e.op == TOK.error)
return e;
}
}
return null;
}
Expression scrubSE(StructLiteralExp sle)
{
sle.ownedByCtfe = OwnedBy.code;
if (!(sle.stageflags & stageScrub))
{
const old = sle.stageflags;
sle.stageflags |= stageScrub; // prevent infinite recursion
if (auto ex = scrubArray(sle.elements, true))
return ex;
sle.stageflags = old;
}
return null;
}
if (e.op == TOK.classReference)
{
StructLiteralExp sle = (cast(ClassReferenceExp)e).value;
if (auto ex = scrubSE(sle))
return ex;
}
else if (auto vie = e.isVoidInitExp())
{
error(loc, "uninitialized variable `%s` cannot be returned from CTFE", vie.var.toChars());
return new ErrorExp();
}
e = resolveSlice(e);
if (auto sle = e.isStructLiteralExp())
{
if (auto ex = scrubSE(sle))
return ex;
}
else if (auto se = e.isStringExp())
{
se.ownedByCtfe = OwnedBy.code;
}
else if (auto ale = e.isArrayLiteralExp())
{
ale.ownedByCtfe = OwnedBy.code;
if (auto ex = scrubArray(ale.elements))
return ex;
}
else if (auto aae = e.isAssocArrayLiteralExp())
{
aae.ownedByCtfe = OwnedBy.code;
if (auto ex = scrubArray(aae.keys))
return ex;
if (auto ex = scrubArray(aae.values))
return ex;
aae.type = toBuiltinAAType(aae.type);
}
else if (auto ve = e.isVectorExp())
{
ve.ownedByCtfe = OwnedBy.code;
if (auto ale = ve.e1.isArrayLiteralExp())
{
ale.ownedByCtfe = OwnedBy.code;
if (auto ex = scrubArray(ale.elements))
return ex;
}
}
return e;
}
/**************************************
* Transitively set all .ownedByCtfe to OwnedBy.cache
*/
private Expression scrubCacheValue(Expression e)
{
if (!e)
return e;
Expression scrubArrayCache(Expressions* elems)
{
foreach (ref e; *elems)
e = scrubCacheValue(e);
return null;
}
Expression scrubSE(StructLiteralExp sle)
{
sle.ownedByCtfe = OwnedBy.cache;
if (!(sle.stageflags & stageScrub))
{
const old = sle.stageflags;
sle.stageflags |= stageScrub; // prevent infinite recursion
if (auto ex = scrubArrayCache(sle.elements))
return ex;
sle.stageflags = old;
}
return null;
}
if (e.op == TOK.classReference)
{
if (auto ex = scrubSE((cast(ClassReferenceExp)e).value))
return ex;
}
else if (auto sle = e.isStructLiteralExp())
{
if (auto ex = scrubSE(sle))
return ex;
}
else if (auto se = e.isStringExp())
{
se.ownedByCtfe = OwnedBy.cache;
}
else if (auto ale = e.isArrayLiteralExp())
{
ale.ownedByCtfe = OwnedBy.cache;
if (Expression ex = scrubArrayCache(ale.elements))
return ex;
}
else if (auto aae = e.isAssocArrayLiteralExp())
{
aae.ownedByCtfe = OwnedBy.cache;
if (auto ex = scrubArrayCache(aae.keys))
return ex;
if (auto ex = scrubArrayCache(aae.values))
return ex;
}
else if (auto ve = e.isVectorExp())
{
ve.ownedByCtfe = OwnedBy.cache;
if (auto ale = ve.e1.isArrayLiteralExp())
{
ale.ownedByCtfe = OwnedBy.cache;
if (auto ex = scrubArrayCache(ale.elements))
return ex;
}
}
return e;
}
/********************************************
* Transitively replace all Expressions allocated in ctfeGlobals.region
* with Mem owned copies.
* Params:
* e = possible ctfeGlobals.region owned expression
* Returns:
* Mem owned expression
*/
private Expression copyRegionExp(Expression e)
{
if (!e)
return e;
static void copyArray(Expressions* elems)
{
foreach (ref e; *elems)
{
auto ex = e;
e = null;
e = copyRegionExp(ex);
}
}
static void copySE(StructLiteralExp sle)
{
if (1 || !(sle.stageflags & stageScrub))
{
const old = sle.stageflags;
sle.stageflags |= stageScrub; // prevent infinite recursion
copyArray(sle.elements);
sle.stageflags = old;
}
}
switch (e.op)
{
case TOK.classReference:
{
auto cre = e.isClassReferenceExp();
cre.value = copyRegionExp(cre.value).isStructLiteralExp();
break;
}
case TOK.structLiteral:
{
auto sle = e.isStructLiteralExp();
/* The following is to take care of updating sle.origin correctly,
* which may have multiple objects pointing to it.
*/
if (sle.isOriginal && !ctfeGlobals.region.contains(cast(void*)sle.origin))
{
/* This means sle has already been moved out of the region,
* and sle.origin is the new location.
*/
return sle.origin;
}
copySE(sle);
sle.isOriginal = sle is sle.origin;
auto slec = ctfeGlobals.region.contains(cast(void*)e)
? e.copy().isStructLiteralExp() // move sle out of region to slec
: sle;
if (ctfeGlobals.region.contains(cast(void*)sle.origin))
{
auto sleo = sle.origin == sle ? slec : sle.origin.copy().isStructLiteralExp();
sle.origin = sleo;
slec.origin = sleo;
}
return slec;
}
case TOK.arrayLiteral:
{
auto ale = e.isArrayLiteralExp();
ale.basis = copyRegionExp(ale.basis);
copyArray(ale.elements);
break;
}
case TOK.assocArrayLiteral:
copyArray(e.isAssocArrayLiteralExp().keys);
copyArray(e.isAssocArrayLiteralExp().values);
break;
case TOK.slice:
{
auto se = e.isSliceExp();
se.e1 = copyRegionExp(se.e1);
se.upr = copyRegionExp(se.upr);
se.lwr = copyRegionExp(se.lwr);
break;
}
case TOK.tuple:
{
auto te = e.isTupleExp();
te.e0 = copyRegionExp(te.e0);
copyArray(te.exps);
break;
}
case TOK.address:
case TOK.delegate_:
case TOK.vector:
case TOK.dotVariable:
{
UnaExp ue = cast(UnaExp)e;
ue.e1 = copyRegionExp(ue.e1);
break;
}
case TOK.index:
{
BinExp be = cast(BinExp)e;
be.e1 = copyRegionExp(be.e1);
be.e2 = copyRegionExp(be.e2);
break;
}
case TOK.this_:
case TOK.super_:
case TOK.variable:
case TOK.type:
case TOK.function_:
case TOK.typeid_:
case TOK.string_:
case TOK.int64:
case TOK.error:
case TOK.float64:
case TOK.complex80:
case TOK.null_:
case TOK.void_:
case TOK.symbolOffset:
case TOK.char_:
break;
case TOK.cantExpression:
case TOK.voidExpression:
case TOK.showCtfeContext:
return e;
default:
printf("e: %s, %s\n", Token.toChars(e.op), e.toChars());
assert(0);
}
if (ctfeGlobals.region.contains(cast(void*)e))
{
return e.copy();
}
return e;
}
/******************************* Special Functions ***************************/
private Expression interpret_length(UnionExp* pue, InterState* istate, Expression earg)
{
//printf("interpret_length()\n");
earg = interpret(pue, earg, istate);
if (exceptionOrCantInterpret(earg))
return earg;
dinteger_t len = 0;
if (auto aae = earg.isAssocArrayLiteralExp())
len = aae.keys.dim;
else
assert(earg.op == TOK.null_);
emplaceExp!(IntegerExp)(pue, earg.loc, len, Type.tsize_t);
return pue.exp();
}
private Expression interpret_keys(UnionExp* pue, InterState* istate, Expression earg, Type returnType)
{
debug (LOG)
{
printf("interpret_keys()\n");
}
earg = interpret(pue, earg, istate);
if (exceptionOrCantInterpret(earg))
return earg;
if (earg.op == TOK.null_)
{
emplaceExp!(NullExp)(pue, earg.loc, earg.type);
return pue.exp();
}
if (earg.op != TOK.assocArrayLiteral && earg.type.toBasetype().ty != Taarray)
return null;
AssocArrayLiteralExp aae = earg.isAssocArrayLiteralExp();
auto ae = ctfeEmplaceExp!ArrayLiteralExp(aae.loc, returnType, aae.keys);
ae.ownedByCtfe = aae.ownedByCtfe;
*pue = copyLiteral(ae);
return pue.exp();
}
private Expression interpret_values(UnionExp* pue, InterState* istate, Expression earg, Type returnType)
{
debug (LOG)
{
printf("interpret_values()\n");
}
earg = interpret(pue, earg, istate);
if (exceptionOrCantInterpret(earg))
return earg;
if (earg.op == TOK.null_)
{
emplaceExp!(NullExp)(pue, earg.loc, earg.type);
return pue.exp();
}
if (earg.op != TOK.assocArrayLiteral && earg.type.toBasetype().ty != Taarray)
return null;
auto aae = earg.isAssocArrayLiteralExp();
auto ae = ctfeEmplaceExp!ArrayLiteralExp(aae.loc, returnType, aae.values);
ae.ownedByCtfe = aae.ownedByCtfe;
//printf("result is %s\n", e.toChars());
*pue = copyLiteral(ae);
return pue.exp();
}
private Expression interpret_dup(UnionExp* pue, InterState* istate, Expression earg)
{
debug (LOG)
{
printf("interpret_dup()\n");
}
earg = interpret(pue, earg, istate);
if (exceptionOrCantInterpret(earg))
return earg;
if (earg.op == TOK.null_)
{
emplaceExp!(NullExp)(pue, earg.loc, earg.type);
return pue.exp();
}
if (earg.op != TOK.assocArrayLiteral && earg.type.toBasetype().ty != Taarray)
return null;
auto aae = copyLiteral(earg).copy().isAssocArrayLiteralExp();
for (size_t i = 0; i < aae.keys.dim; i++)
{
if (Expression e = evaluatePostblit(istate, (*aae.keys)[i]))
return e;
if (Expression e = evaluatePostblit(istate, (*aae.values)[i]))
return e;
}
aae.type = earg.type.mutableOf(); // repaint type from const(int[int]) to const(int)[int]
//printf("result is %s\n", aae.toChars());
return aae;
}
// signature is int delegate(ref Value) OR int delegate(ref Key, ref Value)
private Expression interpret_aaApply(UnionExp* pue, InterState* istate, Expression aa, Expression deleg)
{
aa = interpret(aa, istate);
if (exceptionOrCantInterpret(aa))
return aa;
if (aa.op != TOK.assocArrayLiteral)
{
emplaceExp!(IntegerExp)(pue, deleg.loc, 0, Type.tsize_t);
return pue.exp();
}
FuncDeclaration fd = null;
Expression pthis = null;
if (auto de = deleg.isDelegateExp())
{
fd = de.func;
pthis = de.e1;
}
else if (auto fe = deleg.isFuncExp())
fd = fe.fd;
assert(fd && fd.fbody);
assert(fd.parameters);
size_t numParams = fd.parameters.dim;
assert(numParams == 1 || numParams == 2);
Parameter fparam = fd.type.isTypeFunction().parameterList[numParams - 1];
bool wantRefValue = 0 != (fparam.storageClass & (STC.out_ | STC.ref_));
Expressions args = Expressions(numParams);
AssocArrayLiteralExp ae = cast(AssocArrayLiteralExp)aa;
if (!ae.keys || ae.keys.dim == 0)
return ctfeEmplaceExp!IntegerExp(deleg.loc, 0, Type.tsize_t);
Expression eresult;
for (size_t i = 0; i < ae.keys.dim; ++i)
{
Expression ekey = (*ae.keys)[i];
Expression evalue = (*ae.values)[i];
if (wantRefValue)
{
Type t = evalue.type;
evalue = ctfeEmplaceExp!IndexExp(deleg.loc, ae, ekey);
evalue.type = t;
}
args[numParams - 1] = evalue;
if (numParams == 2)
args[0] = ekey;
UnionExp ue = void;
eresult = interpretFunction(&ue, fd, istate, &args, pthis);
if (eresult == ue.exp())
eresult = ue.copy();
if (exceptionOrCantInterpret(eresult))
return eresult;
if (eresult.isIntegerExp().getInteger() != 0)
return eresult;
}
return eresult;
}
/* Decoding UTF strings for foreach loops. Duplicates the functionality of
* the twelve _aApplyXXn functions in aApply.d in the runtime.
*/
private Expression foreachApplyUtf(UnionExp* pue, InterState* istate, Expression str, Expression deleg, bool rvs)
{
debug (LOG)
{
printf("foreachApplyUtf(%s, %s)\n", str.toChars(), deleg.toChars());
}
FuncDeclaration fd = null;
Expression pthis = null;
if (auto de = deleg.isDelegateExp())
{
fd = de.func;
pthis = de.e1;
}
else if (auto fe = deleg.isFuncExp())
fd = fe.fd;
assert(fd && fd.fbody);
assert(fd.parameters);
size_t numParams = fd.parameters.dim;
assert(numParams == 1 || numParams == 2);
Type charType = (*fd.parameters)[numParams - 1].type;
Type indexType = numParams == 2 ? (*fd.parameters)[0].type : Type.tsize_t;
size_t len = cast(size_t)resolveArrayLength(str);
if (len == 0)
{
emplaceExp!(IntegerExp)(pue, deleg.loc, 0, indexType);
return pue.exp();
}
UnionExp strTmp = void;
str = resolveSlice(str, &strTmp);
auto se = str.isStringExp();
auto ale = str.isArrayLiteralExp();
if (!se && !ale)
{
str.error("CTFE internal error: cannot foreach `%s`", str.toChars());
return CTFEExp.cantexp;
}
Expressions args = Expressions(numParams);
Expression eresult = null; // ded-store to prevent spurious warning
// Buffers for encoding; also used for decoding array literals
char[4] utf8buf = void;
wchar[2] utf16buf = void;
size_t start = rvs ? len : 0;
size_t end = rvs ? 0 : len;
for (size_t indx = start; indx != end;)
{
// Step 1: Decode the next dchar from the string.
string errmsg = null; // Used for reporting decoding errors
dchar rawvalue; // Holds the decoded dchar
size_t currentIndex = indx; // The index of the decoded character
if (ale)
{
// If it is an array literal, copy the code points into the buffer
size_t buflen = 1; // #code points in the buffer
size_t n = 1; // #code points in this char
size_t sz = cast(size_t)ale.type.nextOf().size();
switch (sz)
{
case 1:
if (rvs)
{
// find the start of the string
--indx;
buflen = 1;
while (indx > 0 && buflen < 4)
{
Expression r = (*ale.elements)[indx];
char x = cast(char)r.isIntegerExp().getInteger();
if ((x & 0xC0) != 0x80)
break;
--indx;
++buflen;
}
}
else
buflen = (indx + 4 > len) ? len - indx : 4;
for (size_t i = 0; i < buflen; ++i)
{
Expression r = (*ale.elements)[indx + i];
utf8buf[i] = cast(char)r.isIntegerExp().getInteger();
}
n = 0;
errmsg = utf_decodeChar(utf8buf[0 .. buflen], n, rawvalue);
break;
case 2:
if (rvs)
{
// find the start of the string
--indx;
buflen = 1;
Expression r = (*ale.elements)[indx];
ushort x = cast(ushort)r.isIntegerExp().getInteger();
if (indx > 0 && x >= 0xDC00 && x <= 0xDFFF)
{
--indx;
++buflen;
}
}
else
buflen = (indx + 2 > len) ? len - indx : 2;
for (size_t i = 0; i < buflen; ++i)
{
Expression r = (*ale.elements)[indx + i];
utf16buf[i] = cast(ushort)r.isIntegerExp().getInteger();
}
n = 0;
errmsg = utf_decodeWchar(utf16buf[0 .. buflen], n, rawvalue);
break;
case 4:
{
if (rvs)
--indx;
Expression r = (*ale.elements)[indx];
rawvalue = cast(dchar)r.isIntegerExp().getInteger();
n = 1;
}
break;
default:
assert(0);
}
if (!rvs)
indx += n;
}
else
{
// String literals
size_t saveindx; // used for reverse iteration
switch (se.sz)
{
case 1:
{
if (rvs)
{
// find the start of the string
--indx;
while (indx > 0 && ((se.getCodeUnit(indx) & 0xC0) == 0x80))
--indx;
saveindx = indx;
}
auto slice = se.peekString();
errmsg = utf_decodeChar(slice, indx, rawvalue);
if (rvs)
indx = saveindx;
break;
}
case 2:
if (rvs)
{
// find the start
--indx;
auto wc = se.getCodeUnit(indx);
if (wc >= 0xDC00 && wc <= 0xDFFF)
--indx;
saveindx = indx;
}
const slice = se.peekWstring();
errmsg = utf_decodeWchar(slice, indx, rawvalue);
if (rvs)
indx = saveindx;
break;
case 4:
if (rvs)
--indx;
rawvalue = se.getCodeUnit(indx);
if (!rvs)
++indx;
break;
default:
assert(0);
}
}
if (errmsg)
{
deleg.error("`%.*s`", cast(int)errmsg.length, errmsg.ptr);
return CTFEExp.cantexp;
}
// Step 2: encode the dchar in the target encoding
int charlen = 1; // How many codepoints are involved?
switch (charType.size())
{
case 1:
charlen = utf_codeLengthChar(rawvalue);
utf_encodeChar(&utf8buf[0], rawvalue);
break;
case 2:
charlen = utf_codeLengthWchar(rawvalue);
utf_encodeWchar(&utf16buf[0], rawvalue);
break;
case 4:
break;
default:
assert(0);
}
if (rvs)
currentIndex = indx;
// Step 3: call the delegate once for each code point
// The index only needs to be set once
if (numParams == 2)
args[0] = ctfeEmplaceExp!IntegerExp(deleg.loc, currentIndex, indexType);
Expression val = null;
foreach (k; 0 .. charlen)
{
dchar codepoint;
switch (charType.size())
{
case 1:
codepoint = utf8buf[k];
break;
case 2:
codepoint = utf16buf[k];
break;
case 4:
codepoint = rawvalue;
break;
default:
assert(0);
}
val = ctfeEmplaceExp!IntegerExp(str.loc, codepoint, charType);
args[numParams - 1] = val;
UnionExp ue = void;
eresult = interpretFunction(&ue, fd, istate, &args, pthis);
if (eresult == ue.exp())
eresult = ue.copy();
if (exceptionOrCantInterpret(eresult))
return eresult;
if (eresult.isIntegerExp().getInteger() != 0)
return eresult;
}
}
return eresult;
}
/* If this is a built-in function, return the interpreted result,
* Otherwise, return NULL.
*/
private Expression evaluateIfBuiltin(UnionExp* pue, InterState* istate, const ref Loc loc, FuncDeclaration fd, Expressions* arguments, Expression pthis)
{
Expression e = null;
size_t nargs = arguments ? arguments.dim : 0;
if (!pthis)
{
if (isBuiltin(fd) == BUILTIN.yes)
{
Expressions args = Expressions(nargs);
foreach (i, ref arg; args)
{
Expression earg = (*arguments)[i];
earg = interpret(earg, istate);
if (exceptionOrCantInterpret(earg))
return earg;
arg = earg;
}
e = eval_builtin(loc, fd, &args);
if (!e)
{
error(loc, "cannot evaluate unimplemented builtin `%s` at compile time", fd.toChars());
e = CTFEExp.cantexp;
}
}
}
if (!pthis)
{
if (nargs == 1 || nargs == 3)
{
Expression firstarg = (*arguments)[0];
if (auto firstAAtype = firstarg.type.toBasetype().isTypeAArray())
{
const id = fd.ident;
if (nargs == 1)
{
if (id == Id.aaLen)
return interpret_length(pue, istate, firstarg);
if (fd.toParent2().ident == Id.object)
{
if (id == Id.keys)
return interpret_keys(pue, istate, firstarg, firstAAtype.index.arrayOf());
if (id == Id.values)
return interpret_values(pue, istate, firstarg, firstAAtype.nextOf().arrayOf());
if (id == Id.rehash)
return interpret(pue, firstarg, istate);
if (id == Id.dup)
return interpret_dup(pue, istate, firstarg);
}
}
else // (nargs == 3)
{
if (id == Id._aaApply)
return interpret_aaApply(pue, istate, firstarg, (*arguments)[2]);
if (id == Id._aaApply2)
return interpret_aaApply(pue, istate, firstarg, (*arguments)[2]);
}
}
}
}
if (pthis && !fd.fbody && fd.isCtorDeclaration() && fd.parent && fd.parent.parent && fd.parent.parent.ident == Id.object)
{
if (pthis.op == TOK.classReference && fd.parent.ident == Id.Throwable)
{
// At present, the constructors just copy their arguments into the struct.
// But we might need some magic if stack tracing gets added to druntime.
StructLiteralExp se = (cast(ClassReferenceExp)pthis).value;
assert(arguments.dim <= se.elements.dim);
foreach (i, arg; *arguments)
{
auto elem = interpret(arg, istate);
if (exceptionOrCantInterpret(elem))
return elem;
(*se.elements)[i] = elem;
}
return CTFEExp.voidexp;
}
}
if (nargs == 1 && !pthis && (fd.ident == Id.criticalenter || fd.ident == Id.criticalexit))
{
// Support synchronized{} as a no-op
return CTFEExp.voidexp;
}
if (!pthis)
{
const idlen = fd.ident.toString().length;
const id = fd.ident.toChars();
if (nargs == 2 && (idlen == 10 || idlen == 11) && !strncmp(id, "_aApply", 7))
{
// Functions from aApply.d and aApplyR.d in the runtime
bool rvs = (idlen == 11); // true if foreach_reverse
char c = id[idlen - 3]; // char width: 'c', 'w', or 'd'
char s = id[idlen - 2]; // string width: 'c', 'w', or 'd'
char n = id[idlen - 1]; // numParams: 1 or 2.
// There are 12 combinations
if ((n == '1' || n == '2') &&
(c == 'c' || c == 'w' || c == 'd') &&
(s == 'c' || s == 'w' || s == 'd') &&
c != s)
{
Expression str = (*arguments)[0];
str = interpret(str, istate);
if (exceptionOrCantInterpret(str))
return str;
return foreachApplyUtf(pue, istate, str, (*arguments)[1], rvs);
}
}
}
return e;
}
private Expression evaluatePostblit(InterState* istate, Expression e)
{
auto ts = e.type.baseElemOf().isTypeStruct();
if (!ts)
return null;
StructDeclaration sd = ts.sym;
if (!sd.postblit)
return null;
if (auto ale = e.isArrayLiteralExp())
{
foreach (elem; *ale.elements)
{
if (auto ex = evaluatePostblit(istate, elem))
return ex;
}
return null;
}
if (e.op == TOK.structLiteral)
{
// e.__postblit()
UnionExp ue = void;
e = interpretFunction(&ue, sd.postblit, istate, null, e);
if (e == ue.exp())
e = ue.copy();
if (exceptionOrCantInterpret(e))
return e;
return null;
}
assert(0);
}
private Expression evaluateDtor(InterState* istate, Expression e)
{
auto ts = e.type.baseElemOf().isTypeStruct();
if (!ts)
return null;
StructDeclaration sd = ts.sym;
if (!sd.dtor)
return null;
UnionExp ue = void;
if (auto ale = e.isArrayLiteralExp())
{
foreach_reverse (elem; *ale.elements)
e = evaluateDtor(istate, elem);
}
else if (e.op == TOK.structLiteral)
{
// e.__dtor()
e = interpretFunction(&ue, sd.dtor, istate, null, e);
}
else
assert(0);
if (exceptionOrCantInterpret(e))
{
if (e == ue.exp())
e = ue.copy();
return e;
}
return null;
}
/*************************** CTFE Sanity Checks ***************************/
/* Setter functions for CTFE variable values.
* These functions exist to check for compiler CTFE bugs.
*/
private bool hasValue(VarDeclaration vd)
{
return vd.ctfeAdrOnStack != VarDeclaration.AdrOnStackNone &&
getValue(vd) !is null;
}
// Don't check for validity
private void setValueWithoutChecking(VarDeclaration vd, Expression newval)
{
ctfeGlobals.stack.setValue(vd, newval);
}
private void setValue(VarDeclaration vd, Expression newval)
{
version (none)
{
if (!((vd.storage_class & (STC.out_ | STC.ref_)) ? isCtfeReferenceValid(newval) : isCtfeValueValid(newval)))
{
printf("[%s] vd = %s %s, newval = %s\n", vd.loc.toChars(), vd.type.toChars(), vd.toChars(), newval.toChars());
}
}
assert((vd.storage_class & (STC.out_ | STC.ref_)) ? isCtfeReferenceValid(newval) : isCtfeValueValid(newval));
ctfeGlobals.stack.setValue(vd, newval);
}
/**
* Removes `_d_HookTraceImpl` if found from `ce` and `fd`.
* This is needed for the CTFE interception code to be able to find hooks that are called though the hook's `*Trace`
* wrapper.
*
* This is done by replacing `_d_HookTraceImpl!(T, Hook, errMsg)(..., parameters)` with `Hook(parameters)`.
* Parameters:
* ce = The CallExp that possible will be be replaced
* fd = Fully resolve function declaration that `ce` would call
*/
private void removeHookTraceImpl(ref CallExp ce, ref FuncDeclaration fd)
{
if (fd.ident != Id._d_HookTraceImpl)
return;
auto oldCE = ce;
// Get the Hook from the second template parameter
TemplateInstance templateInstance = fd.parent.isTemplateInstance;
RootObject hook = (*templateInstance.tiargs)[1];
assert(hook.dyncast() == DYNCAST.dsymbol, "Expected _d_HookTraceImpl's second template parameter to be an alias to the hook!");
fd = (cast(Dsymbol)hook).isFuncDeclaration;
// Remove the first three trace parameters
auto arguments = new Expressions();
arguments.reserve(ce.arguments.dim - 3);
arguments.pushSlice((*ce.arguments)[3 .. $]);
ce = ctfeEmplaceExp!CallExp(ce.loc, ctfeEmplaceExp!VarExp(ce.loc, fd, false), arguments);
if (global.params.verbose)
message("strip %s =>\n %s", oldCE.toChars(), ce.toChars());
}
|
D
|
module ws.wm.x11.cursorfont;
enum XC_num_glyphs = 154;
enum XC_X_cursor = 0;
enum XC_arrow = 2;
enum XC_based_arrow_down = 4;
enum XC_based_arrow_up = 6;
enum XC_boat = 8;
enum XC_bogosity = 10;
enum XC_bottom_left_corner = 12;
enum XC_bottom_right_corner = 14;
enum XC_bottom_side = 16;
enum XC_bottom_tee = 18;
enum XC_box_spiral = 20;
enum XC_center_ptr = 22;
enum XC_circle = 24;
enum XC_clock = 26;
enum XC_coffee_mug = 28;
enum XC_cross = 30;
enum XC_cross_reverse = 32;
enum XC_crosshair = 34;
enum XC_diamond_cross = 36;
enum XC_dot = 38;
enum XC_dotbox = 40;
enum XC_double_arrow = 42;
enum XC_draft_large = 44;
enum XC_draft_small = 46;
enum XC_draped_box = 48;
enum XC_exchange = 50;
enum XC_fleur = 52;
enum XC_gobbler = 54;
enum XC_gumby = 56;
enum XC_hand1 = 58;
enum XC_hand2 = 60;
enum XC_heart = 62;
enum XC_icon = 64;
enum XC_iron_cross = 66;
enum XC_left_ptr = 68;
enum XC_left_side = 70;
enum XC_left_tee = 72;
enum XC_leftbutton = 74;
enum XC_ll_angle = 76;
enum XC_lr_angle = 78;
enum XC_man = 80;
enum XC_middlebutton = 82;
enum XC_mouse = 84;
enum XC_pencil = 86;
enum XC_pirate = 88;
enum XC_plus = 90;
enum XC_question_arrow = 92;
enum XC_right_ptr = 94;
enum XC_right_side = 96;
enum XC_right_tee = 98;
enum XC_rightbutton = 100;
enum XC_rtl_logo = 102;
enum XC_sailboat = 104;
enum XC_sb_down_arrow = 106;
enum XC_sb_h_double_arrow = 108;
enum XC_sb_left_arrow = 110;
enum XC_sb_right_arrow = 112;
enum XC_sb_up_arrow = 114;
enum XC_sb_v_double_arrow = 116;
enum XC_shuttle = 118;
enum XC_sizing = 120;
enum XC_spider = 122;
enum XC_spraycan = 124;
enum XC_star = 126;
enum XC_target = 128;
enum XC_tcross = 130;
enum XC_top_left_arrow = 132;
enum XC_top_left_corner = 134;
enum XC_top_right_corner = 136;
enum XC_top_side = 138;
enum XC_top_tee = 140;
enum XC_trek = 142;
enum XC_ul_angle = 144;
enum XC_umbrella = 146;
enum XC_ur_angle = 148;
enum XC_watch = 150;
enum XC_xterm = 152;
|
D
|
/Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/NIOHTTP1.build/HTTPEncoder.swift.o : /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPPipelineSetup.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPDecoder.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPEncoder.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPUpgradeHandler.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPResponseCompressor.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPTypes.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/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/NIO.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 /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.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/SwiftOnoneSupport.swiftmodule /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIOZlib/include/c_nio_zlib.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIOAtomics/include/cpp_magic.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIODarwin/include/c_nio_darwin.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIOHTTPParser/include/c_nio_http_parser.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIOAtomics/include/c-atomics.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIOLinux/include/c_nio_linux.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio-zlib-support.git--8656613645092558840/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.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
/Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/NIOHTTP1.build/HTTPEncoder~partial.swiftmodule : /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPPipelineSetup.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPDecoder.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPEncoder.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPUpgradeHandler.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPResponseCompressor.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPTypes.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/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/NIO.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 /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.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/SwiftOnoneSupport.swiftmodule /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIOZlib/include/c_nio_zlib.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIOAtomics/include/cpp_magic.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIODarwin/include/c_nio_darwin.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIOHTTPParser/include/c_nio_http_parser.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIOAtomics/include/c-atomics.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIOLinux/include/c_nio_linux.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio-zlib-support.git--8656613645092558840/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.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
/Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/NIOHTTP1.build/HTTPEncoder~partial.swiftdoc : /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPPipelineSetup.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPDecoder.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPEncoder.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPUpgradeHandler.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPResponseCompressor.swift /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/NIOHTTP1/HTTPTypes.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/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/NIO.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 /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.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/SwiftOnoneSupport.swiftmodule /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIOZlib/include/c_nio_zlib.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIOAtomics/include/cpp_magic.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIODarwin/include/c_nio_darwin.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIOHTTPParser/include/c_nio_http_parser.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIOAtomics/include/c-atomics.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio.git-6105345694714423636/Sources/CNIOLinux/include/c_nio_linux.h /Users/jimallan/Downloads/starter/location-track-server/.build/checkouts/swift-nio-zlib-support.git--8656613645092558840/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/jimallan/Downloads/starter/location-track-server/.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
|
D
|
/u/tlan2/Rust/Mini_Games/target/debug/build/rand_pcg-2f770365bc017b2a/build_script_build-2f770365bc017b2a: /u/tlan2/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_pcg-0.1.2/build.rs
/u/tlan2/Rust/Mini_Games/target/debug/build/rand_pcg-2f770365bc017b2a/build_script_build-2f770365bc017b2a.d: /u/tlan2/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_pcg-0.1.2/build.rs
/u/tlan2/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_pcg-0.1.2/build.rs:
|
D
|
/Users/yan/IdeaProjects/IOS\ Projects/MyMovieApp/build/Pods.build/Debug-iphonesimulator/YouTubePlayer.build/Objects-normal/x86_64/YouTubePlayer.o : /Users/yan/IdeaProjects/IOS\ Projects/MyMovieApp/Pods/YouTubePlayer/YouTubePlayer/YouTubePlayer/YouTubePlayer.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/yan/IdeaProjects/IOS\ Projects/MyMovieApp/Pods/Target\ Support\ Files/YouTubePlayer/YouTubePlayer-umbrella.h /Users/yan/IdeaProjects/IOS\ Projects/MyMovieApp/build/Pods.build/Debug-iphonesimulator/YouTubePlayer.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/yan/IdeaProjects/IOS\ Projects/MyMovieApp/build/Pods.build/Debug-iphonesimulator/YouTubePlayer.build/Objects-normal/x86_64/YouTubePlayer~partial.swiftmodule : /Users/yan/IdeaProjects/IOS\ Projects/MyMovieApp/Pods/YouTubePlayer/YouTubePlayer/YouTubePlayer/YouTubePlayer.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/yan/IdeaProjects/IOS\ Projects/MyMovieApp/Pods/Target\ Support\ Files/YouTubePlayer/YouTubePlayer-umbrella.h /Users/yan/IdeaProjects/IOS\ Projects/MyMovieApp/build/Pods.build/Debug-iphonesimulator/YouTubePlayer.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/yan/IdeaProjects/IOS\ Projects/MyMovieApp/build/Pods.build/Debug-iphonesimulator/YouTubePlayer.build/Objects-normal/x86_64/YouTubePlayer~partial.swiftdoc : /Users/yan/IdeaProjects/IOS\ Projects/MyMovieApp/Pods/YouTubePlayer/YouTubePlayer/YouTubePlayer/YouTubePlayer.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/yan/IdeaProjects/IOS\ Projects/MyMovieApp/Pods/Target\ Support\ Files/YouTubePlayer/YouTubePlayer-umbrella.h /Users/yan/IdeaProjects/IOS\ Projects/MyMovieApp/build/Pods.build/Debug-iphonesimulator/YouTubePlayer.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
|
D
|
import std.stdio;
struct FileHeader {
byte fmtVersion;
int magic;
byte id;
}
void main() {
writeln(FileHeader.sizeof);
}
|
D
|
# FIXED
drivers/rgb.obj: C:/ti/tivaware_c_series_2_1_4_178/examples/boards/ek-tm4c123gxl/drivers/rgb.c
drivers/rgb.obj: C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/stdint.h
drivers/rgb.obj: C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/_ti_config.h
drivers/rgb.obj: C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/linkage.h
drivers/rgb.obj: C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/_stdint40.h
drivers/rgb.obj: C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/sys/stdint.h
drivers/rgb.obj: C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/sys/cdefs.h
drivers/rgb.obj: C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/sys/_types.h
drivers/rgb.obj: C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/machine/_types.h
drivers/rgb.obj: C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/machine/_stdint.h
drivers/rgb.obj: C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/sys/_stdint.h
drivers/rgb.obj: C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/stdbool.h
drivers/rgb.obj: C:/ti/tivaware_c_series_2_1_4_178/inc/hw_types.h
drivers/rgb.obj: C:/ti/tivaware_c_series_2_1_4_178/inc/hw_memmap.h
drivers/rgb.obj: C:/ti/tivaware_c_series_2_1_4_178/inc/hw_timer.h
drivers/rgb.obj: C:/ti/tivaware_c_series_2_1_4_178/inc/hw_ints.h
drivers/rgb.obj: C:/ti/tivaware_c_series_2_1_4_178/driverlib/sysctl.h
drivers/rgb.obj: C:/ti/tivaware_c_series_2_1_4_178/driverlib/rom.h
drivers/rgb.obj: C:/ti/tivaware_c_series_2_1_4_178/driverlib/rom_map.h
drivers/rgb.obj: C:/ti/tivaware_c_series_2_1_4_178/driverlib/pin_map.h
drivers/rgb.obj: C:/ti/tivaware_c_series_2_1_4_178/driverlib/timer.h
drivers/rgb.obj: C:/ti/tivaware_c_series_2_1_4_178/driverlib/gpio.h
drivers/rgb.obj: C:/ti/tivaware_c_series_2_1_4_178/driverlib/interrupt.h
drivers/rgb.obj: C:/ti/tivaware_c_series_2_1_4_178/examples/boards/ek-tm4c123gxl/drivers/rgb.h
C:/ti/tivaware_c_series_2_1_4_178/examples/boards/ek-tm4c123gxl/drivers/rgb.c:
C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/stdint.h:
C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/_ti_config.h:
C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/linkage.h:
C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/_stdint40.h:
C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/sys/stdint.h:
C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/sys/cdefs.h:
C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/sys/_types.h:
C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/machine/_types.h:
C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/machine/_stdint.h:
C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/sys/_stdint.h:
C:/ti/ccs1010/ccs/tools/compiler/ti-cgt-arm_20.2.1.LTS/include/stdbool.h:
C:/ti/tivaware_c_series_2_1_4_178/inc/hw_types.h:
C:/ti/tivaware_c_series_2_1_4_178/inc/hw_memmap.h:
C:/ti/tivaware_c_series_2_1_4_178/inc/hw_timer.h:
C:/ti/tivaware_c_series_2_1_4_178/inc/hw_ints.h:
C:/ti/tivaware_c_series_2_1_4_178/driverlib/sysctl.h:
C:/ti/tivaware_c_series_2_1_4_178/driverlib/rom.h:
C:/ti/tivaware_c_series_2_1_4_178/driverlib/rom_map.h:
C:/ti/tivaware_c_series_2_1_4_178/driverlib/pin_map.h:
C:/ti/tivaware_c_series_2_1_4_178/driverlib/timer.h:
C:/ti/tivaware_c_series_2_1_4_178/driverlib/gpio.h:
C:/ti/tivaware_c_series_2_1_4_178/driverlib/interrupt.h:
C:/ti/tivaware_c_series_2_1_4_178/examples/boards/ek-tm4c123gxl/drivers/rgb.h:
|
D
|
instance VLK_494_Attila(Npc_Default)
{
name[0] = "Attila";
guild = GIL_VLK;
id = 494;
voice = 9;
flags = 0;
npcType = npctype_main;
B_SetAttributesToChapter(self,2);
aivar[AIV_DropDeadAndKill] = TRUE;
fight_tactic = FAI_HUMAN_STRONG;
EquipItem(self,ItMw_1h_Sld_Axe);
EquipItem(self,ItRw_Mil_Crossbow);
CreateInvItem(self,ItKe_ThiefGuildKey_MIS);
B_SetNpcVisual(self,MALE,"Hum_Head_Bald",Face_L_Tough_Santino,BodyTex_L,itar_leather_l_grd5);
Mdl_SetModelFatness(self,0);
Mdl_ApplyOverlayMds(self,"Humans_Relaxed.mds");
B_GiveNpcTalents(self);
B_SetFightSkills(self,30);
daily_routine = Rtn_Start_494;
};
func void Rtn_Start_494()
{
TA_Stand_Guarding(4,0,22,0,"NW_CITY_HABOUR_POOR_AREA_BACK_ALLEY_02");
TA_Stand_Guarding(22,0,4,0,"NW_CITY_HABOUR_POOR_AREA_BACK_ALLEY_02");
};
func void Rtn_After_494()
{
TA_Stand_Guarding(7,25,12,15,"NW_CITY_HABOUR_POOR_AREA_CAULDRON");
TA_Stand_ArmsCrossed(12,15,16,30,"NW_CITY_HABOUR_NP03_ADD2");
TA_Stand_ArmsCrossed(16,30,18,0,"NW_CITY_HABOUR_NP03_ADD4");
TA_Stand_Guarding(18,0,1,25,"NW_CITY_HABOUR_06_CNADD2");
TA_Sit_Bench(1,25,7,25,"NW_CITY_HABOUR_BENCH_01");
};
|
D
|
module extensions;
|
D
|
/*
* Oracle Linux DTrace.
* Copyright (c) 2006, 2020, Oracle and/or its affiliates. All rights reserved.
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
/*
* ASSERTION:
* Test the declaration of a translator with the input type enclosed in
* between parantheses rather than angle brackets.
*
* SECTION: Translators/Translator Declarations
*
*/
#pragma D option quiet
struct input_struct {
int i;
char c;
} *uvar;
struct output_struct {
int myi;
char myc;
};
translator struct output_struct (struct input_struct *uvar)
{
myi = ((struct input_struct *)uvar)->i;
myc = ((struct input_struct *)uvar)->c;
}
BEGIN
{
printf("Test translator with input type in parantheses");
exit(0);
}
|
D
|
module deimos.cef1.display_handler;
// Copyright (c) 2012 Marshall A. Greenblatt. 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 name of Google Inc. nor the name Chromium Embedded
// Framework 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.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool and should not edited
// by hand. See the translator.README.txt file in the tools directory for
// more information.
//
// #ifndef CEF_INCLUDE_CAPI_CEF_DISPLAY_HANDLER_CAPI_H_
// #pragma once
// #ifdef __cplusplus
extern(C) {
// #endif
import deimos.cef1.base;
///
// Implement this structure to handle events related to browser display state.
// The functions of this structure will be called on the UI thread.
///
struct cef_display_handler_t {
///
// Base structure.
///
cef_base_t base;
///
// Called when the navigation state has changed.
///
extern(System) void function(cef_display_handler_t* self, cef_browser_t* browser, int canGoBack, int canGoForward) on_nav_state_change;
///
// Called when a frame's address has changed.
///
extern(System) void function(cef_display_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, const(cef_string_t)* url) on_address_change;
///
// Called when the size of the content area has changed.
///
extern(System) void function(cef_display_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, int width, int height) on_contents_size_change;
///
// Called when the page title changes.
///
extern(System) void function(cef_display_handler_t* self, cef_browser_t* browser, const(cef_string_t)* title) on_title_change;
///
// Called when the browser is about to display a tooltip. |text| contains the
// text that will be displayed in the tooltip. To handle the display of the
// tooltip yourself return true (1). Otherwise, you can optionally modify
// |text| and then return false (0) to allow the browser to display the
// tooltip.
///
extern(System) int function(cef_display_handler_t* self, cef_browser_t* browser, cef_string_t* text) on_tooltip;
///
// Called when the browser receives a status message. |text| contains the text
// that will be displayed in the status message and |type| indicates the
// status message type.
///
extern(System) void function(cef_display_handler_t* self, cef_browser_t* browser, const(cef_string_t)* value, cef_handler_statustype_t type) on_status_message;
///
// Called to display a console message. Return true (1) to stop the message
// from being output to the console.
///
extern(System) int function(cef_display_handler_t* self, cef_browser_t* browser, const(cef_string_t)* message, const(cef_string_t)* source, int line) on_console_message;
}
// #ifdef __cplusplus
}
// #endif
// #endif CEF_INCLUDE_CAPI_CEF_DISPLAY_HANDLER_CAPI_H_
|
D
|
/**
* Contains high-level interfaces for interacting with DMD as a library.
*
* Copyright: Copyright (C) 1999-2023 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/id.d, _id.d)
* Documentation: https://dlang.org/phobos/dmd_frontend.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/frontend.d
*/
module dmd.frontend;
import dmd.astcodegen : ASTCodegen;
import dmd.dmodule : Module;
import dmd.globals : CHECKENABLE, DiagnosticReporting;
import dmd.errors;
import dmd.location;
import std.range.primitives : isInputRange, ElementType;
import std.traits : isNarrowString;
import std.typecons : Tuple;
import core.stdc.stdarg;
version (Windows) private enum sep = ";", exe = ".exe";
version (Posix) private enum sep = ":", exe = "";
/// Contains aggregated diagnostics information.
immutable struct Diagnostics
{
/// Number of errors diagnosed
uint errors;
/// Number of warnings diagnosed
uint warnings;
/// Returns: `true` if errors have been diagnosed
bool hasErrors()
{
return errors > 0;
}
/// Returns: `true` if warnings have been diagnosed
bool hasWarnings()
{
return warnings > 0;
}
}
/// Indicates the checking state of various contracts.
enum ContractChecking : CHECKENABLE
{
/// Initial value
default_ = CHECKENABLE._default,
/// Never do checking
disabled = CHECKENABLE.off,
/// Always do checking
enabled = CHECKENABLE.on,
/// Only do checking in `@safe` functions
enabledInSafe = CHECKENABLE.safeonly
}
static assert(
__traits(allMembers, ContractChecking).length ==
__traits(allMembers, CHECKENABLE).length
);
/// Indicates which contracts should be checked or not.
struct ContractChecks
{
/// Precondition checks (in contract).
ContractChecking precondition = ContractChecking.enabled;
/// Invariant checks.
ContractChecking invariant_ = ContractChecking.enabled;
/// Postcondition checks (out contract).
ContractChecking postcondition = ContractChecking.enabled;
/// Array bound checks.
ContractChecking arrayBounds = ContractChecking.enabled;
/// Assert checks.
ContractChecking assert_ = ContractChecking.enabled;
/// Switch error checks.
ContractChecking switchError = ContractChecking.enabled;
}
/*
Initializes the global variables of the DMD compiler.
This needs to be done $(I before) calling any function.
Params:
diagnosticHandler = a delegate to configure what to do with diagnostics (other than printing to console or stderr).
fatalErrorHandler = a delegate to configure what to do with fatal errors (default is to call exit(EXIT_FAILURE)).
contractChecks = indicates which contracts should be enabled or not
versionIdentifiers = a list of version identifiers that should be enabled
*/
void initDMD(
DiagnosticHandler diagnosticHandler = null,
FatalErrorHandler fatalErrorHandler = null,
const string[] versionIdentifiers = [],
ContractChecks contractChecks = ContractChecks()
)
{
import std.algorithm : each;
import dmd.root.ctfloat : CTFloat;
version (CRuntime_Microsoft)
import dmd.root.longdouble : initFPU;
import dmd.cond : VersionCondition;
import dmd.dmodule : Module;
import dmd.escape : EscapeState;
import dmd.expression : Expression;
import dmd.globals : CHECKENABLE, global;
import dmd.id : Id;
import dmd.identifier : Identifier;
import dmd.mtype : Type;
import dmd.objc : Objc;
import dmd.target : target, defaultTargetOS, addDefaultVersionIdentifiers;
.diagnosticHandler = diagnosticHandler;
.fatalErrorHandler = fatalErrorHandler;
global._init();
with (global.params)
{
useIn = contractChecks.precondition;
useInvariants = contractChecks.invariant_;
useOut = contractChecks.postcondition;
useArrayBounds = contractChecks.arrayBounds;
useAssert = contractChecks.assert_;
useSwitchError = contractChecks.switchError;
}
versionIdentifiers.each!(VersionCondition.addGlobalIdent);
target.os = defaultTargetOS();
target._init(global.params);
Type._init();
Id.initialize();
Module._init();
Expression._init();
Objc._init();
EscapeState.reset();
addDefaultVersionIdentifiers(global.params, target);
version (CRuntime_Microsoft)
initFPU();
CTFloat.initialize();
}
/**
Deinitializes the global variables of the DMD compiler.
This can be used to restore the state set by `initDMD` to its original state.
Useful if there's a need for multiple sessions of the DMD compiler in the same
application.
*/
void deinitializeDMD()
{
import dmd.dmodule : Module;
import dmd.dsymbol : Dsymbol;
import dmd.escape : EscapeState;
import dmd.expression : Expression;
import dmd.globals : global;
import dmd.id : Id;
import dmd.mtype : Type;
import dmd.objc : Objc;
import dmd.target : target;
diagnosticHandler = null;
fatalErrorHandler = null;
global.deinitialize();
Type.deinitialize();
Id.deinitialize();
Module.deinitialize();
target.deinitialize();
Expression.deinitialize();
Objc.deinitialize();
Dsymbol.deinitialize();
EscapeState.reset();
}
/**
Add import path to the `global.path`.
Params:
path = import to add
*/
void addImport(const(char)[] path)
{
import dmd.globals : global;
import dmd.arraytypes : Strings;
import std.string : toStringz;
if (global.path is null)
global.path = new Strings();
global.path.push(path.toStringz);
}
/**
Add string import path to `global.filePath`.
Params:
path = string import to add
*/
void addStringImport(const(char)[] path)
{
import std.string : toStringz;
import dmd.globals : global;
import dmd.arraytypes : Strings;
if (global.filePath is null)
global.filePath = new Strings();
global.filePath.push(path.toStringz);
}
/**
Searches for a `dmd.conf`.
Params:
dmdFilePath = path to the current DMD executable
Returns: full path to the found `dmd.conf`, `null` otherwise.
*/
string findDMDConfig(const(char)[] dmdFilePath)
{
import dmd.dinifile : findConfFile;
version (Windows)
enum configFile = "sc.ini";
else
enum configFile = "dmd.conf";
return findConfFile(dmdFilePath, configFile).idup;
}
/**
Searches for a `ldc2.conf`.
Params:
ldcFilePath = path to the current LDC executable
Returns: full path to the found `ldc2.conf`, `null` otherwise.
*/
string findLDCConfig(const(char)[] ldcFilePath)
{
import std.file : getcwd;
import std.path : buildPath, dirName;
import std.algorithm.iteration : filter;
import std.file : exists;
auto execDir = ldcFilePath.dirName;
immutable ldcConfig = "ldc2.conf";
// https://wiki.dlang.org/Using_LDC
auto ldcConfigs = [
getcwd.buildPath(ldcConfig),
execDir.buildPath(ldcConfig),
execDir.dirName.buildPath("etc", ldcConfig),
"~/.ldc".buildPath(ldcConfig),
execDir.buildPath("etc", ldcConfig),
execDir.buildPath("etc", "ldc", ldcConfig),
"/etc".buildPath(ldcConfig),
"/etc/ldc".buildPath(ldcConfig),
].filter!exists;
if (ldcConfigs.empty)
return null;
return ldcConfigs.front;
}
/**
Detect the currently active compiler.
Returns: full path to the executable of the found compiler, `null` otherwise.
*/
string determineDefaultCompiler()
{
import std.algorithm.iteration : filter, joiner, map, splitter;
import std.file : exists;
import std.path : buildPath;
import std.process : environment;
import std.range : front, empty, transposed;
// adapted from DUB: https://github.com/dlang/dub/blob/350a0315c38fab9d3d0c4c9d30ff6bb90efb54d6/source/dub/dub.d#L1183
auto compilers = ["dmd", "gdc", "gdmd", "ldc2", "ldmd2"];
// Search the user's PATH for the compiler binary
if ("DMD" in environment)
compilers = environment.get("DMD") ~ compilers;
auto paths = environment.get("PATH", "").splitter(sep);
auto res = compilers.map!(c => paths.map!(p => p.buildPath(c~exe))).joiner.filter!exists;
return !res.empty ? res.front : null;
}
/**
Parses a `dmd.conf` or `ldc2.conf` config file and returns defined import paths.
Params:
iniFile = iniFile to parse imports from
execDir = directory of the compiler binary
Returns: forward range of import paths found in `iniFile`
*/
auto parseImportPathsFromConfig(const(char)[] iniFile, const(char)[] execDir)
{
import std.algorithm, std.range, std.regex;
import std.stdio : File;
import std.path : buildNormalizedPath;
alias expandConfigVariables = a => a.drop(2) // -I
// "set" common config variables
.replace("%@P%", execDir)
.replace("%%ldcbinarypath%%", execDir);
// search for all -I imports in this file
alias searchForImports = l => l.matchAll(`-I[^ "]+`.regex).joiner.map!expandConfigVariables;
return File(iniFile, "r")
.byLineCopy
.map!searchForImports
.joiner
// remove duplicated imports paths
.array
.sort
.uniq
.map!buildNormalizedPath;
}
/**
Finds a `dmd.conf` and parses it for import paths.
This depends on the `$DMD` environment variable.
If `$DMD` is set to `ldmd`, it will try to detect and parse a `ldc2.conf` instead.
Returns:
A forward range of normalized import paths.
See_Also: $(LREF determineDefaultCompiler), $(LREF parseImportPathsFromConfig)
*/
auto findImportPaths()
{
import std.algorithm.searching : endsWith;
import std.file : exists;
import std.path : dirName;
string execFilePath = determineDefaultCompiler();
assert(execFilePath !is null, "No D compiler found. `Use parseImportsFromConfig` manually.");
immutable execDir = execFilePath.dirName;
string iniFile;
if (execFilePath.endsWith("ldc"~exe, "ldc2"~exe, "ldmd"~exe, "ldmd2"~exe))
iniFile = findLDCConfig(execFilePath);
else
iniFile = findDMDConfig(execFilePath);
assert(iniFile !is null && iniFile.exists, "No valid config found.");
return iniFile.parseImportPathsFromConfig(execDir);
}
/**
Parse a module from a string.
Params:
fileName = file to parse
code = text to use instead of opening the file
Returns: the parsed module object
*/
Tuple!(Module, "module_", Diagnostics, "diagnostics") parseModule(AST = ASTCodegen)(
const(char)[] fileName,
const(char)[] code = null)
{
import dmd.root.file : File, Buffer;
import dmd.globals : global;
import dmd.location;
import dmd.parse : Parser;
import dmd.identifier : Identifier;
import dmd.tokens : TOK;
import std.path : baseName, stripExtension;
import std.string : toStringz;
import std.typecons : tuple;
auto id = Identifier.idPool(fileName.baseName.stripExtension);
auto m = new Module(fileName, id, 0, 0);
if (code is null)
m.read(Loc.initial);
else
{
import dmd.root.filename : FileName;
auto fb = cast(ubyte[]) code.dup ~ '\0';
global.fileManager.add(FileName(fileName), fb);
m.src = fb;
}
m.importedFrom = m;
m = m.parseModule!AST();
Diagnostics diagnostics = {
errors: global.errors,
warnings: global.warnings
};
return typeof(return)(m, diagnostics);
}
/**
Run full semantic analysis on a module.
*/
void fullSemantic(Module m)
{
import dmd.dsymbolsem : dsymbolSemantic;
import dmd.semantic2 : semantic2;
import dmd.semantic3 : semantic3;
m.importedFrom = m;
m.importAll(null);
m.dsymbolSemantic(null);
Module.runDeferredSemantic();
m.semantic2(null);
Module.runDeferredSemantic2();
m.semantic3(null);
Module.runDeferredSemantic3();
}
/**
Pretty print a module.
Returns:
Pretty printed module as string.
*/
string prettyPrint(Module m)
{
import dmd.common.outbuffer: OutBuffer;
import dmd.hdrgen : HdrGenState, moduleToBuffer2;
auto buf = OutBuffer();
buf.doindent = 1;
HdrGenState hgs = { fullDump: 1 };
moduleToBuffer2(m, &buf, &hgs);
import std.string : replace, fromStringz;
import std.exception : assumeUnique;
auto generated = buf.extractSlice.replace("\t", " ");
return generated.assumeUnique;
}
/// Interface for diagnostic reporting.
abstract class DiagnosticReporter
{
import dmd.console : Color;
nothrow:
DiagnosticHandler prevHandler;
this()
{
prevHandler = diagnosticHandler;
diagnosticHandler = &diagHandler;
}
~this()
{
// assumed to be used scoped
diagnosticHandler = prevHandler;
}
bool diagHandler(const ref Loc loc, Color headerColor, const(char)* header,
const(char)* format, va_list ap, const(char)* p1, const(char)* p2)
{
import core.stdc.string;
// recover type from header and color
if (strncmp (header, "Error:", 6) == 0)
return error(loc, format, ap, p1, p2);
if (strncmp (header, "Warning:", 8) == 0)
return warning(loc, format, ap, p1, p2);
if (strncmp (header, "Deprecation:", 12) == 0)
return deprecation(loc, format, ap, p1, p2);
if (cast(Classification)headerColor == Classification.warning)
return warningSupplemental(loc, format, ap, p1, p2);
if (cast(Classification)headerColor == Classification.deprecation)
return deprecationSupplemental(loc, format, ap, p1, p2);
return errorSupplemental(loc, format, ap, p1, p2);
}
/// Returns: the number of errors that occurred during lexing or parsing.
abstract int errorCount();
/// Returns: the number of warnings that occurred during lexing or parsing.
abstract int warningCount();
/// Returns: the number of deprecations that occurred during lexing or parsing.
abstract int deprecationCount();
/**
Reports an error message.
Params:
loc = Location of error
format = format string for error
args = printf-style variadic arguments
p1 = additional message prefix
p2 = additional message prefix
Returns: false if the message should also be printed to stderr, true otherwise
*/
abstract bool error(const ref Loc loc, const(char)* format, va_list args, const(char)* p1, const(char)* p2);
/**
Reports additional details about an error message.
Params:
loc = Location of error
format = format string for supplemental message
args = printf-style variadic arguments
p1 = additional message prefix
p2 = additional message prefix
Returns: false if the message should also be printed to stderr, true otherwise
*/
abstract bool errorSupplemental(const ref Loc loc, const(char)* format, va_list args, const(char)* p1, const(char)* p2);
/**
Reports a warning message.
Params:
loc = Location of warning
format = format string for warning
args = printf-style variadic arguments
p1 = additional message prefix
p2 = additional message prefix
Returns: false if the message should also be printed to stderr, true otherwise
*/
abstract bool warning(const ref Loc loc, const(char)* format, va_list args, const(char)* p1, const(char)* p2);
/**
Reports additional details about a warning message.
Params:
loc = Location of warning
format = format string for supplemental message
args = printf-style variadic arguments
p1 = additional message prefix
p2 = additional message prefix
Returns: false if the message should also be printed to stderr, true otherwise
*/
abstract bool warningSupplemental(const ref Loc loc, const(char)* format, va_list args, const(char)* p1, const(char)* p2);
/**
Reports a deprecation message.
Params:
loc = Location of the deprecation
format = format string for the deprecation
args = printf-style variadic arguments
p1 = additional message prefix
p2 = additional message prefix
Returns: false if the message should also be printed to stderr, true otherwise
*/
abstract bool deprecation(const ref Loc loc, const(char)* format, va_list args, const(char)* p1, const(char)* p2);
/**
Reports additional details about a deprecation message.
Params:
loc = Location of deprecation
format = format string for supplemental message
args = printf-style variadic arguments
p1 = additional message prefix
p2 = additional message prefix
Returns: false if the message should also be printed to stderr, true otherwise
*/
abstract bool deprecationSupplemental(const ref Loc loc, const(char)* format, va_list args, const(char)* p1, const(char)* p2);
}
/**
Diagnostic reporter which prints the diagnostic messages to stderr.
This is usually the default diagnostic reporter.
*/
final class StderrDiagnosticReporter : DiagnosticReporter
{
private const DiagnosticReporting useDeprecated;
private int errorCount_;
private int warningCount_;
private int deprecationCount_;
nothrow:
/**
Initializes this object.
Params:
useDeprecated = indicates how deprecation diagnostics should be
handled
*/
this(DiagnosticReporting useDeprecated)
{
this.useDeprecated = useDeprecated;
}
override int errorCount()
{
return errorCount_;
}
override int warningCount()
{
return warningCount_;
}
override int deprecationCount()
{
return deprecationCount_;
}
override bool error(const ref Loc loc, const(char)* format, va_list args, const(char)* p1, const(char)* p2)
{
errorCount_++;
return false;
}
override bool errorSupplemental(const ref Loc loc, const(char)* format, va_list args, const(char)* p1, const(char)* p2)
{
return false;
}
override bool warning(const ref Loc loc, const(char)* format, va_list args, const(char)* p1, const(char)* p2)
{
warningCount_++;
return false;
}
override bool warningSupplemental(const ref Loc loc, const(char)* format, va_list args, const(char)* p1, const(char)* p2)
{
return false;
}
override bool deprecation(const ref Loc loc, const(char)* format, va_list args, const(char)* p1, const(char)* p2)
{
if (useDeprecated == DiagnosticReporting.error)
errorCount_++;
else
deprecationCount_++;
return false;
}
override bool deprecationSupplemental(const ref Loc loc, const(char)* format, va_list args, const(char)* p1, const(char)* p2)
{
return false;
}
}
|
D
|
a musical notation indicating one half step higher than the note named
a long thin sewing needle with a sharp point
(of something seen or heard) clearly defined
ending in a sharp point
having or demonstrating ability to recognize or draw fine distinctions
marked by practical hardheaded intelligence
harsh
having or emitting a high-pitched and sharp tone or tones
extremely steep
keenly and painfully felt
having or made by a thin edge or sharp point
(of a musical note) raised in pitch by one chromatic semitone
very sudden and in great amount or degree
quick and forceful
changing suddenly in direction and degree
|
D
|
import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric;
int[10^^5*2] BS, WS;
void main()
{
auto N = readln.chomp.to!int;
auto S = readln.chomp;
foreach (i, c; S) {
if (i) {
BS[i] = BS[i-1];
WS[i] = WS[i-1];
}
if (c == '#') {
++BS[i];
} else {
++WS[i];
}
}
int r = int.max;
foreach (i; 0..N+1) {
auto s = WS[N-1];
if (i) {
s -= WS[i-1];
s += BS[i-1];
}
r = min(r, s);
}
writeln(r);
}
|
D
|
template TT(T...) { alias T TT; }
void TestOpAssign(Tx, Ux, ops)()
{
foreach(T; Tx.x)
foreach(U; Ux.x)
foreach(op; ops.x)
{
T a = cast(T)1;
mixin("a " ~ op ~ " cast(U)1;");
}
}
void TestOpAssignAssign(Tx, Ux, ops)()
{
foreach(T; Tx.x)
foreach(U; Ux.x)
foreach(op; ops.x)
{
T a = cast(T)1;
U b = cast(U)1;
T r;
mixin("r = a " ~ op ~ " cast(U)1;");
}
}
void TestOpAssignAuto(Tx, Ux, ops)()
{
foreach(T; Tx.x)
foreach(U; Ux.x)
static if (U.sizeof <= T.sizeof)
foreach(op; ops.x)
{
T a = cast(T)1;
U b = cast(U)1;
mixin("auto r = a " ~ op ~ " cast(U)1;");
}
}
void TestOpAndAssign(Tx, Ux, ops)()
{
foreach(T; Tx.x)
foreach(U; Ux.x)
static if (U.sizeof <= T.sizeof && T.sizeof >= 4)
foreach(op; ops.x)
{
T a = cast(T)1;
U b = cast(U)1;
mixin("a = a " ~ op[0..$-1] ~ " cast(U)1;");
}
}
struct boolean { alias TT!(bool) x; }
struct integral { alias TT!(byte, ubyte, short, ushort, int, uint, long, ulong) x; }
struct floating { alias TT!(float, double, real) x; }
struct imaginary { alias TT!(ifloat, idouble, ireal) x; }
struct complex { alias TT!(cfloat, cdouble, creal) x; }
struct all { alias TT!("+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=") x; }
struct arith { alias TT!("+=", "-=", "*=", "/=", "%=") x; }
struct bitwise { alias TT!("&=", "|=", "^=") x; }
struct shift { alias TT!("<<=", ">>=", ">>>=") x; }
struct addsub { alias TT!("+=", "-=") x; }
struct muldivmod { alias TT!("*=", "/=", "%=") x; }
struct nomod { alias TT!("+=", "-=", "*=", "/=") x; }
void OpAssignCases(alias X)()
{
X!(boolean, boolean, bitwise)();
X!(integral, boolean, all)();
X!(integral, integral, all)();
X!(integral, floating, arith)();
X!(floating, boolean, arith)();
X!(floating, integral, arith)();
X!(floating, floating, arith)();
X!(imaginary, boolean, muldivmod)();
X!(imaginary, integral, muldivmod)();
X!(imaginary, floating, muldivmod)();
X!(imaginary, imaginary, addsub)();
X!(complex, boolean, arith)();
X!(complex, integral, arith)();
X!(complex, floating, arith)();
X!(complex, imaginary, arith)();
X!(complex, complex, nomod)();
}
void OpReAssignCases(alias X)()
{
X!(boolean, boolean, bitwise)();
X!(integral, boolean, all)();
X!(integral, integral, all)();
X!(floating, boolean, arith)();
X!(floating, integral, arith)();
X!(floating, floating, arith)();
X!(imaginary, boolean, muldivmod)();
X!(imaginary, integral, muldivmod)();
X!(imaginary, floating, muldivmod)();
X!(imaginary, imaginary, addsub)();
X!(complex, boolean, arith)();
X!(complex, integral, arith)();
X!(complex, floating, arith)();
X!(complex, imaginary, arith)();
X!(complex, complex, nomod)();
}
void main()
{
OpAssignCases!TestOpAssign();
OpAssignCases!TestOpAssignAssign(); // was once disabled due to bug 7436
OpAssignCases!TestOpAssignAuto(); // 5181
OpReAssignCases!TestOpAndAssign();
}
|
D
|
instance BAU_911_Elena(Npc_Default)
{
name[0] = "Елена";
guild = GIL_BAU;
id = 911;
voice = 16;
flags = 0;
npcType = npctype_main;
B_SetAttributesToChapter(self,2);
fight_tactic = FAI_HUMAN_COWARD;
EquipItem(self,ItMw_1h_Bau_Axe);
B_CreateAmbientInv(self);
B_SetNpcVisual(self,FEMALE,"Hum_Head_Babe",FaceBabe_N_GreyCloth,BodyTexBabe_N,ITAR_BauBabe_L);
Mdl_SetModelFatness(self,0);
Mdl_ApplyOverlayMds(self,"Humans_Babe.mds");
B_GiveNpcTalents(self);
B_SetFightSkills(self,25);
daily_routine = Rtn_Start_911;
};
func void Rtn_Start_911()
{
TA_Stand_ArmsCrossed(7,30,20,30,"NW_BIGFARM_STABLE_OUT_04");
TA_Sit_Throne(20,30,7,30,"NW_BIGFARM_HOUSE_UP1_SESSEL");
};
|
D
|
/Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Fluent.build/Model/SoftDeletable.swift.o : /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/ID.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaSupporting+CRUD.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/Model+CRUD.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+CRUD.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Utilities/Deprecated.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Service/MigrateCommand.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Service/RevertCommand.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Decode.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Range.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/SoftDeletable.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Aggregate.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/MigrationConfig.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Join/JoinSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/MigrationSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Transaction/TransactionSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Query/QuerySupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/MigrationLog.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Model.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/Model.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/AnyModel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Relations/Children.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Join/QueryBuilder+Join.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaSupporting+Migration.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/Migration.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/AnyMigration.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Run.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Service/FluentProvider.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaBuilder.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaUpdater.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Filter.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Utilities/FluentError.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaCreator.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/DatabasesConfig+References.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Relations/Siblings.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/Migrations.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/AnyMigrations.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Operators.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Utilities/Exports.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Relations/Parent.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Service/CommandConfig+Fluent.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Cache/KeyedCacheSupporting+Fluent.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Database/DatabaseConnection+Fluent.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/ModelEvent.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/Pivot.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Sort.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Copy.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Cache/CacheEntry.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Query/FluentProperty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Command.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Service.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Console.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Logging.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/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/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/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 /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/DatabaseKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio-zlib-support/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/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.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/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Fluent.build/Model/SoftDeletable~partial.swiftmodule : /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/ID.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaSupporting+CRUD.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/Model+CRUD.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+CRUD.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Utilities/Deprecated.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Service/MigrateCommand.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Service/RevertCommand.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Decode.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Range.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/SoftDeletable.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Aggregate.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/MigrationConfig.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Join/JoinSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/MigrationSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Transaction/TransactionSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Query/QuerySupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/MigrationLog.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Model.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/Model.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/AnyModel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Relations/Children.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Join/QueryBuilder+Join.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaSupporting+Migration.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/Migration.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/AnyMigration.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Run.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Service/FluentProvider.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaBuilder.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaUpdater.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Filter.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Utilities/FluentError.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaCreator.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/DatabasesConfig+References.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Relations/Siblings.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/Migrations.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/AnyMigrations.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Operators.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Utilities/Exports.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Relations/Parent.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Service/CommandConfig+Fluent.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Cache/KeyedCacheSupporting+Fluent.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Database/DatabaseConnection+Fluent.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/ModelEvent.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/Pivot.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Sort.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Copy.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Cache/CacheEntry.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Query/FluentProperty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Command.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Service.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Console.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Logging.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/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/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/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 /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/DatabaseKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio-zlib-support/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/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.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/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Fluent.build/Model/SoftDeletable~partial.swiftdoc : /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/ID.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaSupporting+CRUD.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/Model+CRUD.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+CRUD.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Utilities/Deprecated.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Service/MigrateCommand.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Service/RevertCommand.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Decode.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Range.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/SoftDeletable.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Aggregate.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/MigrationConfig.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Join/JoinSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/MigrationSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Transaction/TransactionSupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Query/QuerySupporting.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/MigrationLog.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Model.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/Model.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/AnyModel.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Relations/Children.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Join/QueryBuilder+Join.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaSupporting+Migration.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/Migration.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/AnyMigration.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Run.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Service/FluentProvider.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaBuilder.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaUpdater.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Filter.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Utilities/FluentError.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/SchemaCreator.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Schema/DatabasesConfig+References.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Relations/Siblings.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/Migrations.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Migration/AnyMigrations.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Operators.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Utilities/Exports.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Relations/Parent.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Service/CommandConfig+Fluent.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Cache/KeyedCacheSupporting+Fluent.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Database/DatabaseConnection+Fluent.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/ModelEvent.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Model/Pivot.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Sort.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/QueryBuilder/QueryBuilder+Copy.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Cache/CacheEntry.swift /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/fluent/Sources/Fluent/Query/FluentProperty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Command.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Service.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Console.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Logging.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/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/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/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 /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/DatabaseKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/Jorge/Desktop/Projects/Web/Swift/kisiBootcamp/.build/checkouts/swift-nio-zlib-support/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/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.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
|
/** D bindings for GSL.
Authors: Chibisi Chima-Okereke
Copyright: Copyright (c) 2016, Chibisi Chima-Okereke. All rights reserved.
License: Boost License 1.0
*/
module gsl.poly;
//import core.stdc.complex;
import gsl.complex;
extern (C):
struct gsl_poly_complex_workspace
{
size_t nc;
double* matrix;
}
double gsl_poly_eval (const(double)* c, const int len, const double x);
gsl_complex gsl_poly_complex_eval (const(double)* c, const int len, const gsl_complex z);
gsl_complex gsl_complex_poly_complex_eval (const(gsl_complex)* c, const int len, const gsl_complex z);
int gsl_poly_eval_derivs (const(double)* c, const size_t lenc, const double x, double* res, const size_t lenres);
int gsl_poly_dd_init (double* dd, const(double)* x, const(double)* y, size_t size);
double gsl_poly_dd_eval (const(double)* dd, const(double)* xa, const size_t size, const double x);
int gsl_poly_dd_taylor (double* c, double xp, const(double)* dd, const(double)* x, size_t size, double* w);
int gsl_poly_dd_hermite_init (double* dd, double* z, const(double)* xa, const(double)* ya, const(double)* dya, const size_t size);
int gsl_poly_solve_quadratic (double a, double b, double c, double* x0, double* x1);
int gsl_poly_complex_solve_quadratic (double a, double b, double c, gsl_complex* z0, gsl_complex* z1);
int gsl_poly_solve_cubic (double a, double b, double c, double* x0, double* x1, double* x2);
int gsl_poly_complex_solve_cubic (double a, double b, double c, gsl_complex* z0, gsl_complex* z1, gsl_complex* z2);
gsl_poly_complex_workspace* gsl_poly_complex_workspace_alloc (size_t n);
void gsl_poly_complex_workspace_free (gsl_poly_complex_workspace* w);
int gsl_poly_complex_solve (const(double)* a, size_t n, gsl_poly_complex_workspace* w, gsl_complex_packed_ptr z);
|
D
|
/**
This module contains support for controlling dynamic arrays' appending
Copyright: Copyright Digital Mars 2000 - 2019.
License: Distributed under the
$(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0).
(See accompanying file LICENSE)
Source: $(DRUNTIMESRC core/_internal/_array/_appending.d)
*/
module core.internal.array.appending;
/// See $(REF _d_arrayappendcTX, rt,lifetime,_d_arrayappendcTX)
private extern (C) byte[] _d_arrayappendcTX(const TypeInfo ti, ref return scope byte[] px, size_t n) @trusted pure nothrow;
private enum isCopyingNothrow(T) = __traits(compiles, (ref T rhs) nothrow { T lhs = rhs; });
/// Implementation of `_d_arrayappendcTX` and `_d_arrayappendcTXTrace`
template _d_arrayappendcTXImpl(Tarr : T[], T)
{
private enum errorMessage = "Cannot append to array if compiling without support for runtime type information!";
/**
* Extend an array `px` by `n` elements.
* Caller must initialize those elements.
* Params:
* px = the array that will be extended, taken as a reference
* n = how many new elements to extend it with
* Returns:
* The new value of `px`
* Bugs:
* This function template was ported from a much older runtime hook that bypassed safety,
* purity, and throwabilty checks. To prevent breaking existing code, this function template
* is temporarily declared `@trusted pure` until the implementation can be brought up to modern D expectations.
*/
ref Tarr _d_arrayappendcTX(return ref scope Tarr px, size_t n) @trusted pure nothrow
{
// needed for CTFE: https://github.com/dlang/druntime/pull/3870#issuecomment-1178800718
version (DigitalMars) pragma(inline, false);
version (D_TypeInfo)
{
auto ti = typeid(Tarr);
// _d_arrayappendcTX takes the `px` as a ref byte[], but its length
// should still be the original length
auto pxx = (cast(byte*)px.ptr)[0 .. px.length];
._d_arrayappendcTX(ti, pxx, n);
px = (cast(T*)pxx.ptr)[0 .. pxx.length];
return px;
}
else
assert(0, errorMessage);
}
version (D_ProfileGC)
{
import core.internal.array.utils : _d_HookTraceImpl;
/**
* TraceGC wrapper around $(REF _d_arrayappendcTX, rt,array,appending,_d_arrayappendcTXImpl).
* Bugs:
* This function template was ported from a much older runtime hook that bypassed safety,
* purity, and throwabilty checks. To prevent breaking existing code, this function template
* is temporarily declared `@trusted pure` until the implementation can be brought up to modern D expectations.
*/
alias _d_arrayappendcTXTrace = _d_HookTraceImpl!(Tarr, _d_arrayappendcTX, errorMessage);
}
}
/// Implementation of `_d_arrayappendT`
ref Tarr _d_arrayappendT(Tarr : T[], T)(return ref scope Tarr x, scope Tarr y) @trusted
{
version (DigitalMars) pragma(inline, false);
import core.stdc.string : memcpy;
import core.internal.traits : hasElaborateCopyConstructor, Unqual;
enum hasPostblit = __traits(hasPostblit, T);
auto length = x.length;
_d_arrayappendcTXImpl!Tarr._d_arrayappendcTX(x, y.length);
// Only call `copyEmplace` if `T` has a copy ctor and no postblit.
static if (hasElaborateCopyConstructor!T && !hasPostblit)
{
import core.lifetime : copyEmplace;
foreach (i, ref elem; y)
copyEmplace(elem, x[length + i]);
}
else
{
if (y.length)
{
// blit all elements at once
auto xptr = cast(Unqual!T *)&x[length];
immutable size = T.sizeof;
memcpy(xptr, cast(Unqual!T *)&y[0], y.length * size);
// call postblits if they exist
static if (hasPostblit)
{
auto eptr = xptr + y.length;
for (auto ptr = xptr; ptr < eptr; ptr++)
ptr.__xpostblit();
}
}
}
return x;
}
version (D_ProfileGC)
{
/**
* TraceGC wrapper around $(REF _d_arrayappendT, core,internal,array,appending).
*/
ref Tarr _d_arrayappendTTrace(Tarr : T[], T)(string file, int line, string funcname, return ref scope Tarr x, scope Tarr y) @trusted
{
version (D_TypeInfo)
{
import core.internal.array.utils: TraceHook, gcStatsPure, accumulatePure;
mixin(TraceHook!(Tarr.stringof, "_d_arrayappendT"));
return _d_arrayappendT(x, y);
}
else
assert(0, "Cannot append to array if compiling without support for runtime type information!");
}
}
@safe unittest
{
double[] arr1;
foreach (i; 0 .. 4)
_d_arrayappendT(arr1, [cast(double)i]);
assert(arr1 == [0.0, 1.0, 2.0, 3.0]);
}
@safe unittest
{
int blitted;
struct Item
{
this(this)
{
blitted++;
}
}
Item[] arr1 = [Item(), Item()];
Item[] arr2 = [Item(), Item()];
Item[] arr1_org = [Item(), Item()];
arr1_org ~= arr2;
_d_arrayappendT(arr1, arr2);
// postblit should have triggered on at least the items in arr2
assert(blitted >= arr2.length);
}
@safe nothrow unittest
{
int blitted;
struct Item
{
this(this) nothrow
{
blitted++;
}
}
Item[][] arr1 = [[Item()]];
Item[][] arr2 = [[Item()]];
_d_arrayappendT(arr1, arr2);
// no postblit should have happened because arr{1,2} contain dynamic arrays
assert(blitted == 0);
}
@safe nothrow unittest
{
int copied;
struct Item
{
this(const scope ref Item) nothrow
{
copied++;
}
}
Item[1][] arr1 = [[Item()]];
Item[1][] arr2 = [[Item()]];
_d_arrayappendT(arr1, arr2);
// copy constructor should have been invoked because arr{1,2} contain static arrays
assert(copied >= arr2.length);
}
@safe nothrow unittest
{
string str;
_d_arrayappendT(str, "a");
_d_arrayappendT(str, "b");
_d_arrayappendT(str, "c");
assert(str == "abc");
}
|
D
|
module dgl.ext.NV_vertex_program4;
import dgl.opengl;
import dgl.glext;
version( D_Version2 ) {
import std.string : containsPattern = count;
import std.conv;
} else {
import tango.text.Util : containsPattern;
import tango.stdc.stringz : fromStringz;
alias char[] string;
}
private ushort extensionId__ = 28;
alias extensionId__ NV_vertex_program4;
import dgl.ext.NV_gpu_program4;
version (DglNoExtSupportAsserts) {
} else {
version = DglExtSupportAsserts;
}
static this() {
if (__extSupportCheckingFuncs.length <= extensionId__) {
__extSupportCheckingFuncs.length = extensionId__ + 1;
}
__extSupportCheckingFuncs[extensionId__] = &__supported;
}
version (all) {
public {
}
private {
extern (System) {
}
}
public {
}
private final bool __supported(GL gl_) {
auto gl = _getGL(gl_);
if (extensionId__ < cast(int)gl.extFuncs.length && gl.extFuncs[extensionId__] !is null) {
return gl.extFuncs[extensionId__][0] !is null;
}
synchronized (gl) {
if (extensionId__ < cast(int)gl.extFuncs.length && gl.extFuncs[extensionId__] !is null) {
return gl.extFuncs[extensionId__][0] !is null;
}
if (gl.extFuncs.length <= extensionId__) {
gl.extFuncs.length = extensionId__ + 1;
version (DglExtSupportAsserts) {
gl.extEnabled.length = extensionId__ + 1;
}
}
gl.extFuncs[extensionId__] = loadFunctions__(gl_);
return gl.extFuncs[extensionId__][0] !is null;
}
}
private void*[] loadFunctions__(GL gl) {
void*[] funcAddr = new void*[1];
{
char* extP = gl.GetString(GL_EXTENSIONS);
version( D_Version2 ) {
string extStr = extP is null ? null : to!(string)(extP);
} else {
string extStr = extP is null ? null : fromStringz(extP);
}
if (!extStr.containsPattern("GL_NV_vertex_program4")) { funcAddr[0] = null; return funcAddr; }
}
funcAddr[0] = cast(void*)≷
return funcAddr;
}
}
else {
private final bool __supported(GL gl_) {
return false;
}
}
|
D
|
module test;
import std.stdio;
public {
import std.file : read;
import std.string : format, strip;
}
import std.array : split, join, empty;
import std.algorithm : startsWith, endsWith;
import std.c.string : memcpy;
bool isEmpty(string test) {
return test.strip().empty();
}
private void _foo() { }
string fmt() {
string str = "one\nnew line";
{
string str_;
str = "abc";
}
void* p;
std.c.string.memcpy(p, &str, str.sizeof);
return format("%d.%d.%d", 0, 9, 9);
}
@property
const(string) bar() pure {
return "";
}
void main() {
}
|
D
|
//-----------------------------------------------------------------------------
// wxD/Samples - HtmlListBox.d
//
// wxD "HtmlListBox" sample.
//
// Written by Alexander Olk (xenomorph2@onlinehome.de)
// Modified by BERO <berobero@users.sourceforge.net>
// (C) 2004 by Alexander Olk
// Licensed under the wxWidgets license, see LICENSE.txt for details.
//
// $Id: HtmlListBox.d,v 1.10 2008/04/24 07:18:58 afb Exp $
//-----------------------------------------------------------------------------
import wx.wx;
private import std.string;
public class MyHtmlListBox : HtmlListBox
{
//---------------------------------------------------------------------
protected bool m_change;
//---------------------------------------------------------------------
public this( Window parent )
{ this( parent, false ); }
public this( Window parent, bool multi )
{
super( parent, -1, wxDefaultPosition, wxDefaultSize, multi ? ListBox.wxLB_MULTIPLE : 0 );
m_change = true;
SetMargins( 5, 5 );
ItemCount = 1000;
Selection = 3;
}
//---------------------------------------------------------------------
public void ChangeSelFg(bool value)
{
m_change = value;
}
//---------------------------------------------------------------------
private static char[] tohex(ubyte value) {
char buf[2];
buf[0] = hexdigits[value/16];
buf[1] = hexdigits[value%16];
return buf.dup;
}
private static uint abs(int value) { return value<0?-value:value; }
protected override string OnGetItem( int n )
{
int level = ( n % 6 ) + 1;
return std.string.format("<h%d><font color=#%02x%02x%02x>Item</font> <b>%d</b></h%d>",
level,
abs(n - 192) % 256,
abs(n - 256) % 256,
abs(n - 128) % 256,
n,level
);
}
//---------------------------------------------------------------------
protected override void OnDrawSeparator( DC dc, Rectangle rect, int n )
{
MyFrame mp = cast(MyFrame)Parent;
if ( mp.menuBar.IsChecked( MyFrame.Cmd.HtmlLbox_DrawSeparator ) )
{
dc.pen = Pen.wxBLACK_DASHED_PEN;
dc.DrawLine( rect.X, rect.Y, rect.Right - 1, rect.Y );
dc.DrawLine( rect.X, rect.Bottom - 1, rect.Right - 1, rect.Bottom - 1 );
}
}
//---------------------------------------------------------------------
protected override Colour GetSelectedTextColour( Colour colFg )
{
return m_change ? super.GetSelectedTextColour( colFg ) : colFg;
}
}
//---------------------------------------------------------------------
public class MyFrame : Frame
{
public enum Cmd { HtmlLbox_Quit,
HtmlLbox_SetMargins,
HtmlLbox_DrawSeparator,
HtmlLbox_ToggleMulti,
HtmlLbox_SelectAll,
HtmlLbox_SetBgCol,
HtmlLbox_SetSelBgCol,
HtmlLbox_SetSelFgCol,
HtmlLbox_About = wxID_ABOUT }
//---------------------------------------------------------------------
private MyHtmlListBox m_hlbox;
//---------------------------------------------------------------------
public this( Window parent, string title, Point pos, Size size )
{
super( parent, -1, title, pos, size );
icon = new Icon( "./data/mondrian.png" );
Menu menuFile = new Menu();
menuFile.Append( Cmd.HtmlLbox_Quit, "E&xit\tAlt-X", "Quit this program" );
Menu menuHLbox = new Menu();
menuHLbox.Append( Cmd.HtmlLbox_SetMargins, "Set &margins...\tCtrl-G", "Change the margins around the items" );
menuHLbox.AppendCheckItem( Cmd.HtmlLbox_DrawSeparator, "&Draw separators\tCtrl-D", "Toggle drawing separators between cells" );
menuHLbox.AppendSeparator();
menuHLbox.AppendCheckItem( Cmd.HtmlLbox_ToggleMulti, "&Multiple selection\tCtrl-M", "Toggle multiple selection on/off" );
menuHLbox.AppendSeparator();
menuHLbox.Append( Cmd.HtmlLbox_SelectAll, "Select &all items\tCtrl-A" );
menuHLbox.AppendSeparator();
menuHLbox.Append( Cmd.HtmlLbox_SetBgCol, "Set &background...\tCtrl-B" );
menuHLbox.Append( Cmd.HtmlLbox_SetSelBgCol, "Set &selection background...\tCtrl-S" );
menuHLbox.AppendCheckItem( Cmd.HtmlLbox_SetSelFgCol, "Keep &foreground in selection\tCtrl-F" );
Menu helpMenu = new Menu();
helpMenu.Append( Cmd.HtmlLbox_About, "&About...\tF1", "Show about dialog" );
MenuBar menuBar = new MenuBar();
menuBar.Append( menuFile, "&File" );
menuBar.Append( menuHLbox, "&Listbox" );
menuBar.Append( helpMenu, "&Help" );
menuBar.Check( Cmd.HtmlLbox_DrawSeparator, true );
this.menuBar = menuBar;
CreateStatusBar( 2 );
StatusText = "Welcome to wxWidgets!";
m_hlbox = new MyHtmlListBox( this );
TextCtrl text = new TextCtrl( this, -1, "", wxDefaultPosition, wxDefaultSize, TextCtrl.wxTE_MULTILINE );
Log.SetActiveTarget( text );
BoxSizer sizer = new BoxSizer( Orientation.wxHORIZONTAL );
sizer.Add( m_hlbox, 1, Stretch.wxGROW );
sizer.Add( text, 1, Stretch.wxGROW );
this.sizer = sizer;
EVT_MENU( Cmd.HtmlLbox_Quit, & OnQuit ) ;
EVT_MENU( Cmd.HtmlLbox_SetMargins, & OnSetMargins ) ;
EVT_MENU( Cmd.HtmlLbox_DrawSeparator, & OnDrawSeparator ) ;
EVT_MENU( Cmd.HtmlLbox_ToggleMulti, & OnToggleMulti ) ;
EVT_MENU( Cmd.HtmlLbox_SelectAll, & OnSelectAll ) ;
EVT_MENU( Cmd.HtmlLbox_About, & OnAbout ) ;
EVT_MENU( Cmd.HtmlLbox_SetBgCol, & OnSetBgCol ) ;
EVT_MENU( Cmd.HtmlLbox_SetSelBgCol, & OnSetSelBgCol ) ;
EVT_MENU( Cmd.HtmlLbox_SetSelFgCol, & OnSetSelFgCol ) ;
EVT_UPDATE_UI( Cmd.HtmlLbox_SelectAll, & OnUpdateUISelectAll ) ;
EVT_LISTBOX( wxID_ANY, & OnLboxSelect ) ;
EVT_LISTBOX_DCLICK( wxID_ANY, & OnLboxDClick ) ;
}
//---------------------------------------------------------------------
public void OnQuit( Object sender, Event e )
{
Close();
}
//---------------------------------------------------------------------
public void OnAbout( Object sender, Event e )
{
MessageBox( this, "This sample shows wxHtmlListBox class.\n"
"\n"
"(c) 2003 Vadim Zeitlin\n"
"Ported to wxD by BERO", "About HtmlLbox", Dialog.wxOK | Dialog.wxICON_INFORMATION );
}
//---------------------------------------------------------------------
public void OnSetMargins( Object sender, Event e )
{
long margin = GetNumberFromUser(
"Enter the margins to use for the listbox items.",
"Margin: ",
"HtmlLbox: Set the margins",
0, 0, 20,
this
);
if ( margin != -1 )
{
m_hlbox.SetMargins( margin, margin );
m_hlbox.RefreshAll();
}
}
//---------------------------------------------------------------------
public void OnDrawSeparator( Object sender, Event e )
{
m_hlbox.RefreshAll();
}
//---------------------------------------------------------------------
public void OnToggleMulti( Object sender, Event e )
{
CommandEvent evt = cast(CommandEvent) e;
Sizer sizer = this.sizer;
sizer.Detach( m_hlbox );
m_hlbox = new MyHtmlListBox( this, evt.IsChecked );
sizer.Prepend( m_hlbox, 1, Stretch.wxGROW, 0, null );
sizer.Layout();
}
//---------------------------------------------------------------------
public void OnSelectAll( Object sender, Event e )
{
m_hlbox.SelectAll();
}
//---------------------------------------------------------------------
public void OnSetBgCol( Object sender, Event e )
{
ColourData data = new ColourData();
data.colour = m_hlbox.BackgroundColour;
data.ChooseFull = true;
ColourDialog cd = new ColourDialog( this, data );
cd.Title = "Choose the background colour";
if ( cd.ShowModal() == wxID_OK )
{
Colour col = cd.colourData.colour;
if ( col.Ok() )
{
m_hlbox.BackgroundColour = col;
m_hlbox.Refresh();
StatusText = "Background colour changed.";
}
}
}
//---------------------------------------------------------------------
public void OnSetSelBgCol( Object sender, Event e )
{
ColourData data = new ColourData();
data.colour = m_hlbox.BackgroundColour;
data.ChooseFull = true;
ColourDialog cd = new ColourDialog( this, data );
cd.Title = "Choose the selection background colour";
if ( cd.ShowModal() == wxID_OK )
{
Colour col = cd.colourData.colour;
if ( col.Ok() )
{
m_hlbox.SelectionBackground = col;
m_hlbox.Refresh();
StatusText = "Selection background colour changed.";
}
}
}
//---------------------------------------------------------------------
public void OnSetSelFgCol( Object sender, Event e )
{
CommandEvent evt = cast(CommandEvent) e;
m_hlbox.ChangeSelFg = !evt.IsChecked;
m_hlbox.Refresh();
}
//---------------------------------------------------------------------
public void OnUpdateUISelectAll( Object sender, Event e )
{
UpdateUIEvent evt = cast(UpdateUIEvent) e;
evt.Enabled = m_hlbox && m_hlbox.HasMultipleSelection;
}
//---------------------------------------------------------------------
public void OnLboxSelect( Object sender, Event e )
{
CommandEvent evt = cast(CommandEvent) e;
Log.LogMessage( "Listbox selection is now {0}.", evt.Int );
if ( m_hlbox.HasMultipleSelection )
{
string s = "";
bool first = true;
uint cookie = 0;
for ( int item = m_hlbox.GetFirstSelected( cookie ); item != -1/*wxNOT_FOUND*/; item = m_hlbox.GetNextSelected( cookie ) )
{
if ( first )
{
first = false;
}
else
{
s ~= ", ";
}
s ~= std.string.toString(item);
}
if ( s.length > 0 )
Log.LogMessage( "Selected items: {0}", s );
}
StatusText = "# items selected = " ~ .toString(m_hlbox.SelectedCount);
}
//---------------------------------------------------------------------
public void OnLboxDClick( Object sender, Event e )
{
CommandEvent evt = cast(CommandEvent) e;
Log.LogMessage( "Listbox item {0} double clicked.", evt.Int );
}
}
//---------------------------------------------------------------------
public class HTLBox : App
{
public override bool OnInit()
{
MyFrame frame = new MyFrame( null, "HtmListBox sample", Point( -1, -1 ), Size( 400, 500 ) );
frame.Show( true );
return true;
}
//---------------------------------------------------------------------
static void Main()
{
HTLBox app = new HTLBox();
app.Run();
}
}
void main()
{
HTLBox.Main();
}
|
D
|
/*
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.
*/
module derelict.glib.glist;
import derelict.glib.gtypes;
import derelict.glib.glibconfig;
import derelict.glib.gnode;
extern (C):
alias _GList GList;
struct _GList
{
gpointer data;
GList* next;
GList* prev;
}
version(Derelict_Link_Static)
{
extern( C ) nothrow
{
GList* g_list_alloc();
void g_list_free(GList* list);
void g_list_free_1(GList* list);
void g_list_free_full(GList* list, GDestroyNotify free_func);
GList* g_list_append(GList* list, gpointer data);
GList* g_list_prepend(GList* list, gpointer data);
GList* g_list_insert(GList* list, gpointer data, gint position);
GList* g_list_insert_sorted(GList* list, gpointer data, GCompareFunc func);
GList* g_list_insert_sorted_with_data(GList* list, gpointer data, GCompareDataFunc func, gpointer user_data);
GList* g_list_insert_before(GList* list, GList* sibling, gpointer data);
GList* g_list_concat(GList* list1, GList* list2);
GList* g_list_remove(GList* list, gconstpointer data);
GList* g_list_remove_all(GList* list, gconstpointer data);
GList* g_list_remove_link(GList* list, GList* llink);
GList* g_list_delete_link(GList* list, GList* link_);
GList* g_list_reverse(GList* list);
GList* g_list_copy(GList* list);
GList* g_list_copy_deep(GList *list, GCopyFunc func, gpointer user_data);
GList* g_list_nth(GList* list, guint n);
GList* g_list_nth_prev(GList* list, guint n);
GList* g_list_find(GList* list, gconstpointer data);
GList* g_list_find_custom(GList* list, gconstpointer data, GCompareFunc func);
gint g_list_position(GList* list, GList* llink);
gint g_list_index(GList* list, gconstpointer data);
GList* g_list_last(GList* list);
GList* g_list_first(GList* list);
guint g_list_length(GList* list);
void g_list_foreach(GList* list, GFunc func, gpointer user_data);
GList* g_list_sort(GList* list, GCompareFunc compare_func);
GList* g_list_sort_with_data(GList* list, GCompareDataFunc compare_func, gpointer user_data);
gpointer g_list_nth_data(GList* list, guint n);
}
}
else
{
extern( C ) nothrow
{
alias da_g_list_alloc = GList* function();
alias da_g_list_free = void function(GList* list);
alias da_g_list_free_1 = void function(GList* list);
alias da_g_list_free_full = void function(GList* list, GDestroyNotify free_func);
alias da_g_list_append = GList* function(GList* list, gpointer data);
alias da_g_list_prepend = GList* function(GList* list, gpointer data);
alias da_g_list_insert = GList* function(GList* list, gpointer data, gint position);
alias da_g_list_insert_sorted = GList* function(GList* list, gpointer data, GCompareFunc func);
alias da_g_list_insert_sorted_with_data = GList* function(GList* list, gpointer data, GCompareDataFunc func, gpointer user_data);
alias da_g_list_insert_before = GList* function(GList* list, GList* sibling, gpointer data);
alias da_g_list_concat = GList* function(GList* list1, GList* list2);
alias da_g_list_remove = GList* function(GList* list, gconstpointer data);
alias da_g_list_remove_all = GList* function(GList* list, gconstpointer data);
alias da_g_list_remove_link = GList* function(GList* list, GList* llink);
alias da_g_list_delete_link = GList* function(GList* list, GList* link_);
alias da_g_list_reverse = GList* function(GList* list);
alias da_g_list_copy = GList* function(GList* list);
alias da_g_list_copy_deep = GList* function(GList *list, GCopyFunc func, gpointer user_data);
alias da_g_list_nth = GList* function(GList* list, guint n);
alias da_g_list_nth_prev = GList* function(GList* list, guint n);
alias da_g_list_find = GList* function(GList* list, gconstpointer data);
alias da_g_list_find_custom = GList* function(GList* list, gconstpointer data, GCompareFunc func);
alias da_g_list_position = gint function(GList* list, GList* llink);
alias da_g_list_index = gint function(GList* list, gconstpointer data);
alias da_g_list_last = GList* function(GList* list);
alias da_g_list_first = GList* function(GList* list);
alias da_g_list_length = guint function(GList* list);
alias da_g_list_foreach = void function(GList* list, GFunc func, gpointer user_data);
alias da_g_list_sort = GList* function(GList* list, GCompareFunc compare_func);
alias da_g_list_sort_with_data = GList* function(GList* list, GCompareDataFunc compare_func, gpointer user_data);
alias da_g_list_nth_data = gpointer function(GList* list, guint n);
}
__gshared
{
da_g_list_alloc g_list_alloc;
da_g_list_free g_list_free;
da_g_list_free_1 g_list_free_1;
da_g_list_free_full g_list_free_full;
da_g_list_append g_list_append;
da_g_list_prepend g_list_prepend;
da_g_list_insert g_list_insert;
da_g_list_insert_sorted g_list_insert_sorted;
da_g_list_insert_sorted_with_data g_list_insert_sorted_with_data;
da_g_list_insert_before g_list_insert_before;
da_g_list_concat g_list_concat;
da_g_list_remove g_list_remove;
da_g_list_remove_all g_list_remove_all;
da_g_list_remove_link g_list_remove_link;
da_g_list_delete_link g_list_delete_link;
da_g_list_reverse g_list_reverse;
da_g_list_copy g_list_copy;
da_g_list_copy_deep g_list_copy_deep;
da_g_list_nth g_list_nth;
da_g_list_nth_prev g_list_nth_prev;
da_g_list_find g_list_find;
da_g_list_find_custom g_list_find_custom;
da_g_list_position g_list_position;
da_g_list_index g_list_index;
da_g_list_last g_list_last;
da_g_list_first g_list_first;
da_g_list_length g_list_length;
da_g_list_foreach g_list_foreach;
da_g_list_sort g_list_sort;
da_g_list_sort_with_data g_list_sort_with_data;
da_g_list_nth_data g_list_nth_data;
}
}
|
D
|
/Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/HTTP.build/Status/Status.swift.o : /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Async/Response+Async.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Method/Method.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Messages/Message.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Response/ResponseRepresentable.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Body/BodyRepresentable.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Messages/Message+CustomStringConvertible.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Middleware/Middleware.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Response/Response.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Middleware/Middleware+Chaining.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Method/Method+String.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Chunk/Response+Chunk.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Chunk/Body+Chunk.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Chunk/ChunkStream.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Version/Version.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/FoundationClient/URI+Foundation.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/FoundationClient/Response+Foundation.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/FoundationClient/Client+Foundation.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/FoundationClient/Request+Foundation.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Responder/Responder.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Responder/AsyncResponder.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/AsyncServerWorker.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Parser/CHTTPParser.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Parser/ResponseParser.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Parser/RequestParser.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/Server.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/TCPServer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/TLSServer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/BasicServer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/AsyncServer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Serializer/Serializer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Serializer/ResponseSerializer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Serializer/RequestSerializer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Parser/ParserError.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/ServerError.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Serializer/SerializerError.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Body/Body+Bytes.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Headers/Headers.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Parser/ParseResults.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Status/Status.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Response/Response+Redirect.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Client/HTTP+Client.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Client/Client.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Request/Request.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/ThreadsafeArray.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Body/Body.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/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/URI.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/TLS.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/libc.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.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/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Random.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/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Sockets.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Bits.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/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Transport.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/CHTTP/include/http_parser.h /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/ctls.git-9210868160426949823/module.modulemap /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/CHTTP.build/module.modulemap /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/CSQLite.build/module.modulemap /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/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/HTTP.build/Status~partial.swiftmodule : /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Async/Response+Async.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Method/Method.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Messages/Message.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Response/ResponseRepresentable.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Body/BodyRepresentable.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Messages/Message+CustomStringConvertible.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Middleware/Middleware.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Response/Response.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Middleware/Middleware+Chaining.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Method/Method+String.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Chunk/Response+Chunk.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Chunk/Body+Chunk.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Chunk/ChunkStream.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Version/Version.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/FoundationClient/URI+Foundation.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/FoundationClient/Response+Foundation.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/FoundationClient/Client+Foundation.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/FoundationClient/Request+Foundation.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Responder/Responder.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Responder/AsyncResponder.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/AsyncServerWorker.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Parser/CHTTPParser.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Parser/ResponseParser.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Parser/RequestParser.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/Server.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/TCPServer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/TLSServer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/BasicServer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/AsyncServer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Serializer/Serializer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Serializer/ResponseSerializer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Serializer/RequestSerializer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Parser/ParserError.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/ServerError.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Serializer/SerializerError.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Body/Body+Bytes.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Headers/Headers.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Parser/ParseResults.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Status/Status.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Response/Response+Redirect.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Client/HTTP+Client.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Client/Client.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Request/Request.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/ThreadsafeArray.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Body/Body.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/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/URI.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/TLS.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/libc.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.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/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Random.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/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Sockets.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Bits.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/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Transport.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/CHTTP/include/http_parser.h /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/ctls.git-9210868160426949823/module.modulemap /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/CHTTP.build/module.modulemap /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/CSQLite.build/module.modulemap /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/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/HTTP.build/Status~partial.swiftdoc : /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Async/Response+Async.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Method/Method.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Messages/Message.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Response/ResponseRepresentable.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Body/BodyRepresentable.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Messages/Message+CustomStringConvertible.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Middleware/Middleware.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Response/Response.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Middleware/Middleware+Chaining.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Method/Method+String.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Chunk/Response+Chunk.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Chunk/Body+Chunk.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Chunk/ChunkStream.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Version/Version.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/FoundationClient/URI+Foundation.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/FoundationClient/Response+Foundation.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/FoundationClient/Client+Foundation.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/FoundationClient/Request+Foundation.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Responder/Responder.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Responder/AsyncResponder.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/AsyncServerWorker.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Parser/CHTTPParser.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Parser/ResponseParser.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Parser/RequestParser.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/Server.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/TCPServer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/TLSServer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/BasicServer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/AsyncServer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Serializer/Serializer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Serializer/ResponseSerializer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Serializer/RequestSerializer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Parser/ParserError.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/ServerError.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Serializer/SerializerError.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Body/Body+Bytes.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Headers/Headers.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Parser/ParseResults.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Status/Status.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Response/Response+Redirect.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Client/HTTP+Client.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Client/Client.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Request/Request.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Server/ThreadsafeArray.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/HTTP/Body/Body.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/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/URI.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/TLS.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/libc.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.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/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Random.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/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Sockets.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Bits.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/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Transport.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/engine.git-3311994267206676365/Sources/CHTTP/include/http_parser.h /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/ctls.git-9210868160426949823/module.modulemap /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/CHTTP.build/module.modulemap /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/CSQLite.build/module.modulemap /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
|
instance MENU_STATUS(C_MENU_DEF)
{
//
// Spielername und Gilde
//
items[0] = "MENU_ITEM_PLAYERGUILD_TITLE";
items[1] = "MENU_ITEM_PLAYERGUILD";
//
// Level und Erfahrung
//
items[2] = "MENU_ITEM_LEVEL_TITLE";
items[3] = "MENU_ITEM_EXP_TITLE";
items[4] = "MENU_ITEM_LEVEL_NEXT_TITLE";
items[5] = "MENU_ITEM_LEARN_TITLE";
items[6] = "MENU_ITEM_LEVEL";
items[7] = "MENU_ITEM_EXP";
items[8] = "MENU_ITEM_LEVEL_NEXT";
items[9] = "MENU_ITEM_LEARN";
//
// Attribute
//
items[10] = "MENU_ITEM_ATTRIBUTE_HEADING";
items[11] = "MENU_ITEM_ATTRIBUTE_1_TITLE";
items[12] = "MENU_ITEM_ATTRIBUTE_2_TITLE";
items[13] = "MENU_ITEM_ATTRIBUTE_3_TITLE";
items[14] = "MENU_ITEM_ATTRIBUTE_4_TITLE";
items[15] = "MENU_ITEM_ATTRIBUTE_1";
items[16] = "MENU_ITEM_ATTRIBUTE_2";
items[17] = "MENU_ITEM_ATTRIBUTE_3";
items[18] = "MENU_ITEM_ATTRIBUTE_4";
//
// Schutz
//
items[19] = "MENU_ITEM_ARMOR_HEADING";
items[20] = "MENU_ITEM_ARMOR_1_TITLE";
items[21] = "MENU_ITEM_ARMOR_2_TITLE";
items[22] = "MENU_ITEM_ARMOR_3_TITLE";
items[23] = "MENU_ITEM_ARMOR_4_TITLE";
items[24] = "MENU_ITEM_ARMOR_1";
items[25] = "MENU_ITEM_ARMOR_2";
items[26] = "MENU_ITEM_ARMOR_3";
items[27] = "MENU_ITEM_ARMOR_4";
//
// Waffentalente
//
// Ueberschriften
items[28] = "MENU_ITEM_TALENTS_WEAPON_HEADING";
items[29] = "MENU_ITEM_TALENTS_THIEF_HEADING";
items[30] = "MENU_ITEM_TALENTS_MAGIC_HEADING";
// Talent-Liste
items[31] = "MENU_ITEM_TALENT_1_TITLE";
items[32] = "MENU_ITEM_TALENT_1_SKILL";
items[33] = "MENU_ITEM_TALENT_1";
items[34] = "MENU_ITEM_TALENT_2_TITLE";
items[35] = "MENU_ITEM_TALENT_2_SKILL";
items[36] = "MENU_ITEM_TALENT_2";
items[37] = "MENU_ITEM_TALENT_3_TITLE";
items[38] = "MENU_ITEM_TALENT_3_SKILL";
items[39] = "MENU_ITEM_TALENT_3";
items[40] = "MENU_ITEM_TALENT_4_TITLE";
items[41] = "MENU_ITEM_TALENT_4_SKILL";
items[42] = "MENU_ITEM_TALENT_4";
items[43] = "MENU_ITEM_TALENT_5_TITLE";
items[44] = "MENU_ITEM_TALENT_5_SKILL";
items[45] = "MENU_ITEM_TALENT_5";
items[46] = "MENU_ITEM_TALENT_6_TITLE";
items[47] = "MENU_ITEM_TALENT_6_SKILL";
items[48] = "MENU_ITEM_TALENT_6";
items[49] = "MENU_ITEM_TALENT_7_TITLE";
items[50] = "MENU_ITEM_TALENT_7_SKILL";
items[51] = "MENU_ITEM_TALENT_8_TITLE";
items[52] = "MENU_ITEM_TALENT_8_SKILL";
items[53] = "MENU_ITEM_TALENT_9_TITLE";
items[54] = "MENU_ITEM_TALENT_9_SKILL";
items[55] = "MENU_ITEM_TALENT_10_TITLE";
items[56] = "MENU_ITEM_TALENT_10_SKILL";
items[57] = "MENU_ITEM_TALENT_11_TITLE";
items[58] = "MENU_ITEM_TALENT_11_SKILL";
items[59] = "MENU_ITEM_TALENT_12_TITLE";
items[60] = "MENU_ITEM_TALENT_12_SKILL";
items[61] = "MENU_ITEM_TALENT_13_TITLE";
items[62] = "MENU_ITEM_TALENT_13_SKILL";
items[63] = "MENU_ITEM_TALENT_14_TITLE";
items[64] = "MENU_ITEM_TALENT_14_SKILL";
items[65] = "MENU_ITEM_TALENT_15_TITLE";
items[66] = "MENU_ITEM_TALENT_15_SKILL";
items[67] = "MENU_ITEM_TALENTS_WORK_HEADING";
//
// Eigenschaften
//
dimx = 8192;
dimy = 8192;
flags = flags | MENU_OVERTOP|MENU_NOANI;
backPic = STAT_BACK_PIC;
};
const int STAT_DY = 300;
//
// Spiel- und Spielerdaten
//
const int STAT_PLY_Y = 900;
const int STAT_ATR_Y = 2700;
const int STAT_ARM_Y = 4800;
const int STAT_TAL_Y = 900;
const int STAT_A_X1 = 700;
const int STAT_A_X2 = 1500;
const int STAT_A_X3 = 2500;
const int STAT_B_X1 = 3500;
const int STAT_B_X2 = 5700;
const int STAT_B_X3 = 7200;
instance MENU_ITEM_PLAYERGUILD_TITLE(C_MENU_ITEM_DEF)
{
// text[0] = "Gilde:";
text[0] = "Společ.:";
posx = STAT_A_X1; posy = STAT_PLY_Y+STAT_DY*0; fontName = STAT_FONT_TITLE;
flags = flags & ~IT_SELECTABLE;
};
instance MENU_ITEM_PLAYERGUILD(C_MENU_ITEM_DEF)
{
posx = STAT_A_X2; posy = STAT_PLY_Y+STAT_DY*0;
dimx = STAT_B_X1 - STAT_A_X2;
dimy = STAT_DY;
fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
//
// Sonderattribute-Werte
//
// Texte
INSTANCE MENU_ITEM_LEVEL_TITLE(C_MENU_ITEM_DEF)
{
posx = STAT_A_X1; posy = STAT_PLY_Y + 1*STAT_DY;
// text[0] = "Stufe"; fontName = STAT_FONT_TITLE;
text[0] = "Úroveň"; fontName = STAT_FONT_TITLE;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_EXP_TITLE(C_MENU_ITEM_DEF)
{
posx = STAT_A_X1; posy = STAT_PLY_Y + 3*STAT_DY;
// text[0] = "Erfahrung"; fontName = STAT_FONT_DEFAULT;
text[0] = "Zkušenost"; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_LEVEL_NEXT_TITLE(C_MENU_ITEM_DEF)
{
posx = STAT_A_X1; posy = STAT_PLY_Y + 4*STAT_DY;
// text[0] = "Nächste Stufe"; fontName = STAT_FONT_DEFAULT;
text[0] = "Další úroveň"; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_LEARN_TITLE(C_MENU_ITEM_DEF)
{
posx = STAT_A_X1; posy = STAT_PLY_Y + 5*STAT_DY;
// text[0] = "Lernpunkte"; fontName = STAT_FONT_DEFAULT;
text[0] = "Zkuš. body"; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
// Werte
INSTANCE MENU_ITEM_LEVEL(C_MENU_ITEM_DEF)
{
posx = STAT_A_X3; posy = STAT_PLY_Y + 1*STAT_DY; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_EXP(C_MENU_ITEM_DEF)
{
posx = STAT_A_X3; posy = STAT_PLY_Y + 3*STAT_DY; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_LEVEL_NEXT(C_MENU_ITEM_DEF)
{
posx = STAT_A_X3; posy = STAT_PLY_Y + 4*STAT_DY; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_LEARN(C_MENU_ITEM_DEF)
{
posx = STAT_A_X3; posy = STAT_PLY_Y + 5*STAT_DY; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
//
// Attribute
//
// Titel
INSTANCE MENU_ITEM_ATTRIBUTE_HEADING(C_MENU_ITEM_DEF)
{
posx = STAT_A_X1; posy = STAT_ATR_Y + 1*STAT_DY;
// text[0] = "Attribute:"; fontName = STAT_FONT_TITLE;
text[0] = "VLASTNOSTI"; fontName = STAT_FONT_TITLE;
flags = flags & ~IT_SELECTABLE;
};
// Texte
INSTANCE MENU_ITEM_ATTRIBUTE_1_TITLE(C_MENU_ITEM_DEF)
{
posx = STAT_A_X1; posy = STAT_ATR_Y + 2*STAT_DY;
// text[0] = "Stärke"; fontName = STAT_FONT_DEFAULT;
text[0] = "Síla"; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_ATTRIBUTE_2_TITLE(C_MENU_ITEM_DEF)
{
posx = STAT_A_X1; posy = STAT_ATR_Y + 3*STAT_DY;
// text[0] = "Geschick"; fontName = STAT_FONT_DEFAULT;
text[0] = "Obratnost"; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_ATTRIBUTE_3_TITLE(C_MENU_ITEM_DEF)
{
posx = STAT_A_X1; posy = STAT_ATR_Y + 4*STAT_DY;
// text[0] = "Mana"; fontName = STAT_FONT_DEFAULT;
text[0] = "Mana"; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_ATTRIBUTE_4_TITLE(C_MENU_ITEM_DEF)
{
posx = STAT_A_X1; posy = STAT_ATR_Y + 5*STAT_DY;
// text[0] = "Gesundheit"; fontName = STAT_FONT_DEFAULT;
text[0] = "Zdraví"; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
// Werte
INSTANCE MENU_ITEM_ATTRIBUTE_1(C_MENU_ITEM_DEF)
{
posx = STAT_A_X3 - 300; posy = STAT_ATR_Y + 2*STAT_DY; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_ATTRIBUTE_2(C_MENU_ITEM_DEF)
{
posx = STAT_A_X3 - 300; posy = STAT_ATR_Y + 3*STAT_DY; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_ATTRIBUTE_3(C_MENU_ITEM_DEF)
{
posx = STAT_A_X3 - 300; posy = STAT_ATR_Y + 4*STAT_DY; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_ATTRIBUTE_4(C_MENU_ITEM_DEF)
{
posx = STAT_A_X3 - 300; posy = STAT_ATR_Y + 5*STAT_DY; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
//
// Schutz
//
INSTANCE MENU_ITEM_ARMOR_HEADING(C_MENU_ITEM_DEF)
{
// text[0] = "Rüstungs-Schutz:"; fontName = STAT_FONT_TITLE;
text[0] = "OCHRANA"; fontName = STAT_FONT_TITLE;
posx = STAT_A_X1; posy = STAT_ARM_Y + 0*STAT_DY;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_ARMOR_1_TITLE(C_MENU_ITEM_DEF)
{
// text[0] = "Waffen";
text[0] = "proti zbraním";
posx = STAT_A_X1; posy = STAT_ARM_Y + 1*STAT_DY; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_ARMOR_2_TITLE(C_MENU_ITEM_DEF)
{
// text[0] = "Geschosse";
text[0] = "proti šípům";
posx = STAT_A_X1; posy = STAT_ARM_Y + 2*STAT_DY; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_ARMOR_3_TITLE(C_MENU_ITEM_DEF)
{
// text[0] = "Feuer";
text[0] = "proti ohni";
posx = STAT_A_X1; posy = STAT_ARM_Y + 3*STAT_DY; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_ARMOR_4_TITLE(C_MENU_ITEM_DEF)
{
// text[0] = "Magie";
text[0] = "proti magii";
posx = STAT_A_X1; posy = STAT_ARM_Y + 4*STAT_DY; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_ARMOR_1(C_MENU_ITEM_DEF)
{
posx = STAT_A_X3; posy = STAT_ARM_Y + 1*STAT_DY; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_ARMOR_2(C_MENU_ITEM_DEF)
{
posx = STAT_A_X3; posy = STAT_ARM_Y + 2*STAT_DY; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_ARMOR_3(C_MENU_ITEM_DEF)
{
posx = STAT_A_X3; posy = STAT_ARM_Y + 3*STAT_DY; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_ARMOR_4(C_MENU_ITEM_DEF)
{
posx = STAT_A_X3; posy = STAT_ARM_Y + 4*STAT_DY; fontName = STAT_FONT_DEFAULT;
flags = flags & ~IT_SELECTABLE;
};
//
// Talente
//
// Headings
INSTANCE MENU_ITEM_TALENTS_WEAPON_HEADING(C_MENU_ITEM_DEF)
{
text[0] = "Bojové dovednosti / Kritický úder";
posx = STAT_B_X1; posy = STAT_TAL_Y + STAT_DY*0; fontName = STAT_FONT_TITLE;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_TALENTS_THIEF_HEADING(C_MENU_ITEM_DEF)
{
text[0] = "Zloděj. dovednosti / Možnost přistižení";
posx = STAT_B_X1; posy = STAT_TAL_Y + STAT_DY*7; fontName = STAT_FONT_TITLE;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_TALENTS_MAGIC_HEADING(C_MENU_ITEM_DEF)
{
text[0] = "Magie:";
posx = STAT_B_X1; posy = STAT_TAL_Y + STAT_DY*13; fontName = STAT_FONT_TITLE;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENU_ITEM_TALENTS_WORK_HEADING(C_MENU_ITEM_DEF)
{
text[0] = "Ostatní dovednosti:";
posx = STAT_B_X1; posy = STAT_TAL_Y + STAT_DY*18; fontName = STAT_FONT_TITLE;
flags = flags & ~IT_SELECTABLE;
};
//
// Liste der Talente
//
/////////////////////////
// Waffentalente...
// Talent 1 (Einhänder)
INSTANCE MENU_ITEM_TALENT_1_TITLE(C_MENU_ITEM_DEF) { posx = STAT_B_X1;posy = STAT_TAL_Y + 1*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
INSTANCE MENU_ITEM_TALENT_1_SKILL(C_MENU_ITEM_DEF) { posx = STAT_B_X2;posy = STAT_TAL_Y + 1*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
INSTANCE MENU_ITEM_TALENT_1(C_MENU_ITEM_DEF) { posx = STAT_B_X3;posy = STAT_TAL_Y + 1*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
// Talent 2 (Zweihänder)
INSTANCE MENU_ITEM_TALENT_2_TITLE(C_MENU_ITEM_DEF) { posx = STAT_B_X1;posy = STAT_TAL_Y + 2*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
instance MENU_ITEM_TALENT_2_SKILL(C_MENU_ITEM_DEF) { posx = STAT_B_X2;posy = STAT_TAL_Y + 2*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
INSTANCE MENU_ITEM_TALENT_2(C_MENU_ITEM_DEF) { posx = STAT_B_X3;posy = STAT_TAL_Y + 2*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
// Talent 3 (Kampfstab)
INSTANCE MENU_ITEM_TALENT_3_TITLE(C_MENU_ITEM_DEF) { posx = STAT_B_X1;posy = STAT_TAL_Y + 3*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
instance MENU_ITEM_TALENT_3_SKILL(C_MENU_ITEM_DEF) { posx = STAT_B_X2;posy = STAT_TAL_Y + 3*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
INSTANCE MENU_ITEM_TALENT_3(C_MENU_ITEM_DEF) { posx = STAT_B_X3;posy = STAT_TAL_Y + 3*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
// Talent 4 (Bogen)
INSTANCE MENU_ITEM_TALENT_4_TITLE(C_MENU_ITEM_DEF) { posx = STAT_B_X1;posy = STAT_TAL_Y + 4*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
instance MENU_ITEM_TALENT_4_SKILL(C_MENU_ITEM_DEF) { posx = STAT_B_X2;posy = STAT_TAL_Y + 4*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
INSTANCE MENU_ITEM_TALENT_4(C_MENU_ITEM_DEF) { posx = STAT_B_X3;posy = STAT_TAL_Y + 4*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
// Talent 5 (Armbrust)
INSTANCE MENU_ITEM_TALENT_5_TITLE(C_MENU_ITEM_DEF) { posx = STAT_B_X1;posy = STAT_TAL_Y + 5*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
instance MENU_ITEM_TALENT_5_SKILL(C_MENU_ITEM_DEF) { posx = STAT_B_X2;posy = STAT_TAL_Y + 5*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
INSTANCE MENU_ITEM_TALENT_5(C_MENU_ITEM_DEF) { posx = STAT_B_X3;posy = STAT_TAL_Y + 5*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
////////////////////////////
// Diebestalente
// Talent 9 (Schleichen)
INSTANCE MENU_ITEM_TALENT_9_TITLE(C_MENU_ITEM_DEF) { posx = STAT_B_X1;posy = STAT_TAL_Y + 8*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
instance MENU_ITEM_TALENT_9_SKILL(C_MENU_ITEM_DEF) { posx = STAT_B_X2;posy = STAT_TAL_Y + 8*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
// Talent 6 (Schlösser knacken)
INSTANCE MENU_ITEM_TALENT_6_TITLE(C_MENU_ITEM_DEF) { posx = STAT_B_X1;posy = STAT_TAL_Y + 9*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
instance MENU_ITEM_TALENT_6_SKILL(C_MENU_ITEM_DEF) { posx = STAT_B_X2;posy = STAT_TAL_Y + 9*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
INSTANCE MENU_ITEM_TALENT_6(C_MENU_ITEM_DEF) { posx = STAT_B_X3;posy = STAT_TAL_Y + 9*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
// Talent 7 (Taschendiebstahl)
INSTANCE MENU_ITEM_TALENT_7_TITLE(C_MENU_ITEM_DEF) { posx = STAT_B_X1;posy = STAT_TAL_Y + 10*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
instance MENU_ITEM_TALENT_7_SKILL(C_MENU_ITEM_DEF) { posx = STAT_B_X2;posy = STAT_TAL_Y + 10*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
// Talent 12 (Akrobatik)
INSTANCE MENU_ITEM_TALENT_12_TITLE(C_MENU_ITEM_DEF) { posx = STAT_B_X1;posy = STAT_TAL_Y + 11*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
instance MENU_ITEM_TALENT_12_SKILL(C_MENU_ITEM_DEF) { posx = STAT_B_X2;posy = STAT_TAL_Y + 11*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
//////////////////////////
// Magie
// Talent 8 (Magiekreis)
INSTANCE MENU_ITEM_TALENT_8_TITLE(C_MENU_ITEM_DEF) { posx = STAT_B_X1;posy = STAT_TAL_Y + 14*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
instance MENU_ITEM_TALENT_8_SKILL(C_MENU_ITEM_DEF) { posx = STAT_B_X2;posy = STAT_TAL_Y + 14*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
// Talent 13 (Runen erschaffen)
INSTANCE MENU_ITEM_TALENT_13_TITLE(C_MENU_ITEM_DEF) { posx = STAT_B_X1;posy = STAT_TAL_Y + 15*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
instance MENU_ITEM_TALENT_13_SKILL(C_MENU_ITEM_DEF) { posx = STAT_B_X2;posy = STAT_TAL_Y + 15*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
// Talent 15 (Alchemie)
INSTANCE MENU_ITEM_TALENT_15_TITLE(C_MENU_ITEM_DEF) { posx = STAT_B_X1;posy = STAT_TAL_Y + 16*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
instance MENU_ITEM_TALENT_15_SKILL(C_MENU_ITEM_DEF) { posx = STAT_B_X2;posy = STAT_TAL_Y + 16*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
//////////////////////////
// Handwerk
// Talent 11 (Kochen)
INSTANCE MENU_ITEM_TALENT_11_TITLE(C_MENU_ITEM_DEF) { posx = STAT_B_X1;posy = STAT_TAL_Y + 19*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
instance MENU_ITEM_TALENT_11_SKILL(C_MENU_ITEM_DEF) { posx = STAT_B_X2;posy = STAT_TAL_Y + 19*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
// Talent 10 (Schmieden)
INSTANCE MENU_ITEM_TALENT_10_TITLE(C_MENU_ITEM_DEF) { posx = STAT_B_X1;posy = STAT_TAL_Y + 20*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
instance MENU_ITEM_TALENT_10_SKILL(C_MENU_ITEM_DEF) { posx = STAT_B_X2;posy = STAT_TAL_Y + 20*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
// Talent 14 (Bogenmachen)
INSTANCE MENU_ITEM_TALENT_14_TITLE(C_MENU_ITEM_DEF) { posx = STAT_B_X1;posy = STAT_TAL_Y + 21*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
instance MENU_ITEM_TALENT_14_SKILL(C_MENU_ITEM_DEF) { posx = STAT_B_X2;posy = STAT_TAL_Y + 21*STAT_DY; fontName = STAT_FONT_DEFAULT;flags=flags & ~IT_SELECTABLE; };
|
D
|
/**
* Copyright: Copyright (c) 2012 Jacob Carlborg. All rights reserved.
* Authors: Jacob Carlborg
* Version: Initial created: Nov 7, 2012
* License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0)
*/
module tests.NonMutable;
import orange.serialization.Serializer;
import orange.serialization.archives.XmlArchive;
import orange.test.UnitTester;
import tests.Util;
Serializer serializer;
XmlArchive!(char) archive;
class B
{
int a;
pure this (int a)
{
this.a = a;
}
override equals_t opEquals (Object other)
{
if (auto o = cast(B) other)
return a == o.a;
return false;
}
}
class A
{
const int a;
immutable int b;
immutable string c;
immutable B d;
immutable(int)* e;
this (int a, int b, string c, immutable B d, immutable(int)* e)
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
}
override equals_t opEquals (Object other)
{
if (auto o = cast(A) other)
return a == o.a &&
b == o.b &&
c == o.c &&
d == o.d &&
*e == *o.e;
return false;
}
}
A a;
immutable int ptr = 3;
class CTFEFieldsIssue35
{
public immutable int FIRST;
public immutable int SECOND1;
public bool someFlag;
this ()
{
FIRST = 1;
SECOND1 = 1;
}
}
unittest
{
archive = new XmlArchive!(char);
serializer = new Serializer(archive);
a = new A(1, 2, "str", new immutable(B)(3), &ptr);
describe("serialize object with immutable and const fields") in {
it("should return a serialized object") in {
serializer.reset;
serializer.serialize(a);
assert(archive.data().containsDefaultXmlContent());
assert(archive.data().contains(`<object runtimeType="tests.NonMutable.A" type="tests.NonMutable.A" key="0" id="0">`));
assert(archive.data().containsXmlTag("int", `key="a" id="1"`, "1"));
assert(archive.data().containsXmlTag("int", `key="b" id="2"`, "2"));
assert(archive.data().containsXmlTag("string", `type="immutable(char)" length="3" key="c" id="3"`, "str"));
assert(archive.data().contains(`<object runtimeType="tests.NonMutable.B" type="immutable(tests.NonMutable.B)" key="d" id="4">`));
assert(archive.data().containsXmlTag("pointer", `key="e" id="6"`));
assert(archive.data().containsXmlTag("int", `key="1" id="7"`, "3"));
};
};
describe("deserialize object") in {
it("should return a deserialized object equal to the original object") in {
auto aDeserialized = serializer.deserialize!(A)(archive.untypedData);
assert(a == aDeserialized);
};
};
describe("serializing object with CTFE fields") in {
it("should compile") in {
assert(__traits(compiles, {
serializer.serialize(new CTFEFieldsIssue35);
}));
};
};
}
|
D
|
/**
* TLS Channel
*
* Copyright:
* (C) 2011,2012,2014 Jack Lloyd
* (C) 2014-2015 Etienne Cimon
*
* License:
* Botan is released under the Simplified BSD License (see LICENSE.md)
*/
module botan.tls.channel;
import botan.constants;
static if (BOTAN_HAS_TLS):
package:
public import botan.cert.x509.x509cert;
public import botan.tls.policy;
public import botan.tls.session;
public import botan.tls.alert;
public import botan.tls.session_manager;
public import botan.tls.version_;
public import botan.tls.exceptn;
public import botan.rng.rng;
import core.thread : Thread;
import botan.tls.handshake_state;
import botan.tls.messages;
import botan.tls.heartbeats;
import botan.tls.record;
import botan.tls.seq_numbers;
import botan.utils.rounding;
import memutils.dictionarylist;
import botan.utils.loadstor;
import botan.utils.types;
import botan.utils.get_byte;
import memutils.hashmap;
import std.string : toStringz;
alias DataWriter = void delegate(in ubyte[]);
alias OnClearData = void delegate(in ubyte[]);
alias OnAlert = void delegate(in TLSAlert, in ubyte[]);
alias OnHandshakeComplete = bool delegate(in TLSSession);
/**
* Generic interface for TLS endpoint
*/
class TLSChannel
{
public:
this(DataWriter output_fn,
OnClearData data_cb,
OnAlert alert_cb,
OnHandshakeComplete handshake_cb,
TLSSessionManager session_manager,
RandomNumberGenerator rng,
bool is_datagram,
size_t reserved_io_buffer_size)
{
m_owner = Thread.getThis();
m_handshake_cb = handshake_cb;
m_data_cb = data_cb;
m_alert_cb = alert_cb;
m_output_fn = output_fn;
m_rng = rng;
m_session_manager = session_manager;
/* epoch 0 is plaintext, thus null cipher state */
//m_write_cipher_states[cast(ushort)0] = ConnectionCipherState.init;
//m_read_cipher_states[cast(ushort)0] = ConnectionCipherState.init;
m_writebuf.reserve(reserved_io_buffer_size);
m_readbuf.reserve(reserved_io_buffer_size);
}
/**
* Inject TLS traffic received from counterparty
* Returns: a hint as the how many more bytes we need to process the
* current record (this may be 0 if on a record boundary)
*/
size_t receivedData(const(ubyte)* input, size_t input_size)
{
const size_t max_fragment_size = maximumFragmentSize();
try
{
while (!isClosed() && input_size)
{
SecureVector!ubyte record;
ulong record_sequence = 0;
RecordType record_type = NO_RECORD;
TLSProtocolVersion record_version;
size_t consumed = 0;
const size_t needed = .readRecord(m_readbuf,
input,
input_size,
m_is_datagram,
consumed,
record,
record_sequence,
record_version,
record_type,
*m_sequence_numbers,
&readCipherStateEpoch);
assert(consumed > 0, "Got to eat something");
assert(consumed <= input_size, "Record reader consumed sane amount");
input += consumed;
input_size -= consumed;
assert(input_size == 0 || needed == 0, "Got a full record or consumed all input");
if (input_size == 0 && needed != 0)
return needed; // need more data to complete record
if (record.length > max_fragment_size)
throw new TLSException(TLSAlert.RECORD_OVERFLOW, "Plaintext record is too large");
if (record_type == HANDSHAKE || record_type == CHANGE_CIPHER_SPEC)
{
if (!m_pending_state)
{
if (record_version.isDatagramProtocol())
{
if (m_sequence_numbers)
{
/*
* Might be a peer retransmit under epoch - 1 in which
* case we must retransmit last flight
*/
(*m_sequence_numbers).readAccept(record_sequence);
const ushort epoch = record_sequence >> 48;
if (epoch == sequenceNumbers().currentReadEpoch())
{
createHandshakeState(record_version);
}
else if (epoch == sequenceNumbers().currentReadEpoch() - 1)
{
assert(m_active_state, "Have active state here");
auto rec = unlock(record);
m_active_state.handshakeIo().addRecord(rec, record_type, record_sequence);
}
}
else if (record_sequence == 0)
{
createHandshakeState(record_version);
}
}
else
{
createHandshakeState(record_version);
}
}
if (m_pending_state)
{
auto rec = unlock(record);
m_pending_state.handshakeIo().addRecord(rec, record_type, record_sequence);
while (true) {
if (auto pending = *m_pending_state) {
auto msg = pending.getNextHandshakeMsg();
if (msg.type == HANDSHAKE_NONE) // no full handshake yet
break;
processHandshakeMsg(activeState(), pending, msg.type, msg.data);
} else break;
}
}
}
else if (record_type == HEARTBEAT && peerSupportsHeartbeats())
{
if (!activeState())
throw new TLSUnexpectedMessage("Heartbeat sent before handshake done");
HeartbeatMessage heartbeat = HeartbeatMessage(unlock(record));
const Vector!ubyte* payload = &heartbeat.payload();
if (heartbeat.isRequest())
{
if (!pendingState())
{
HeartbeatMessage response = HeartbeatMessage(HeartbeatMessage.RESPONSE, payload.ptr, payload.length);
auto rec = response.contents();
sendRecord(HEARTBEAT, rec);
}
}
else
{
m_alert_cb(TLSAlert(TLSAlert.HEARTBEAT_PAYLOAD), cast(ubyte[])(*payload)[]);
}
}
else if (record_type == APPLICATION_DATA)
{
if (!activeState())
throw new TLSUnexpectedMessage("Application data before handshake done");
/*
* OpenSSL among others sends empty records in versions
* before TLS v1.1 in order to randomize the IV of the
* following record. Avoid spurious callbacks.
*/
if (record.length > 0)
m_data_cb(cast(ubyte[])record[]);
}
else if (record_type == ALERT)
{
TLSAlert alert_msg = TLSAlert(record);
if (alert_msg.type() == TLSAlert.NO_RENEGOTIATION)
m_pending_state.free();
if (alert_msg.type() == TLSAlert.CLOSE_NOTIFY)
sendWarningAlert(TLSAlert.CLOSE_NOTIFY); // reply in kind
m_alert_cb(alert_msg, null);
if (alert_msg.isFatal())
{
if (auto active = activeState()) {
auto entry = &active.serverHello().sessionId();
m_session_manager.removeEntry(*entry);
}
return 0;
}
}
else if (record_type != NO_RECORD)
throw new TLSUnexpectedMessage("Unexpected record type " ~ to!string(record_type) ~ " from counterparty");
}
return 0; // on a record boundary
}
catch(TLSException e)
{
sendFatalAlert(e.type());
throw e;
}
catch(IntegrityFailure e)
{
sendFatalAlert(TLSAlert.BAD_RECORD_MAC);
throw e;
}
catch(DecodingError e)
{
sendFatalAlert(TLSAlert.DECODE_ERROR);
throw e;
}
catch(Exception e)
{
sendFatalAlert(TLSAlert.INTERNAL_ERROR);
throw e;
}
}
/**
* Inject TLS traffic received from counterparty
* Returns: a hint as the how many more bytes we need to process the
* current record (this may be 0 if on a record boundary)
*/
size_t receivedData(const ref Vector!ubyte buf)
{
return this.receivedData(buf.ptr, buf.length);
}
/**
* Inject plaintext intended for counterparty
* Throws an exception if isActive() is false
*/
void send(const(ubyte)* buf, size_t buf_size)
{
if (!isActive())
throw new TLSClosedException("Data cannot be sent on inactive TLS connection");
sendRecordArray(sequenceNumbers().currentWriteEpoch(), APPLICATION_DATA, buf, buf_size);
}
/**
* Inject plaintext intended for counterparty
* Throws an exception if isActive() is false
*/
void send(in string str)
{
this.send(cast(const(ubyte)*)(str.toStringz), str.length);
}
/**
* Inject plaintext intended for counterparty
* Throws an exception if isActive() is false
*/
void send(Alloc)(const ref Vector!( char, Alloc ) val)
{
send(val.ptr, val.length);
}
/**
* Send a TLS alert message. If the alert is fatal, the internal
* state (keys, etc) will be reset.
*
* Params:
* alert = the TLSAlert to send
*/
void sendAlert(in TLSAlert alert)
{
if (alert.isValid() && !isClosed())
{
try
{
auto rec = alert.serialize();
sendRecord(ALERT, rec);
}
catch (Exception) { /* swallow it */ }
}
if (alert.type() == TLSAlert.NO_RENEGOTIATION)
m_pending_state.free();
if (alert.isFatal()) {
if (auto active = activeState()) {
auto entry = &active.serverHello().sessionId();
m_session_manager.removeEntry(*entry);
}
}
}
/**
* Send a warning alert
*/
void sendWarningAlert(TLSAlertType type) { sendAlert(TLSAlert(type, false)); }
/**
* Send a fatal alert
*/
void sendFatalAlert(TLSAlertType type) { sendAlert(TLSAlert(type, true)); }
/**
* Send a close notification alert
*/
void close() { sendWarningAlert(TLSAlert.CLOSE_NOTIFY); }
/**
* Returns: true iff the connection is active for sending application data
*/
bool isActive() const
{
return (activeState() !is null);
}
/**
* Returns: true iff the connection has been definitely closed
*/
bool isClosed() const
{
if (activeState() || pendingState())
return false;
/*
* If no active or pending state, then either we had a connection
* and it has been closed, or we are a server which has never
* received a connection. This case is detectable by also lacking
* m_sequence_numbers
*/
return (*m_sequence_numbers !is null);
}
/**
* Attempt to renegotiate the session
* Params:
* force_full_renegotiation = if true, require a full renegotiation,
* otherwise allow session resumption
*/
void renegotiate(bool force_full_renegotiation = false)
{
if (pendingState()) // currently in handshake?
return;
if (const HandshakeState active = activeState())
initiateHandshake(createHandshakeState(active.Version()),
force_full_renegotiation);
else
throw new Exception("Cannot renegotiate on inactive connection");
}
/**
* Returns: true iff the peer supports heartbeat messages
*/
bool peerSupportsHeartbeats() const
{
if (const HandshakeState active = activeState())
return active.serverHello().supportsHeartbeats();
return false;
}
/**
* Returns: true iff we are allowed to send heartbeat messages
*/
bool heartbeatSendingAllowed() const
{
if (const HandshakeState active = activeState())
return active.serverHello().peerCanSendHeartbeats();
return false;
}
/**
* Attempt to send a heartbeat message (if negotiated with counterparty)
* Params:
* payload = will be echoed back
* payload_size = size of payload in bytes
*/
void heartbeat(const(ubyte)* payload, size_t payload_size)
{
if (heartbeatSendingAllowed())
{
HeartbeatMessage heartbeat = HeartbeatMessage(HeartbeatMessage.REQUEST, payload, payload_size);
auto rec = heartbeat.contents();
sendRecord(HEARTBEAT, rec);
}
}
/**
* Attempt to send a heartbeat message (if negotiated with counterparty)
*/
void heartbeat() { heartbeat(null, 0); }
/**
* Returns: certificate chain of the peer (may be empty)
*/
Vector!X509Certificate peerCertChain() const
{
if (const HandshakeState active = activeState())
return getPeerCertChain(active).dup;
return Vector!X509Certificate();
}
/**
* Key material export (RFC 5705)
* Params:
* label = a disambiguating label string
* context = a per-association context value
* length = the length of the desired key in bytes
* Returns: key of length bytes
*/
const(SymmetricKey) keyMaterialExport(in string label,
in string context,
size_t length) const
{
if (auto active = activeState())
{
Unique!KDF prf = active.protocolSpecificPrf();
const(SecureVector!ubyte)* master_secret = &active.sessionKeys().masterSecret();
Vector!ubyte salt;
salt ~= label;
salt ~= active.clientHello().randomBytes();
salt ~= active.serverHello().randomBytes();
if (context != "")
{
size_t context_size = context.length;
if (context_size > 0xFFFF)
throw new Exception("key_material_export context is too long");
salt.pushBack(get_byte(0, cast(ushort) context_size));
salt.pushBack(get_byte(1, cast(ushort) context_size));
salt ~= context;
}
return SymmetricKey(prf.deriveKey(length, *master_secret, salt));
}
else
throw new Exception("key_material_export connection not active");
}
/// Returns the ALPN chosen in the ServerHello with the ALPN extention
const(string) applicationProtocol() const { return m_application_protocol; }
/// Returns the current session ID
const(ubyte[]) sessionId() const {
if (auto active = activeState()) {
return active.serverHello().sessionIdBytes();
}
return null;
}
~this()
{
resetState();
}
protected:
abstract void processHandshakeMsg(in HandshakeState active_state,
HandshakeState pending_state,
HandshakeType type,
const ref Vector!ubyte contents);
abstract void initiateHandshake(HandshakeState state,
bool force_full_renegotiation);
abstract Vector!X509Certificate getPeerCertChain(in HandshakeState state) const;
abstract HandshakeState newHandshakeState(HandshakeIO io);
HandshakeState createHandshakeState(TLSProtocolVersion _version)
{
if (pendingState())
throw new InternalError("createHandshakeState called during handshake");
if (const HandshakeState active = activeState())
{
TLSProtocolVersion active_version = active.Version();
if (active_version.isDatagramProtocol() != _version.isDatagramProtocol())
throw new Exception("Active state using version " ~ active_version.toString() ~
" cannot change to " ~ _version.toString() ~ " in pending");
}
if (!m_sequence_numbers)
{
if (_version.isDatagramProtocol())
m_sequence_numbers = new DatagramSequenceNumbers;
else
m_sequence_numbers = new StreamSequenceNumbers;
}
Unique!HandshakeIO io;
if (_version.isDatagramProtocol()) {
// default MTU is IPv6 min MTU minus UDP/IP headers (TODO: make configurable)
const ushort mtu = 1280 - 40 - 8;
io = new DatagramHandshakeIO(*m_sequence_numbers, &sendRecordUnderEpoch, mtu);
}
else {
io = new StreamHandshakeIO(&sendRecord);
}
m_pending_state = newHandshakeState(io.release());
if (auto active = activeState())
m_pending_state.setVersion(active.Version());
return *m_pending_state;
}
/**
* Perform a handshake timeout check. This does nothing unless
* this is a DTLS channel with a pending handshake state, in
* which case we check for timeout and potentially retransmit
* handshake packets.
*/
bool timeoutCheck() {
if (m_pending_state)
return m_pending_state.handshakeIo().timeoutCheck();
//FIXME: scan cipher suites and remove epochs older than 2*MSL
return false;
}
void activateSession()
{
std.algorithm.swap(m_active_state, m_pending_state);
m_pending_state.free();
if (!m_active_state.Version().isDatagramProtocol())
{
// TLS is easy just remove all but the current state
auto current_epoch = sequenceNumbers().currentWriteEpoch();
foreach (const ref ushort k, const ref ConnectionCipherState v; m_write_cipher_states) {
if (k != current_epoch) {
v.destroy();
m_write_cipher_states.remove(k);
}
}
foreach (const ref ushort k, const ref ConnectionCipherState v; m_read_cipher_states) {
if (k != current_epoch) {
v.destroy();
m_write_cipher_states.remove(k);
}
}
}
}
void changeCipherSpecReader(ConnectionSide side)
{
auto pending = pendingState();
assert(pending && pending.serverHello(), "Have received server hello");
if (pending.serverHello().compressionMethod() != NO_COMPRESSION)
throw new InternalError("Negotiated unknown compression algorithm");
(*m_sequence_numbers).newReadCipherState();
const ushort epoch = sequenceNumbers().currentReadEpoch();
assert(m_read_cipher_states.get(epoch, ConnectionCipherState.init) is ConnectionCipherState.init,
"No read cipher state currently set for next epoch");
// flip side as we are reading
ConnectionCipherState read_state = new ConnectionCipherState(pending.Version(),
(side == CLIENT) ? SERVER : CLIENT,
false,
pending.ciphersuite(),
pending.sessionKeys());
m_read_cipher_states[epoch] = read_state;
}
void changeCipherSpecWriter(ConnectionSide side)
{
auto pending = pendingState();
assert(pending && pending.serverHello(), "Have received server hello");
if (pending.serverHello().compressionMethod() != NO_COMPRESSION)
throw new InternalError("Negotiated unknown compression algorithm");
(*m_sequence_numbers).newWriteCipherState();
const ushort epoch = sequenceNumbers().currentWriteEpoch();
assert(m_write_cipher_states.get(epoch, ConnectionCipherState.init) is ConnectionCipherState.init, "No write cipher state currently set for next epoch");
ConnectionCipherState write_state = new ConnectionCipherState(pending.Version(),
side,
true,
pending.ciphersuite(),
pending.sessionKeys());
m_write_cipher_states[epoch] = write_state;
}
/* secure renegotiation handling */
void secureRenegotiationCheck(const ClientHello client_hello)
{
const bool secure_renegotiation = client_hello.secureRenegotiation();
if (auto active = activeState())
{
const bool active_sr = active.clientHello().secureRenegotiation();
if (active_sr != secure_renegotiation)
throw new TLSException(TLSAlert.HANDSHAKE_FAILURE, "TLSClient changed its mind about secure renegotiation");
}
if (secure_renegotiation)
{
Vector!ubyte data = client_hello.renegotiationInfo();
if (data != secureRenegotiationDataForClientHello())
throw new TLSException(TLSAlert.HANDSHAKE_FAILURE, "TLSClient sent bad values for secure renegotiation");
}
}
void secureRenegotiationCheck(const ServerHello server_hello)
{
const bool secure_renegotiation = server_hello.secureRenegotiation();
if (auto active = activeState())
{
const bool active_sr = active.clientHello().secureRenegotiation();
if (active_sr != secure_renegotiation)
throw new TLSException(TLSAlert.HANDSHAKE_FAILURE, "TLSServer changed its mind about secure renegotiation");
}
if (secure_renegotiation)
{
const Vector!ubyte data = server_hello.renegotiationInfo();
if (data != secureRenegotiationDataForServerHello())
throw new TLSException(TLSAlert.HANDSHAKE_FAILURE, "TLSServer sent bad values for secure renegotiation");
}
}
Vector!ubyte secureRenegotiationDataForClientHello() const
{
if (auto active = activeState()) {
auto verif_data = active.clientFinished().verifyDataBytes();
return Vector!ubyte(verif_data);
}
return Vector!ubyte();
}
Vector!ubyte secureRenegotiationDataForServerHello() const
{
if (auto active = activeState())
{
Vector!ubyte buf = active.clientFinished().verifyDataBytes();
buf ~= active.serverFinished().verifyDataBytes();
return buf.move();
}
return Vector!ubyte();
}
/**
* Returns: true iff the counterparty supports the secure
* renegotiation extensions.
*/
bool secureRenegotiationSupported() const
{
if (auto active = activeState())
return active.serverHello().secureRenegotiation();
if (auto pending = pendingState())
if (auto hello = pending.serverHello())
return hello.secureRenegotiation();
return false;
}
RandomNumberGenerator rng() { return m_rng; }
TLSSessionManager sessionManager() { return m_session_manager; }
bool saveSession(in TLSSession session) const { return m_handshake_cb(session); }
private:
size_t maximumFragmentSize() const
{
// should we be caching this value?
if (auto pending = pendingState())
if (auto server_hello = pending.serverHello())
if (size_t frag = server_hello.fragmentSize())
return frag;
if (auto active = activeState())
if (size_t frag = active.serverHello().fragmentSize())
return frag;
return MAX_PLAINTEXT_SIZE;
}
void sendRecord(ubyte record_type, const ref Vector!ubyte record)
{
sendRecordArray(sequenceNumbers().currentWriteEpoch(), record_type, record.ptr, record.length);
}
void sendRecordUnderEpoch(ushort epoch, ubyte record_type, const ref Vector!ubyte record)
{
sendRecordArray(epoch, record_type, record.ptr, record.length);
}
void sendRecordArray(ushort epoch, ubyte type, const(ubyte)* input, size_t length)
{
if (length == 0)
return;
/*
* If using CBC mode without an explicit IV (TLS v1.0),
* send a single ubyte of plaintext to randomize the (implicit) IV of
* the following main block. If using a stream cipher, or TLS v1.1
* or higher, this isn't necessary.
*
* An empty record also works but apparently some implementations do
* not like this (https://bugzilla.mozilla.org/show_bug.cgi?id=665814)
*
* See http://www.openssl.org/~bodo/tls-cbc.txt for background.
*/
auto cipher_state = cast(ConnectionCipherState)writeCipherStateEpoch(epoch);
if (type == APPLICATION_DATA && cipher_state.cbcWithoutExplicitIv())
{
writeRecord(cipher_state, epoch, type, input, 1);
input += 1;
length -= 1;
}
const size_t max_fragment_size = maximumFragmentSize();
while (length)
{
const size_t sending = std.algorithm.min(length, max_fragment_size);
writeRecord(cipher_state, epoch, type, input, sending);
input += sending;
length -= sending;
}
}
void writeRecord(ConnectionCipherState cipher_state, ushort epoch, ubyte record_type, const(ubyte)* input, size_t length)
{
assert(m_pending_state || m_active_state, "Some connection state exists");
TLSProtocolVersion record_version = (m_pending_state) ? (m_pending_state.Version()) : (m_active_state.Version());
.writeRecord(m_writebuf,
record_type,
input,
length,
record_version,
(*m_sequence_numbers).nextWriteSequence(epoch),
cipher_state,
m_rng);
m_output_fn(cast(ubyte[]) m_writebuf[]);
}
const(ConnectionSequenceNumbers) sequenceNumbers() const
{
assert(m_sequence_numbers, "Have a sequence numbers object");
return *m_sequence_numbers;
}
const(ConnectionCipherState) readCipherStateEpoch(ushort epoch) const
{
auto state = m_read_cipher_states.get(epoch, ConnectionCipherState.init);
assert(state !is ConnectionCipherState.init || epoch == 0, "Have a cipher state for the specified epoch");
return state;
}
const(ConnectionCipherState) writeCipherStateEpoch(ushort epoch) const
{
auto state = m_write_cipher_states.get(epoch, ConnectionCipherState.init);
assert(state !is ConnectionCipherState.init || epoch == 0, "Have a cipher state for the specified epoch");
return state;
}
protected void resetState()
{
m_active_state.free();
m_pending_state.free();
m_readbuf.destroy();
m_writebuf.destroy();
foreach (const ref k, const ref v; m_write_cipher_states)
{
v.destroy();
}
m_write_cipher_states.clear();
foreach (const ref k, const ref v; m_read_cipher_states)
{
v.destroy();
}
m_read_cipher_states.clear();
}
const(HandshakeState) activeState() const { return *m_active_state; }
const(HandshakeState) pendingState() const { return *m_pending_state; }
Thread m_owner;
package string m_application_protocol;
bool m_is_datagram;
/* callbacks */
OnHandshakeComplete m_handshake_cb;
OnClearData m_data_cb;
OnAlert m_alert_cb;
DataWriter m_output_fn;
/* external state */
RandomNumberGenerator m_rng;
package TLSSessionManager m_session_manager; // fixme: package protection for switchContext, use protected: method instead
/* sequence number state */
Unique!ConnectionSequenceNumbers m_sequence_numbers;
/* pending and active connection states */
Unique!HandshakeState m_active_state;
Unique!HandshakeState m_pending_state;
/* cipher states for each epoch */
HashMap!(ushort, ConnectionCipherState) m_write_cipher_states;
HashMap!(ushort, ConnectionCipherState) m_read_cipher_states;
/* I/O buffers */
SecureVector!ubyte m_writebuf;
SecureVector!ubyte m_readbuf;
}
|
D
|
/Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Build/Intermediates/Pods.build/Debug-iphonesimulator/HandyJSON.build/Objects-normal/x86_64/ReflectionHelper.o : /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Metadata.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/CBridge.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Transformable.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Measuable.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/MangledName.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ExtendCustomBasicType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/BuiltInBasicType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/BuiltInBridgeType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ExtendCustomModelType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/TransformType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/EnumType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/PointerType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ContextDescriptorType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/TransformOf.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/URLTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/DataTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/DateTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ISO8601DateTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/EnumTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/NSDecimalNumberTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/DateFormatterTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/HexColorTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/CustomDateFormatTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/OtherExtension.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Configuration.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/PropertyInfo.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Logger.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ReflectionHelper.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/HelpingMapper.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Serializer.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Deserializer.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/FieldDescriptor.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Properties.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/AnyExtensions.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Export.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/HandyJSON.h /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Target\ Support\ Files/HandyJSON/HandyJSON-umbrella.h /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Build/Intermediates/Pods.build/Debug-iphonesimulator/HandyJSON.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.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/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Build/Intermediates/Pods.build/Debug-iphonesimulator/HandyJSON.build/Objects-normal/x86_64/ReflectionHelper~partial.swiftmodule : /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Metadata.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/CBridge.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Transformable.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Measuable.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/MangledName.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ExtendCustomBasicType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/BuiltInBasicType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/BuiltInBridgeType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ExtendCustomModelType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/TransformType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/EnumType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/PointerType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ContextDescriptorType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/TransformOf.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/URLTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/DataTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/DateTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ISO8601DateTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/EnumTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/NSDecimalNumberTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/DateFormatterTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/HexColorTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/CustomDateFormatTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/OtherExtension.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Configuration.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/PropertyInfo.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Logger.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ReflectionHelper.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/HelpingMapper.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Serializer.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Deserializer.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/FieldDescriptor.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Properties.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/AnyExtensions.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Export.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/HandyJSON.h /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Target\ Support\ Files/HandyJSON/HandyJSON-umbrella.h /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Build/Intermediates/Pods.build/Debug-iphonesimulator/HandyJSON.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.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/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Build/Intermediates/Pods.build/Debug-iphonesimulator/HandyJSON.build/Objects-normal/x86_64/ReflectionHelper~partial.swiftdoc : /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Metadata.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/CBridge.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Transformable.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Measuable.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/MangledName.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ExtendCustomBasicType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/BuiltInBasicType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/BuiltInBridgeType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ExtendCustomModelType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/TransformType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/EnumType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/PointerType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ContextDescriptorType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/TransformOf.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/URLTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/DataTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/DateTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ISO8601DateTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/EnumTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/NSDecimalNumberTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/DateFormatterTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/HexColorTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/CustomDateFormatTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/OtherExtension.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Configuration.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/PropertyInfo.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Logger.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ReflectionHelper.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/HelpingMapper.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Serializer.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Deserializer.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/FieldDescriptor.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Properties.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/AnyExtensions.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Export.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/HandyJSON.h /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Target\ Support\ Files/HandyJSON/HandyJSON-umbrella.h /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Build/Intermediates/Pods.build/Debug-iphonesimulator/HandyJSON.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.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/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Build/Intermediates/Pods.build/Debug-iphonesimulator/HandyJSON.build/Objects-normal/x86_64/ReflectionHelper~partial.swiftsourceinfo : /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Metadata.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/CBridge.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Transformable.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Measuable.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/MangledName.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ExtendCustomBasicType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/BuiltInBasicType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/BuiltInBridgeType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ExtendCustomModelType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/TransformType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/EnumType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/PointerType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ContextDescriptorType.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/TransformOf.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/URLTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/DataTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/DateTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ISO8601DateTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/EnumTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/NSDecimalNumberTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/DateFormatterTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/HexColorTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/CustomDateFormatTransform.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/OtherExtension.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Configuration.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/PropertyInfo.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Logger.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/ReflectionHelper.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/HelpingMapper.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Serializer.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Deserializer.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/FieldDescriptor.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Properties.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/AnyExtensions.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/Export.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/HandyJSON/Source/HandyJSON.h /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Target\ Support\ Files/HandyJSON/HandyJSON-umbrella.h /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Build/Intermediates/Pods.build/Debug-iphonesimulator/HandyJSON.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.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/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
|
D
|
module ProgressBarTest;
import std.container.array;
import std.stdio;
import std.algorithm;
import std.ascii;
//import std.exception;
import std.string;
import std.traits;
import std.conv;
import std.file;
import std.path;
import std.format;
import std.math;
import core.stdc.stdlib;
import iup;
import im;
import cd;
import toolkit.event;
import toolkit.input;
import toolkit.drawing;
public class ProgressBarTestDialog : IupDialog
{
private IupTimer timer;
private IupProgressBar progressbar1, progressbar2;
private IupButton btn_restart, btn_pause, btn_accelerate;
private IupButton btn_decelerate, btn_show1, btn_show2;
private float increment = 0.1f;
private IupImage8 img_play, img_pause;
this()
{
super();
}
~this()
{
writeln("~this");
}
protected override void initializeComponent()
{
IupImage8 img_restart = new IupImage8(TEST_IMAGE_SIZE, TEST_IMAGE_SIZE, pixmap_restart);
Color background = img_restart.background;
img_restart.setColor(0, Color.fromRgb(0, 0, 0));
img_restart.setColor(1, background);
img_play = new IupImage8(TEST_IMAGE_SIZE, TEST_IMAGE_SIZE, pixmap_play);
background = img_play.background;
img_play.setColor(0, Color.fromRgb(0, 0, 0));
img_play.setColor(1, background);
IupImage8 img_forward = new IupImage8(TEST_IMAGE_SIZE, TEST_IMAGE_SIZE, pixmap_forward);
background = img_forward.background;
img_forward.setColor(0, Color.fromRgb(0, 0, 0));
img_forward.setColor(1, background);
IupImage8 img_rewind = new IupImage8(TEST_IMAGE_SIZE, TEST_IMAGE_SIZE, pixmap_rewind);
background = img_rewind.background;
img_rewind.setColor(0, Color.fromRgb(0, 0, 0));
img_rewind.setColor(1, background);
img_pause = new IupImage8(TEST_IMAGE_SIZE, TEST_IMAGE_SIZE, pixmap_pause);
background = img_pause.background;
img_pause.setColor(0, Color.fromRgb(0, 0, 0));
img_pause.setColor(1, background);
timer = new IupTimer();
timer.interval = 100;
timer.tick += &timer_tick;
progressbar1 = new IupProgressBar();
progressbar1.canExpand = true;
progressbar1.isMarqueeStyle = true;
progressbar2 = new IupProgressBar();
progressbar2.orientation = Orientation.Vertical;
progressbar2.backgroundColor = Color.fromRgb(255, 0, 128);
progressbar2.foregroundColor = Color.fromRgb(0, 128, 0);
progressbar2.rasterSize = Size(30, 100);
progressbar2.maximum = 50;
progressbar2.value = 25;
// progressbar2.isDashed = false;
btn_restart = new IupButton();
btn_restart.click += &btn_restart_click;
btn_restart.image = img_restart;
btn_restart.tooltip.text = "Restart";
btn_pause = new IupButton();
btn_pause.click += &btn_pause_click;
btn_pause.image = img_play;
btn_pause.tooltip.text = "Play/Pause";
btn_accelerate = new IupButton();
btn_accelerate.click += &btn_accelerate_click;
btn_accelerate.image = img_forward;
btn_accelerate.tooltip.text = "Accelerate";
btn_decelerate = new IupButton();
btn_decelerate.click += &btn_decelerate_click;
btn_decelerate.image = img_rewind;
btn_decelerate.tooltip.text = "Decelerate";
btn_show1 = new IupButton("Dashed");
btn_show1.click += &btn_show1_click;
btn_show1.tooltip.text = "Dashed or Continuous";
btn_show2 = new IupButton("Marquee");
btn_show2.click += &btn_show2_click;
btn_show2.tooltip.text = "Marquee or Defined";
IupHbox hbox1 = new IupHbox(new IupFill(),
btn_pause,
btn_restart,
btn_decelerate,
btn_accelerate,
btn_show1,
btn_show2,
new IupFill());
IupVbox vbox1 = new IupVbox(progressbar1, hbox1);
IupHbox hbox = new IupHbox(vbox1, progressbar2);
hbox.margin = Size(10, 10);
hbox.gap = 5;
this.child = hbox;
this.title = "ProgressBar Test";
this.unmapped += &dialog_unmapped;
this.destroying += &dialog_destroying;
this.closing += &dialog_closing;
}
private void dialog_closing(Object sender, CallbackEventArgs e)
{
timer.enabled = false;
writeln("dialog_closing");
}
private void dialog_destroying(Object sender, CallbackEventArgs e)
{
timer.destroy();
writeln("dialog_destroying");
}
private void dialog_unmapped(Object sender, CallbackEventArgs e)
{
writeln("dialog_unmapped");
}
private void btn_restart_click(Object sender, CallbackEventArgs e)
{
progressbar2.value = 0;
}
private void btn_pause_click(Object sender, CallbackEventArgs e)
{
bool ee = timer.enabled;
if(timer.enabled)
{
progressbar1.isMarqueeStyle = false;
timer.enabled = false;
btn_pause.image = img_play;
}
else
{
progressbar1.isMarqueeStyle = true;
timer.enabled = true;
btn_pause.image = img_pause;
}
}
private void btn_accelerate_click(Object sender, CallbackEventArgs e)
{
increment *= 2;
}
private void btn_decelerate_click(Object sender, CallbackEventArgs e)
{
increment /= 2;
}
private void btn_show1_click(Object sender, CallbackEventArgs e)
{
progressbar2.isDashed = !progressbar2.isDashed;
}
private void btn_show2_click(Object sender, CallbackEventArgs e)
{
progressbar2.isMarqueeStyle = !progressbar2.isMarqueeStyle;
}
void timer_tick(Object sender, CallbackEventArgs args)
{
int value = progressbar2.value;
value += cast(int)(increment*50);
if (value > 50) value = 0; /* start over */
progressbar2.value = value;
writefln("value=%d", value);
}
enum TEST_IMAGE_SIZE = 22;
private const(ubyte)[] pixmap_play = [
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2
,2,2,2,2,2,2,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
];
private const(ubyte)[] pixmap_restart = [
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,1,1,2,2,2,2,2,2,2,2,1,1,2,2,2,2,2,2
,2,2,2,2,1,1,2,2,2,2,2,2,1,1,1,1,2,2,2,2,2,2
,2,2,2,2,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,2,2
,2,2,2,2,1,1,2,2,1,1,1,1,1,1,1,1,2,2,2,2,2,2
,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2
,2,2,2,2,1,1,2,2,1,1,1,1,1,1,1,1,2,2,2,2,2,2
,2,2,2,2,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,2,2
,2,2,2,2,1,1,2,2,2,2,2,2,1,1,1,1,2,2,2,2,2,2
,2,2,2,2,1,1,2,2,2,2,2,2,2,2,1,1,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
];
private const(ubyte)[] pixmap_rewind = [
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,1,2,2,2,2,1,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,1,1,2,2,2,1,1,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,1,2,2,1,1,1,2,2,2,2,2,2,2
,2,2,2,2,2,2,1,1,1,1,2,1,1,1,1,2,2,2,2,2,2,2
,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2
,2,2,2,2,2,2,1,1,1,1,2,1,1,1,1,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,1,2,2,1,1,1,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,1,1,2,2,2,1,1,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,1,2,2,2,2,1,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
];
private const(ubyte)[] pixmap_forward = [
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,2,2,2,2,1,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,2,2,2,1,1,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,1,2,2,1,1,1,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,1,1,2,1,1,1,1,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,1,1,2,1,1,1,1,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,1,2,2,1,1,1,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,2,2,2,1,1,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,2,2,2,2,1,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
];
private const(ubyte)[] pixmap_pause = [
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,2,2,1,1,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,2,2,1,1,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,2,2,1,1,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,2,2,1,1,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,2,2,1,1,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,2,2,1,1,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,2,2,1,1,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,2,2,1,1,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,1,1,2,2,1,1,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
];
}
|
D
|
module a;
enum s = import(x"74 65 73 74 31 2e 74 78 74");
enum c = import(x"74 65 73 74 32 2e 74 78 74"c);
enum w = import(x"74 65 73 74 33 2e 74 78 74"w);
enum d = import(x"74 65 73 74 34 2e 74 78 74"d);
|
D
|
import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
void main()
{
immutable int memorysize = 65536;
int pointer = 0;
int i = 0;
int bra = 0;
string program = readln();
int[] arr = new int[memorysize];
int len = 0;
while (program[len] != '\n')
{
len++;
}
fill(arr, 0);
while (i < len)
{
if (program[i] == '+')
{
if (0 <= pointer && pointer < memorysize)
{
arr[pointer]++;
}
else
{
writeln("Out Of Array Bounds At:" ~ i.to!string);
return;
}
i++;
}
else if (program[i] == '-')
{
if (0 <= pointer && pointer < memorysize)
{
arr[pointer]--;
}
else
{
writeln("Out Of Array Bounds At:" ~ i.to!string);
return;
}
i++;
}
else if (program[i] == '<')
{
pointer--;
i++;
}
else if (program[i] == '>')
{
pointer++;
i++;
}
else if (program[i] == ',')
{
immutable int inp = readln().to!int;
arr[pointer] = inp;
i++;
}
else if (program[i] == '.')
{
write(arr[pointer].to!char);
i++;
}
else if (program[i] == '[')
{
if (arr[pointer] == 0)
{
bra = 1;
while (bra > 0)
{
i++;
if (i < len && program[i] == '[')
{
bra++;
}
else if (i < len && program[i] == ']')
{
bra--;
}
else if (i >= len)
{
writeln("EOF Reached.");
return;
}
}
}
else
{
i++;
}
}
else if (program[i] == ']')
{
if (arr[pointer] != 0)
{
bra = 1;
while (bra > 0)
{
i--;
if (i >= 0 && program[i] == '[')
{
bra--;
}
else if (i >= 0 && program[i] == ']')
{
bra++;
}
else if (i < 0)
{
writeln("Out of Program");
return;
}
}
}
else
{
i++;
}
}
else
{
i++;
}
}
}
|
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_or_int_lit8_5.java
.class public dot.junit.opcodes.or_int_lit8.d.T_or_int_lit8_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(I)I
.limit regs 8
or-int/lit8 v0, v7, 127
return v0
.end method
|
D
|
<?xml version="1.0" encoding="UTF-8"?>
<di:SashWindowsMngr xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:di="http://www.eclipse.org/papyrus/0.7.0/sashdi">
<pageList>
<availablePage>
<emfPageIdentifier href="model.notation#_4t5psEe_EeSpc8zwCNI6wA"/>
</availablePage>
<availablePage>
<emfPageIdentifier href="model.notation#_4uCMkEe_EeSpc8zwCNI6wA"/>
</availablePage>
<availablePage>
<emfPageIdentifier href="model.notation#_Ydk0sEi2EeSpc8zwCNI6wA"/>
</availablePage>
<availablePage>
<emfPageIdentifier href="model.notation#_NWVkwEoaEeSdwvY3eCqmwA"/>
</availablePage>
<availablePage>
<emfPageIdentifier href="model.notation#_vEWXgEoaEeSdwvY3eCqmwA"/>
</availablePage>
<availablePage>
<emfPageIdentifier href="model.notation#_YG4j8EofEeSdwvY3eCqmwA"/>
</availablePage>
</pageList>
<sashModel currentSelection="//@sashModel/@windows.0/@children.0">
<windows>
<children xsi:type="di:TabFolder">
<children>
<emfPageIdentifier href="model.notation#_4t5psEe_EeSpc8zwCNI6wA"/>
</children>
<children>
<emfPageIdentifier href="model.notation#_4uCMkEe_EeSpc8zwCNI6wA"/>
</children>
<children>
<emfPageIdentifier href="model.notation#_Ydk0sEi2EeSpc8zwCNI6wA"/>
</children>
<children>
<emfPageIdentifier href="model.notation#_vEWXgEoaEeSdwvY3eCqmwA"/>
</children>
</children>
</windows>
</sashModel>
</di:SashWindowsMngr>
|
D
|
/**
* D header file for POSIX.
*
* Copyright: Copyright Sean Kelly 2005 - 2009.
* License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
* Authors: Sean Kelly, Alex Rønne Petersen
* Standards: The Open Group Base Specifications Issue 6, IEEE Std 1003.1, 2004 Edition
*/
/* 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.sys.posix.sys.socket;
private import core.sys.posix.config;
public import core.sys.posix.sys.types; // for ssize_t, size_t
public import core.sys.posix.sys.uio; // for iovec
version (Posix):
extern (C):
//
// Required
//
/*
socklen_t
sa_family_t
struct sockaddr
{
sa_family_t sa_family;
char sa_data[];
}
struct sockaddr_storage
{
sa_family_t ss_family;
}
struct msghdr
{
void* msg_name;
socklen_t msg_namelen;
struct iovec* msg_iov;
int msg_iovlen;
void* msg_control;
socklen_t msg_controllen;
int msg_flags;
}
struct iovec {} // from core.sys.posix.sys.uio
struct cmsghdr
{
socklen_t cmsg_len;
int cmsg_level;
int cmsg_type;
}
SCM_RIGHTS
CMSG_DATA(cmsg)
CMSG_NXTHDR(mhdr,cmsg)
CMSG_FIRSTHDR(mhdr)
struct linger
{
int l_onoff;
int l_linger;
}
SOCK_DGRAM
SOCK_SEQPACKET
SOCK_STREAM
SOL_SOCKET
SO_ACCEPTCONN
SO_BROADCAST
SO_DEBUG
SO_DONTROUTE
SO_ERROR
SO_KEEPALIVE
SO_LINGER
SO_OOBINLINE
SO_RCVBUF
SO_RCVLOWAT
SO_RCVTIMEO
SO_REUSEADDR
SO_SNDBUF
SO_SNDLOWAT
SO_SNDTIMEO
SO_TYPE
SOMAXCONN
MSG_CTRUNC
MSG_DONTROUTE
MSG_EOR
MSG_OOB
MSG_PEEK
MSG_TRUNC
MSG_WAITALL
AF_INET
AF_UNIX
AF_UNSPEC
SHUT_RD
SHUT_RDWR
SHUT_WR
int accept(int, sockaddr*, socklen_t*);
int bind(int, in sockaddr*, socklen_t);
int connect(int, in sockaddr*, socklen_t);
int getpeername(int, sockaddr*, socklen_t*);
int getsockname(int, sockaddr*, socklen_t*);
int getsockopt(int, int, int, void*, socklen_t*);
int listen(int, int);
ssize_t recv(int, void*, size_t, int);
ssize_t recvfrom(int, void*, size_t, int, sockaddr*, socklen_t*);
ssize_t recvmsg(int, msghdr*, int);
ssize_t send(int, in void*, size_t, int);
ssize_t sendmsg(int, in msghdr*, int);
ssize_t sendto(int, in void*, size_t, int, in sockaddr*, socklen_t);
int setsockopt(int, int, int, in void*, socklen_t);
int shutdown(int, int);
int socket(int, int, int);
int sockatmark(int);
int socketpair(int, int, int, ref int[2]);
*/
version( linux )
{
alias uint socklen_t;
alias ushort sa_family_t;
struct sockaddr
{
sa_family_t sa_family;
byte[14] sa_data;
}
private enum : size_t
{
_SS_SIZE = 128,
_SS_PADSIZE = _SS_SIZE - (c_ulong.sizeof * 2)
}
struct sockaddr_storage
{
sa_family_t ss_family;
c_ulong __ss_align;
byte[_SS_PADSIZE] __ss_padding;
}
struct msghdr
{
void* msg_name;
socklen_t msg_namelen;
iovec* msg_iov;
size_t msg_iovlen;
void* msg_control;
size_t msg_controllen;
int msg_flags;
}
struct cmsghdr
{
size_t cmsg_len;
int cmsg_level;
int cmsg_type;
static if( false /* (!is( __STRICT_ANSI__ ) && __GNUC__ >= 2) || __STDC_VERSION__ >= 199901L */ )
{
ubyte[1] __cmsg_data;
}
}
enum : uint
{
SCM_RIGHTS = 0x01
}
static if( false /* (!is( __STRICT_ANSI__ ) && __GNUC__ >= 2) || __STDC_VERSION__ >= 199901L */ )
{
extern (D) ubyte[1] CMSG_DATA( cmsghdr* cmsg ) { return cmsg.__cmsg_data; }
}
else
{
extern (D) ubyte* CMSG_DATA( cmsghdr* cmsg ) { return cast(ubyte*)( cmsg + 1 ); }
}
private cmsghdr* __cmsg_nxthdr(msghdr*, cmsghdr*);
alias __cmsg_nxthdr CMSG_NXTHDR;
extern (D) size_t CMSG_FIRSTHDR( msghdr* mhdr )
{
return cast(size_t)( mhdr.msg_controllen >= cmsghdr.sizeof
? cast(cmsghdr*) mhdr.msg_control
: cast(cmsghdr*) null );
}
struct linger
{
int l_onoff;
int l_linger;
}
enum
{
SOCK_DGRAM = 2,
SOCK_SEQPACKET = 5,
SOCK_STREAM = 1
}
enum
{
SOL_SOCKET = 1
}
enum
{
SO_ACCEPTCONN = 30,
SO_BROADCAST = 6,
SO_DEBUG = 1,
SO_DONTROUTE = 5,
SO_ERROR = 4,
SO_KEEPALIVE = 9,
SO_LINGER = 13,
SO_OOBINLINE = 10,
SO_RCVBUF = 8,
SO_RCVLOWAT = 18,
SO_RCVTIMEO = 20,
SO_REUSEADDR = 2,
SO_SNDBUF = 7,
SO_SNDLOWAT = 19,
SO_SNDTIMEO = 21,
SO_TYPE = 3
}
enum
{
SOMAXCONN = 128
}
enum : uint
{
MSG_CTRUNC = 0x08,
MSG_DONTROUTE = 0x04,
MSG_EOR = 0x80,
MSG_OOB = 0x01,
MSG_PEEK = 0x02,
MSG_TRUNC = 0x20,
MSG_WAITALL = 0x100
}
enum
{
AF_INET = 2,
AF_UNIX = 1,
AF_UNSPEC = 0
}
enum
{
SHUT_RD,
SHUT_WR,
SHUT_RDWR
}
int accept(int, sockaddr*, socklen_t*);
int bind(int, in sockaddr*, socklen_t);
int connect(int, in sockaddr*, socklen_t);
int getpeername(int, sockaddr*, socklen_t*);
int getsockname(int, sockaddr*, socklen_t*);
int getsockopt(int, int, int, void*, socklen_t*);
int listen(int, int);
ssize_t recv(int, void*, size_t, int);
ssize_t recvfrom(int, void*, size_t, int, sockaddr*, socklen_t*);
ssize_t recvmsg(int, msghdr*, int);
ssize_t send(int, in void*, size_t, int);
ssize_t sendmsg(int, in msghdr*, int);
ssize_t sendto(int, in void*, size_t, int, in sockaddr*, socklen_t);
int setsockopt(int, int, int, in void*, socklen_t);
int shutdown(int, int);
int socket(int, int, int);
int sockatmark(int);
int socketpair(int, int, int, ref int[2]);
}
else version( OSX )
{
alias uint socklen_t;
alias ubyte sa_family_t;
struct sockaddr
{
ubyte sa_len;
sa_family_t sa_family;
byte[14] sa_data;
}
private enum : size_t
{
_SS_PAD1 = long.sizeof - ubyte.sizeof - sa_family_t.sizeof,
_SS_PAD2 = 128 - ubyte.sizeof - sa_family_t.sizeof - _SS_PAD1 - long.sizeof
}
struct sockaddr_storage
{
ubyte ss_len;
sa_family_t ss_family;
byte[_SS_PAD1] __ss_pad1;
long __ss_align;
byte[_SS_PAD2] __ss_pad2;
}
struct msghdr
{
void* msg_name;
socklen_t msg_namelen;
iovec* msg_iov;
int msg_iovlen;
void* msg_control;
socklen_t msg_controllen;
int msg_flags;
}
struct cmsghdr
{
socklen_t cmsg_len;
int cmsg_level;
int cmsg_type;
}
enum : uint
{
SCM_RIGHTS = 0x01
}
/+
CMSG_DATA(cmsg) ((unsigned char *)(cmsg) + \
ALIGN(sizeof(struct cmsghdr)))
CMSG_NXTHDR(mhdr, cmsg) \
(((unsigned char *)(cmsg) + ALIGN((cmsg)->cmsg_len) + \
ALIGN(sizeof(struct cmsghdr)) > \
(unsigned char *)(mhdr)->msg_control +(mhdr)->msg_controllen) ? \
(struct cmsghdr *)0 /* NULL */ : \
(struct cmsghdr *)((unsigned char *)(cmsg) + ALIGN((cmsg)->cmsg_len)))
CMSG_FIRSTHDR(mhdr) ((struct cmsghdr *)(mhdr)->msg_control)
+/
struct linger
{
int l_onoff;
int l_linger;
}
enum
{
SOCK_DGRAM = 2,
SOCK_SEQPACKET = 5,
SOCK_STREAM = 1
}
enum : uint
{
SOL_SOCKET = 0xffff
}
enum : uint
{
SO_ACCEPTCONN = 0x0002,
SO_BROADCAST = 0x0020,
SO_DEBUG = 0x0001,
SO_DONTROUTE = 0x0010,
SO_ERROR = 0x1007,
SO_KEEPALIVE = 0x0008,
SO_LINGER = 0x1080,
SO_NOSIGPIPE = 0x1022, // non-standard
SO_OOBINLINE = 0x0100,
SO_RCVBUF = 0x1002,
SO_RCVLOWAT = 0x1004,
SO_RCVTIMEO = 0x1006,
SO_REUSEADDR = 0x0004,
SO_SNDBUF = 0x1001,
SO_SNDLOWAT = 0x1003,
SO_SNDTIMEO = 0x1005,
SO_TYPE = 0x1008
}
enum
{
SOMAXCONN = 128
}
enum : uint
{
MSG_CTRUNC = 0x20,
MSG_DONTROUTE = 0x4,
MSG_EOR = 0x8,
MSG_OOB = 0x1,
MSG_PEEK = 0x2,
MSG_TRUNC = 0x10,
MSG_WAITALL = 0x40
}
enum
{
AF_INET = 2,
AF_UNIX = 1,
AF_UNSPEC = 0
}
enum
{
SHUT_RD,
SHUT_WR,
SHUT_RDWR
}
int accept(int, sockaddr*, socklen_t*);
int bind(int, in sockaddr*, socklen_t);
int connect(int, in sockaddr*, socklen_t);
int getpeername(int, sockaddr*, socklen_t*);
int getsockname(int, sockaddr*, socklen_t*);
int getsockopt(int, int, int, void*, socklen_t*);
int listen(int, int);
ssize_t recv(int, void*, size_t, int);
ssize_t recvfrom(int, void*, size_t, int, sockaddr*, socklen_t*);
ssize_t recvmsg(int, msghdr*, int);
ssize_t send(int, in void*, size_t, int);
ssize_t sendmsg(int, in msghdr*, int);
ssize_t sendto(int, in void*, size_t, int, in sockaddr*, socklen_t);
int setsockopt(int, int, int, in void*, socklen_t);
int shutdown(int, int);
int socket(int, int, int);
int sockatmark(int);
int socketpair(int, int, int, ref int[2]);
}
else version( FreeBSD )
{
alias uint socklen_t;
alias ubyte sa_family_t;
struct sockaddr
{
ubyte sa_len;
sa_family_t sa_family;
byte[14] sa_data;
}
private
{
enum _SS_ALIGNSIZE = long.sizeof;
enum _SS_MAXSIZE = 128;
enum _SS_PAD1SIZE = _SS_ALIGNSIZE - ubyte.sizeof - sa_family_t.sizeof;
enum _SS_PAD2SIZE = _SS_MAXSIZE - ubyte.sizeof - sa_family_t.sizeof - _SS_PAD1SIZE - _SS_ALIGNSIZE;
}
struct sockaddr_storage
{
ubyte ss_len;
sa_family_t ss_family;
byte[_SS_PAD1SIZE] __ss_pad1;
long __ss_align;
byte[_SS_PAD2SIZE] __ss_pad2;
}
struct msghdr
{
void* msg_name;
socklen_t msg_namelen;
iovec* msg_iov;
int msg_iovlen;
void* msg_control;
socklen_t msg_controllen;
int msg_flags;
}
struct cmsghdr
{
socklen_t cmsg_len;
int cmsg_level;
int cmsg_type;
}
enum : uint
{
SCM_RIGHTS = 0x01
}
private // <machine/param.h>
{
enum _ALIGNBYTES = /+c_int+/ int.sizeof - 1;
extern (D) size_t _ALIGN( size_t p ) { return (p + _ALIGNBYTES) & ~_ALIGNBYTES; }
}
extern (D) ubyte* CMSG_DATA( cmsghdr* cmsg )
{
return cast(ubyte*) cmsg + _ALIGN( cmsghdr.sizeof );
}
extern (D) cmsghdr* CMSG_NXTHDR( msghdr* mhdr, cmsghdr* cmsg )
{
if( cmsg == null )
{
return CMSG_FIRSTHDR( mhdr );
}
else
{
if( cast(ubyte*) cmsg + _ALIGN( cmsg.cmsg_len ) + _ALIGN( cmsghdr.sizeof ) >
cast(ubyte*) mhdr.msg_control + mhdr.msg_controllen )
return null;
else
return cast(cmsghdr*) (cast(ubyte*) cmsg + _ALIGN( cmsg.cmsg_len ));
}
}
extern (D) cmsghdr* CMSG_FIRSTHDR( msghdr* mhdr )
{
return mhdr.msg_controllen >= cmsghdr.sizeof ? cast(cmsghdr*) mhdr.msg_control : null;
}
struct linger
{
int l_onoff;
int l_linger;
}
enum
{
SOCK_DGRAM = 2,
SOCK_SEQPACKET = 5,
SOCK_STREAM = 1
}
enum : uint
{
SOL_SOCKET = 0xffff
}
enum : uint
{
SO_ACCEPTCONN = 0x0002,
SO_BROADCAST = 0x0020,
SO_DEBUG = 0x0001,
SO_DONTROUTE = 0x0010,
SO_ERROR = 0x1007,
SO_KEEPALIVE = 0x0008,
SO_LINGER = 0x0080,
SO_NOSIGPIPE = 0x0800, // non-standard
SO_OOBINLINE = 0x0100,
SO_RCVBUF = 0x1002,
SO_RCVLOWAT = 0x1004,
SO_RCVTIMEO = 0x1006,
SO_REUSEADDR = 0x0004,
SO_SNDBUF = 0x1001,
SO_SNDLOWAT = 0x1003,
SO_SNDTIMEO = 0x1005,
SO_TYPE = 0x1008
}
enum
{
SOMAXCONN = 128
}
enum : uint
{
MSG_CTRUNC = 0x20,
MSG_DONTROUTE = 0x4,
MSG_EOR = 0x8,
MSG_OOB = 0x1,
MSG_PEEK = 0x2,
MSG_TRUNC = 0x10,
MSG_WAITALL = 0x40
}
enum
{
AF_INET = 2,
AF_UNIX = 1,
AF_UNSPEC = 0
}
enum
{
SHUT_RD = 0,
SHUT_WR = 1,
SHUT_RDWR = 2
}
int accept(int, sockaddr*, socklen_t*);
int bind(int, in sockaddr*, socklen_t);
int connect(int, in sockaddr*, socklen_t);
int getpeername(int, sockaddr*, socklen_t*);
int getsockname(int, sockaddr*, socklen_t*);
int getsockopt(int, int, int, void*, socklen_t*);
int listen(int, int);
ssize_t recv(int, void*, size_t, int);
ssize_t recvfrom(int, void*, size_t, int, sockaddr*, socklen_t*);
ssize_t recvmsg(int, msghdr*, int);
ssize_t send(int, in void*, size_t, int);
ssize_t sendmsg(int, in msghdr*, int);
ssize_t sendto(int, in void*, size_t, int, in sockaddr*, socklen_t);
int setsockopt(int, int, int, in void*, socklen_t);
int shutdown(int, int);
int socket(int, int, int);
int sockatmark(int);
int socketpair(int, int, int, ref int[2]);
}
else version (Solaris)
{
alias uint socklen_t;
alias ushort sa_family_t;
struct sockaddr
{
sa_family_t sa_family;
char[14] sa_data;
}
alias double sockaddr_maxalign_t;
private enum _SS_PAD1SIZE = sockaddr_maxalign_t.sizeof - sa_family_t.sizeof;
private enum _SS_PAD2SIZE = 256 - sa_family_t.sizeof + _SS_PAD1SIZE + sockaddr_maxalign_t.sizeof;
struct sockaddr_storage
{
sa_family_t ss_family;
char[_SS_PAD1SIZE] _ss_pad1;
sockaddr_maxalign_t _ss_align;
char[_SS_PAD2SIZE] _ss_pad2;
}
struct msghdr
{
void* msg_name;
socklen_t msg_namelen;
iovec* msg_iov;
int msg_iovlen;
void* msg_control;
socklen_t msg_controllen;
int msg_flags;
}
struct cmsghdr
{
socklen_t cmsg_len;
int cmsg_level;
int cmsg_type;
}
enum : uint
{
SCM_RIGHTS = 0x1011
}
struct linger
{
int l_onoff;
int l_linger;
}
enum
{
SOCK_STREAM = 2,
SOCK_DGRAM = 1,
SOCK_RDM = 5,
SOCK_SEQPACKET = 6,
}
enum : uint
{
SOL_SOCKET = 0xffff
}
enum : uint
{
SO_ACCEPTCONN = 0x0002,
SO_BROADCAST = 0x0020,
SO_DEBUG = 0x0001,
SO_DONTROUTE = 0x0010,
SO_ERROR = 0x1007,
SO_KEEPALIVE = 0x0008,
SO_LINGER = 0x0080,
SO_OOBINLINE = 0x0100,
SO_RCVBUF = 0x1002,
SO_RCVLOWAT = 0x1004,
SO_RCVTIMEO = 0x1006,
SO_REUSEADDR = 0x0004,
SO_SNDBUF = 0x1001,
SO_SNDLOWAT = 0x1003,
SO_SNDTIMEO = 0x1005,
SO_TYPE = 0x1008
}
enum
{
SOMAXCONN = 128
}
enum : uint
{
MSG_CTRUNC = 0x10,
MSG_DONTROUTE = 0x4,
MSG_EOR = 0x8,
MSG_OOB = 0x1,
MSG_PEEK = 0x2,
MSG_TRUNC = 0x20,
MSG_WAITALL = 0x40
}
enum
{
AF_INET = 2,
AF_UNIX = 1,
AF_UNSPEC = 0
}
enum
{
SHUT_RD,
SHUT_WR,
SHUT_RDWR
}
int accept(int, sockaddr*, socklen_t*);
int bind(int, in sockaddr*, socklen_t);
int connect(int, in sockaddr*, socklen_t);
int getpeername(int, sockaddr*, socklen_t*);
int getsockname(int, sockaddr*, socklen_t*);
int getsockopt(int, int, int, void*, socklen_t*);
int listen(int, int);
ssize_t recv(int, void*, size_t, int);
ssize_t recvfrom(int, void*, size_t, int, sockaddr*, socklen_t*);
ssize_t recvmsg(int, msghdr*, int);
ssize_t send(int, in void*, size_t, int);
ssize_t sendmsg(int, in msghdr*, int);
ssize_t sendto(int, in void*, size_t, int, in sockaddr*, socklen_t);
int setsockopt(int, int, int, in void*, socklen_t);
int shutdown(int, int);
int socket(int, int, int);
int sockatmark(int);
int socketpair(int, int, int, ref int[2]);
}
else
{
static assert(false, "Unsupported platform");
}
//
// IPV6 (IP6)
//
/*
AF_INET6
*/
version( linux )
{
enum
{
AF_INET6 = 10
}
}
else version( OSX )
{
enum
{
AF_INET6 = 30
}
}
else version( FreeBSD )
{
enum
{
AF_INET6 = 28
}
}
else version (Solaris)
{
enum
{
AF_INET6 = 26,
}
}
else
{
static assert(false, "Unsupported platform");
}
//
// Raw Sockets (RS)
//
/*
SOCK_RAW
*/
version( linux )
{
enum
{
SOCK_RAW = 3
}
}
else version( OSX )
{
enum
{
SOCK_RAW = 3
}
}
else version( FreeBSD )
{
enum
{
SOCK_RAW = 3
}
}
else version (Solaris)
{
enum
{
SOCK_RAW = 4,
}
}
else
{
static assert(false, "Unsupported platform");
}
|
D
|
module jamu.assembler.exceptions;
import std.conv;
import std.format;
import std.stdio;
import std.string;
import std.file : readText;
import colorize : fg, color, cwrite, cwriteln, cwritefln;
import jamu.assembler.tokens;
import jamu.assembler.ast;
// Helper function to turn tabs into spaces. Harder than it looks because
// a tab has a different size depending on its location
private string tabs2Spaces(string s) pure {
enum tabLength = 8;
string r = "";
foreach (c; s) {
if (c == '\t') {
r ~= " ";
while (r.length % tabLength != 0) { r ~= " "; }
} else {
r ~= c;
}
}
return r;
}
class AssemblerError {
Loc location;
ulong length = 1;
string message;
string exceptionType;
string fileSource() {
return readText(location.fileName);
}
private void printFileLocation(Loc fileLoc, string message = "", fg errorColor = fg.red) {
// Get line text and replace tabs with spaces
string lineText = fileSource.split('\n')[fileLoc.lineNumber - 1];
string lineNumberString = format("%3d | ", fileLoc.lineNumber);
auto offset = lineText[0..fileLoc.charNumber].tabs2Spaces().length;
lineText = lineText.tabs2Spaces();
// Write the line
cwriteln(lineNumberString.color(fg.blue), lineText);
// Add annotations
if (message.length) {
cwrite(" | ".color(fg.blue));
writef("%*s", offset, "");
foreach(i; 0..this.length) {
cwrite("^".color(errorColor));
}
cwriteln((" " ~ message).color(errorColor));
}
}
void printError() {
cwriteln(("[" ~ exceptionType ~ "] ").color(fg.red), message);
cwriteln(" --> ".color(fg.blue) ~ this.location.toString());
cwriteln(" |".color(fg.blue));
printFileLocation(location, message);
}
}
class LexError : AssemblerError {
this(Loc location, uint length, string message) {
this.location = location;
this.length = length;
this.message = message;
this.exceptionType = "Lex Error";
}
}
class LexException: Exception {
LexError[] errors;
this(LexError[] errors, string file = __FILE__, size_t line = __LINE__) {
this.errors = errors;
string msg = errors[0].message;
super(msg, file, line);
}
}
class ParseError: AssemblerError {
this(Token t, string message) {
this.location = t.location;
this.length = t.value.length;
this.message = message;
this.exceptionType = "Parse Error";
}
}
class ParseException: Exception {
ParseError[] errors;
this(ParseError[] errors, string file = __FILE__, size_t line = __LINE__) {
this.errors = errors;
string msg = errors[0].message;
super(msg, file, line);
}
}
class TypeError: AssemblerError {
this(Instruction ins, string message) {
this.location = ins.meta.location;
this.length = ins.meta.tokens[0].value.length;
this.message = message;
this.exceptionType = "Type Error";
}
this(Token tok, string message) {
this.location = tok.location;
this.length = tok.value.length;
this.message = message;
this.exceptionType = "Type Error";
}
}
class TypeException : Exception {
TypeError[] errors;
this(TypeError[] errors, string file = __FILE__, size_t line = __LINE__) {
this.errors = errors;
string msg = errors[0].message;
super(msg, file, line);
}
}
|
D
|
///////////////////////////////////////////////////////////////////////
// Info EXIT
///////////////////////////////////////////////////////////////////////
instance Infos_Mil_9_Exit (C_INFO)
{
nr = 999;
condition = Infos_Mil_9_Exit_Condition;
information = Infos_Mil_9_Exit_Info;
permanent = TRUE;
description = DIALOG_ENDE;
};
FUNC int Infos_Mil_9_Exit_Condition()
{
return TRUE;
};
FUNC VOID Infos_Mil_9_Exit_Info()
{
AI_StopProcessInfos ( self );
};
///////////////////////////////////////////////////////////////////////
// Info HI
///////////////////////////////////////////////////////////////////////
instance Infos_Mil_9_HI (C_INFO)
{
condition = Infos_Mil_9_HI_Condition;
information = Infos_Mil_9_HI_Info;
description = "Wie läufts?";
permanent = TRUE;
};
FUNC int Infos_Mil_9_HI_Condition()
{
return TRUE;
};
FUNC void Infos_Mil_9_HI_Info()
{
AI_Output (other, self,"Infos_Mil_9_HI_Info_15_01"); //Wie läufts?
AI_Output (self, other,"Infos_Mil_9_HI_Info_06_02"); //(brummig) jaja, läuft gut.
};
///////////////////////////////////////////////////////////////////////
// Info FOODGOOD
///////////////////////////////////////////////////////////////////////
instance Info_Mil_9_FOODGOOD (C_INFO)
{
condition = Info_Mil_9_FOODGOOD_Condition;
information = Info_Mil_9_FOODGOOD_Info;
permanent = TRUE;
description = "Übles Essen hier! Willst du dir etwas Silber verdienen?";
};
func int Info_Mil_9_FOODGOOD_Condition()
{
if B_LunchTimeAtHalvors()
&& (self.aivar[AIV_DEALDAY] < B_GetDay())
&& Npc_KnowsInfo(hero, MIL_100_Halvor_SNAF)
{
return TRUE;
};
};
func void Info_Mil_9_FOODGOOD_Info()
{
AI_Output (hero, self,"Info_Mil_9_FOODGOOD_15_01"); //Übles Essen hier! Willst du dir etwas Silber verdienen?
if (Npc_HasItems(hero, ItMi_Silver) >= SNAF_BRIBE_SUM)
{
AI_Output (self, hero,"Info_Mil_9_FOODGOOD_09_03"); //Was muss ich dafür machen?
AI_Output (hero, self,"Info_Mil_9_FOODGOOD_15_04"); //Kauf dein Mittagessen ab morgen bei Snaf im Aussenring!
AI_Output (self, hero,"Info_Mil_9_FOODGOOD_09_05"); //Warum nicht, dort schmeckt es zwar nicht ganz so gut, aber Silber ist Silber!
B_GiveInvItems (hero, self, ItMi_Silver, SNAF_BRIBE_SUM);
self.aivar[AIV_DEALDAY] = B_GetDay();
Snaf_MilitiaBribed = Snaf_MilitiaBribed + 1;
if ((Snaf_MilitiaBribed + Snaf_MilitiaFrightened) >= SNAF_NEW_CUSTOMERS)
{
B_Snaf_NewCustomers();
};
}
else
{
B_Say (self, hero, "$NotEnoughSilver");
};
};
///////////////////////////////////////////////////////////////////////
// Info JOIN
///////////////////////////////////////////////////////////////////////
instance Infos_Mil_9_JOIN (C_INFO)
{
condition = Infos_Mil_9_JOIN_Condition;
information = Infos_Mil_9_JOIN_Info;
description = "Könnt ihr noch einen Mann gebrauchen?";
permanent = TRUE;
};
FUNC int Infos_Mil_9_JOIN_Condition()
{
return TRUE;
};
FUNC void Infos_Mil_9_JOIN_Info()
{
AI_Output (other, self,"Infos_Mil_9_JOIN_Info_15_01"); //Könnt ihr noch einen Mann gebrauchen?
AI_Output (self, other,"Infos_Mil_9_JOIN_Info_06_02"); //Das solltest du dir gut überlegen. Bei uns ist Disziplin gefordert.
AI_Output (self, other,"Infos_Mil_9_JOIN_Info_06_03"); //Selbst wenn du keine Aufgaben hast, hast du Aufgaben. Jeden Tag musst du dich einmal melden.
AI_Output (self, other,"Infos_Mil_9_JOIN_Info_06_04"); //Wenn du das wirklich willst, dann sprich mal mit Cassian. Er ist Leutnant und kümmert sich um die Neuen.
Info_ClearChoices (Infos_Mil_9_JOIN);
};
///////////////////////////////////////////////////////////////////////
// Info STORY
///////////////////////////////////////////////////////////////////////
instance Infos_Mil_9_STORY (C_INFO)
{
condition = Infos_Mil_9_STORY_Condition;
information = Infos_Mil_9_STORY_Info;
permanent = TRUE;
description = "Erzähl mir was über die Orks";
};
FUNC int Infos_Mil_9_STORY_Condition()
{
return TRUE;
};
FUNC void Infos_Mil_9_STORY_Info()
{
AI_Output (other, self,"Infos_Mil_9_STORY_Info_15_01"); //Erzähl mir was über die Orks.
AI_Output (self, other,"Infos_Mil_9_STORY_Info_09_02"); //Man darf nicht den Fehler machen, sie zu unterschätzen. Es sind keine Wilden, gegen die wir da kämpfen.
AI_Output (self, other,"Infos_Mil_9_STORY_Info_09_03"); //Sie haben eine Kultur die wahrscheinlich älter ist, als die der Menschen.
AI_Output (self, other,"Infos_Mil_9_STORY_Info_09_04"); //Aber das gefährliche ist, das sie leben um zu kämpfen. Und sie kämpfen um zu sterben.
};
///////////////////////////////////////////////////////////////////////
// Info STORY
///////////////////////////////////////////////////////////////////////
instance Infos_Mil_9_BOSS (C_INFO)
{
condition = Infos_Mil_9_BOSS_Condition;
information = Infos_Mil_9_BOSS_Info;
permanent = TRUE;
description = "Wer hat hier das Sagen?";
};
FUNC int Infos_Mil_9_BOSS_Condition()
{
var C_NPC Berengar; Berengar = Hlp_GetNpc (MIL_103_Berengar);
var C_NPC Cassian; Cassian = Hlp_GetNpc (MIL_119_Cassian);
var C_NPC Brutus; Brutus = Hlp_GetNpc (MIL_121_Brutus);
if (Berengar.aivar[AIV_FINDABLE] == FALSE)
|| (Cassian.aivar[AIV_FINDABLE] == FALSE)
|| (Brutus.aivar[AIV_FINDABLE] == FALSE)
{
return TRUE;
};
};
FUNC void Infos_Mil_9_BOSS_Info()
{
AI_Output (other, self,"Infos_Mil_9_BOSS_Info_15_01"); //Wer hat hier das Sagen?
AI_Output (self, other,"Infos_Mil_9_BOSS_Info_09_02"); //Hauptmann Berengar führt das Kommando. Er hat zwei Leutnants die seine Befehle weitergeben, Cassian und Brutus.
var C_NPC Berengar; Berengar = Hlp_GetNpc (MIL_103_Berengar);
Berengar.aivar[AIV_FINDABLE] = TRUE;
var C_NPC Cassian; Cassian = Hlp_GetNpc (MIL_119_Cassian);
Cassian.aivar[AIV_FINDABLE] = TRUE;
var C_NPC Brutus; Brutus = Hlp_GetNpc (MIL_121_Brutus);
Brutus.aivar[AIV_FINDABLE] = TRUE;
};
///////////////////////////////////////////////////////////////////////
// Zuweisung der Infos zum NSC
///////////////////////////////////////////////////////////////////////
FUNC VOID B_AssignAmbientInfos_Mil_9(var c_NPC slf)
{
B_AssignFindNpc_MIL (slf);
Infos_Mil_9_Exit.npc = Hlp_GetInstanceID (slf);
Infos_Mil_9_HI.npc = Hlp_GetInstanceID (slf);
//Infos_Mil_9_JOIN.npc = Hlp_GetInstanceID (slf);
Infos_Mil_9_STORY.npc = Hlp_GetInstanceID (slf);
Infos_Mil_9_BOSS.npc = Hlp_GetInstanceID (slf);
Info_Mil_9_FOODGOOD.npc = Hlp_GetInstanceID (slf);
};
|
D
|
/Users/Shashi/Documents/cunyhackathon/StudyBuddy/build/StudyBuddy.build/Debug-iphonesimulator/StudyBuddy.build/Objects-normal/x86_64/User.o : /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/LoginViewController.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/WelcomePageViewController.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/UserData.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/DetailTableViewController.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/User.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/StudySessionsData.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/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/SwiftOnoneSupport.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
/Users/Shashi/Documents/cunyhackathon/StudyBuddy/build/StudyBuddy.build/Debug-iphonesimulator/StudyBuddy.build/Objects-normal/x86_64/User~partial.swiftmodule : /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/LoginViewController.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/WelcomePageViewController.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/UserData.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/DetailTableViewController.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/User.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/StudySessionsData.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/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/SwiftOnoneSupport.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
/Users/Shashi/Documents/cunyhackathon/StudyBuddy/build/StudyBuddy.build/Debug-iphonesimulator/StudyBuddy.build/Objects-normal/x86_64/User~partial.swiftdoc : /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/LoginViewController.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/WelcomePageViewController.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/UserData.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/DetailTableViewController.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/User.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/StudySessionsData.swift /Users/Shashi/Documents/cunyhackathon/StudyBuddy/StudyBuddy/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/SwiftOnoneSupport.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
|
D
|
/***********************************************************************\
* pbt.d *
* *
* Windows API header module *
* *
* Translated from MinGW Windows headers *
* by Stewart Gordon *
* *
* Placed into public domain *
\***********************************************************************/
module win32.pbt;
version(Windows):
private import win32.windef;
enum : WPARAM {
PBT_APMQUERYSUSPEND,
PBT_APMQUERYSTANDBY,
PBT_APMQUERYSUSPENDFAILED,
PBT_APMQUERYSTANDBYFAILED,
PBT_APMSUSPEND,
PBT_APMSTANDBY,
PBT_APMRESUMECRITICAL,
PBT_APMRESUMESUSPEND,
PBT_APMRESUMESTANDBY,
PBT_APMBATTERYLOW,
PBT_APMPOWERSTATUSCHANGE,
PBT_APMOEMEVENT // = 11
}
const LPARAM PBTF_APMRESUMEFROMFAILURE = 1;
|
D
|
module tests;
import std.algorithm.iteration;
import std.complex;
import std.conv;
import std.datetime;
import std.datetime.systime;
import std.datetime.timezone;
import std.format;
import std.path;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.utf;
import std.variant;
import dunit;
import config;
void assertIn(string s1, string s2, lazy string msg = null,
string file = __FILE__, size_t line = __LINE__)
{
if (s2.indexOf(s1) >= 0) {
return;
}
string message = (msg !is null) ? msg : format!"'%s' not found in '%s'"(s1, s2);
fail(message, file, line);
}
class BaseTest {
static auto SEPARATOR_PATTERN = regex("^-- ([A-Z]\\d+) -+");
public string[string] loadData(string filename) {
string[string] result;
auto key = "";
string[] lines = new string[0];
auto f = File(filename, "r");
foreach(line; f.byLine()) {
auto m = line.matchFirst(SEPARATOR_PATTERN);
if (m.empty) {
lines ~= to!string(line);
}
else {
if ((key != "") && (lines.length > 0)) {
result[key] = lines.join("\n");
}
key = to!string(m[1]);
lines = new string[0];
}
}
f.close();
return result;
}
public ASTNode[string] toMap(MappingNode node) {
ASTNode[string] result;
foreach(kvp; node.elements) {
auto key = (cast(Token) kvp.key).value.toString();
result[key] = kvp.value;
}
return result;
}
Token W(string s) {
Variant v = null;
return new Token(TokenKind.Word, s, v);
}
Token S(string s, string val) {
Variant v = val;
return new Token(TokenKind.String, s, v);
}
Token N(long n) {
Variant v = n;
return new Token(TokenKind.Integer, format!"%d"(n), v);
}
SliceNode SN(ASTNode start, ASTNode stop, ASTNode step) {
return new SliceNode(start, stop, step);
}
void compareObjects(Object e, Object a, Object context=null) {
if ((e is null) && (a is null)) {
return;
}
auto equal = (e !is null) && (a !is null);
if (equal) {
equal = typeid(e) == typeid(a);
}
if (equal) {
if (typeid(e) == typeid(Object[])) {
//auto ea = cast(Object[])e;
//auto aa = cast(Object[]) a;
//compareArrays(ea, aa);
}
else if (typeid(e) == typeid(UnaryNode)) {
auto en = cast(UnaryNode) e;
auto an = cast(UnaryNode) a;
assertEquals(en.kind, an.kind);
compareObjects(en.operand, an.operand);
}
else if (typeid(e) == typeid(BinaryNode)) {
auto en = cast(BinaryNode) e;
auto an = cast(BinaryNode) a;
assertEquals(en.kind, an.kind);
compareObjects(en.left, an.left);
compareObjects(en.right, an.right);
}
else if (typeid(e) == typeid(SliceNode)) {
auto en = cast(SliceNode) e;
auto an = cast(SliceNode) a;
assertEquals(en.kind, an.kind);
compareObjects(en.start, an.start);
compareObjects(en.stop, an.stop);
compareObjects(en.step, an.step);
}
else if (typeid(e) == typeid(Token)) {
auto et = cast(Token) e;
auto at = cast(Token) a;
assertEquals(et.kind, at.kind);
assertEquals(et.text, at.text);
assertEquals(et.value, at.value);
}
}
if (!equal) {
auto s = (context is null) ? "" : format!" (%s)"(context);
auto msg = format!"Failed%s: expected %s, actual %s"(s, e, a);
}
}
void compareArrays(Object[] e, Object[] a) {
assertEquals(e.length, a.length);
for (auto i = 0; i < e.length; i++) {
compareObjects(e[i], a[i]);
}
}
string dataFilePath(string[] s...) {
s.insertInPlace(0, "resources");
return buildPath(s);
}
}
class TokenizerTests : BaseTest {
mixin UnitTest;
@Test
public void location()
{
Location loc = new Location();
assertEquals(1, loc.line);
assertEquals(1, loc.column);
loc.nextLine();
assertEquals(2, loc.line);
assertEquals(1, loc.column);
}
@Test
public void decoding() {
auto f = File(dataFilePath("all_unicode.bin"));
auto r = inputRangeObject(f.byChunk(8192).joiner);
auto d = new Decoder(r);
auto i = 0;
for (i = 0; i < 0xD800; i++) {
auto c = d.decode();
assertEquals(i, cast(int) c);
}
for (i = 0xE000; i < 0x110000; i++) {
auto c = d.decode();
assertEquals(i, cast(int) c);
}
}
@Test
public void decoding_edge_cases() {
ubyte[] invalid = new ubyte[1];
invalid[0] = 195;
auto r = inputRangeObject(invalid);
auto d = new Decoder(r);
auto e = expectThrows(d.decode());
assertEquals(e.msg, "Decoding error");
}
@Test
public void locations() {
alias Position = Tuple!(int, "sline", int, "scol", int, "eline", int, "ecol");
Position[] positions = new Position[0];
auto f = File(dataFilePath("pos.forms.cfg.txt"), "r");
foreach (line; f.byLine()) {
auto parts = line.split().map!(s => to!int(s));
positions ~= Position(parts[0], parts[1], parts[2], parts[3]);
}
f.close();
f = File(dataFilePath("forms.cfg"));
auto r = inputRangeObject(f.byChunk(8192).joiner);
auto tokenizer = new Tokenizer(r);
foreach (i, position; positions.enumerate()) {
auto token = tokenizer.getToken();
//if (i == 3455) {
// writeln("about to fail");
//}
assertEquals(position.sline, token.start.line);
assertEquals(position.scol, token.start.column);
assertEquals(position.eline, token.end.line);
assertEquals(position.ecol, token.end.column);
}
}
private Tokenizer makeTokenizer(string s) {
auto r = inputRangeObject(s.representation.map!(b => ubyte(b)));
return new Tokenizer(r);
}
void compareLocations(Location e, Location a) {
assertEquals(e.line, a.line);
assertEquals(e.column, a.column);
}
@Test
public void tokens() {
auto tokenizer = makeTokenizer("");
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
tokenizer = makeTokenizer("# a comment\n");
auto token = tokenizer.getToken();
assertEquals(TokenKind.Newline, token.kind);
assertEquals(token.text, "# a comment");
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
tokenizer = makeTokenizer("foo");
token = tokenizer.getToken();
assertEquals(TokenKind.Word, token.kind);
assertEquals("foo", token.text);
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
tokenizer = makeTokenizer("'foo'");
token = tokenizer.getToken();
assertEquals(TokenKind.String, token.kind);
assertEquals("'foo'", token.text);
assertEquals("foo", token.value.get!string);
compareLocations(new Location(1, 1), token.start);
compareLocations(new Location(1, 5), token.end);
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
tokenizer = makeTokenizer("2.71828");
token = tokenizer.getToken();
assertEquals(TokenKind.Float, token.kind);
assertEquals("2.71828", token.text);
assertEquals(2.71828, token.value.get!(double));
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
tokenizer = makeTokenizer(".5");
token = tokenizer.getToken();
assertEquals(TokenKind.Float, token.kind);
assertEquals(".5", token.text);
assertEquals(0.5, token.value.get!(double));
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
tokenizer = makeTokenizer("-.5");
token = tokenizer.getToken();
assertEquals(TokenKind.Float, token.kind);
assertEquals("-.5", token.text);
assertEquals(-0.5, token.value.get!(double));
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
tokenizer = makeTokenizer("0x123aBc");
token = tokenizer.getToken();
assertEquals(TokenKind.Integer, token.kind);
assertEquals("0x123aBc", token.text);
assertEquals(0x123abcL, token.value);
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
tokenizer = makeTokenizer("0o123");
token = tokenizer.getToken();
assertEquals(TokenKind.Integer, token.kind);
assertEquals("0o123", token.text);
assertEquals(83L, token.value);
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
tokenizer = makeTokenizer("0123");
token = tokenizer.getToken();
assertEquals(TokenKind.Integer, token.kind);
assertEquals("0123", token.text);
assertEquals(83L, token.value);
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
tokenizer = makeTokenizer("0b0001_0110_0111");
token = tokenizer.getToken();
assertEquals(TokenKind.Integer, token.kind);
assertEquals("0b0001_0110_0111", token.text);
assertEquals(0x167L, token.value);
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
tokenizer = makeTokenizer("-4");
token = tokenizer.getToken();
assertEquals(TokenKind.Integer, token.kind);
assertEquals("-4", token.text);
assertEquals(-4L, token.value);
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
tokenizer = makeTokenizer("-4e8");
token = tokenizer.getToken();
assertEquals(TokenKind.Float, token.kind);
assertEquals("-4e8", token.text);
assertEquals(-4e8, token.value.get!(double));
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
tokenizer = makeTokenizer("1e8");
token = tokenizer.getToken();
assertEquals(TokenKind.Float, token.kind);
assertEquals("1e8", token.text);
assertEquals(1e8, token.value.get!(double));
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
tokenizer = makeTokenizer("1e-8");
token = tokenizer.getToken();
assertEquals(TokenKind.Float, token.kind);
assertEquals("1e-8", token.text);
assertEquals(1e-8, token.value.get!(double));
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
tokenizer = makeTokenizer("4.3j");
token = tokenizer.getToken();
assertEquals(TokenKind.Complex, token.kind);
assertEquals("4.3j", token.text);
assertEquals(complex(0.0, 4.3), token.value.get!(Complex!double));
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
alias Empty = Tuple!(string, "source", int, "line", int, "column");
auto empties = [
Empty("''", 1, 2),
Empty("\"\"", 1, 2),
Empty("''''''", 1, 6),
Empty("\"\"\"\"\"\"", 1, 6)
];
foreach (empty; empties) {
tokenizer = makeTokenizer(empty.source);
token = tokenizer.getToken();
assertEquals(TokenKind.String, token.kind);
assertEquals(empty.source, token.text);
assertEquals("", token.value.get!(string));
compareLocations(new Location(empty.line, empty.column), token.end);
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
}
auto s = "\"\"\"abc\ndef\n\"\"\"";
tokenizer = makeTokenizer(s);
token = tokenizer.getToken();
assertEquals(TokenKind.String, token.kind);
assertEquals(s, token.text);
assertEquals("abc\ndef\n", token.value.get!(string));
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
s = "'\\n'";
tokenizer = makeTokenizer(s);
token = tokenizer.getToken();
assertEquals(TokenKind.String, token.kind);
assertEquals(s, token.text);
assertEquals("\n", token.value.get!(string));
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
auto punct = "< > { } [ ] ( ) + - * / ** // % . <= <> << >= >> == != , : @ ~ & | ^ $ && ||";
tokenizer = makeTokenizer(punct);
auto parts = split(punct);
parts ~= "";
auto expectedKinds = [
TokenKind.LessThan, TokenKind.GreaterThan, TokenKind.LeftCurly, TokenKind.RightCurly,
TokenKind.LeftBracket, TokenKind.RightBracket, TokenKind.LeftParenthesis, TokenKind.RightParenthesis,
TokenKind.Plus, TokenKind.Minus, TokenKind.Star, TokenKind.Slash, TokenKind.Power, TokenKind.SlashSlash,
TokenKind.Modulo, TokenKind.Dot, TokenKind.LessThanOrEqual, TokenKind.AltUnequal, TokenKind.LeftShift,
TokenKind.GreaterThanOrEqual, TokenKind.RightShift, TokenKind.Equal, TokenKind.Unequal, TokenKind.Comma,
TokenKind.Colon, TokenKind.At, TokenKind.BitwiseComplement, TokenKind.BitwiseAnd, TokenKind.BitwiseOr,
TokenKind.BitwiseXor, TokenKind.Dollar, TokenKind.And, TokenKind.Or,
TokenKind.EOF
];
assertEquals(parts.length, expectedKinds.length);
for (auto i = 0; i < parts.length; i++) {
token = tokenizer.getToken();
assertEquals(parts[i], token.text);
assertEquals(expectedKinds[i], token.kind);
}
auto keywords = "true false null is in not and or";
tokenizer = makeTokenizer(keywords);
parts = split(keywords);
parts ~= "";
expectedKinds = [
TokenKind.True, TokenKind.False, TokenKind.None, TokenKind.Is,
TokenKind.In, TokenKind.Not, TokenKind.And, TokenKind.Or,
TokenKind.EOF
];
assertEquals(parts.length, expectedKinds.length);
for (auto i = 0; i < parts.length; i++) {
token = tokenizer.getToken();
assertEquals(parts[i], token.text);
assertEquals(expectedKinds[i], token.kind);
switch (token.kind) {
case TokenKind.False:
assertFalse(token.value.get!(bool));
break;
case TokenKind.True:
assertTrue(token.value.get!(bool));
break;
case TokenKind.None:
assertEquals(NullValue, token.value.get!(immutable(Object)));
break;
default:
break;
}
}
auto newlines = "\n \r \r\n";
tokenizer = makeTokenizer(newlines);
for (auto i = 0; i < 4; i++) {
token = tokenizer.getToken();
auto expected = (i < 3) ? TokenKind.Newline : TokenKind.EOF;
assertEquals(expected, token.kind);
}
}
@Test
public void badTokens() {
alias Case = Tuple!(string, "source", string, "message", int, "line", int, "column");
auto badNumbers = [
Case("9a", "invalid character in number", 1, 2),
Case("079", "invalid character in number", 1, 1),
Case("0xaBcz", "invalid character in number", 1, 6),
Case("0o79", "invalid character in number", 1, 4),
Case(".5z", "invalid character in number", 1, 3),
Case("0.5.7", "invalid character in number", 1, 4),
Case(" 0.4e-z", "invalid character in number", 1, 7),
Case(" 0.4e-8.3", "invalid character in number", 1, 8),
Case(" 089z", "invalid character in number", 1, 5),
Case("0o89z", "invalid character in number", 1, 3),
Case("0X89g", "invalid character in number", 1, 5),
Case("10z", "invalid character in number", 1, 3),
Case("0.4e-8Z", "invalid character in number", 1, 7),
Case("123_", "invalid '_' at end of number: 123_", 1, 4),
Case("1__23", "invalid '_' in number: 1__", 1, 3),
Case("1_2__3", "invalid '_' in number: 1_2__", 1, 5),
Case("0.4e-8_", "invalid '_' at end of number: 0.4e-8_", 1, 7),
Case("0.4_e-8", "invalid '_' at end of number: 0.4_", 1, 4),
Case("0._4e08", "invalid '_' in number: 0._", 1, 3),
Case("\\ ", "unexpected character: \\", 1, 2)
];
foreach (c; badNumbers) {
auto tokenizer = makeTokenizer(c.source);
auto e = expectThrows(tokenizer.getToken());
assertIn(c.message, e.msg);
compareLocations(new Location(c.line, c.column), (cast(TokenizerException) e).location);
}
auto badStrings = [
Case("\'", "unterminated string:",1, 1),
Case("\"", "unterminated string:",1, 1),
Case("\'\'\'", "unterminated string:", 1, 1),
Case(" ;", "unexpected character: ", 1, 3)
];
foreach (c; badStrings) {
auto tokenizer = makeTokenizer(c.source);
auto msg = format!"Failed for '%s'"(c.source);
auto e = expectThrows(tokenizer.getToken(), msg);
assertIn(c.message, e.msg);
compareLocations(new Location(c.line, c.column), (cast(TokenizerException) e).location);
}
}
@Test
public void escapes() {
alias Case = Tuple!(string, "source", string, "result");
auto cases = [
Case("'\\a'", "\u0007"),
Case("'\\b'", "\b"),
Case("'\\f'", "\u000C"),
Case("'\\n'", "\n"),
Case("'\\r'", "\r"),
Case("'\\t'", "\t"),
Case("'\\v'", "\u000B"),
Case("'\\\\'", "\\"),
Case("'\\''", "'"),
Case("'\\\"'", "\""),
Case("'\\xAB'", "\u00AB"),
Case("'\\u2803'", "\u2803"),
Case("'\\u28A0abc\\u28A0'", "\u28a0abc\u28a0"),
Case("'\\u28A0abc'", "\u28a0abc"),
Case("'\\uE000'", "\ue000"),
Case("'\\U0010ffff'", "\U0010ffff")
];
foreach (c; cases) {
auto tokenizer = makeTokenizer(c.source);
auto token = tokenizer.getToken();
assertEquals(TokenKind.String, token.kind);
assertEquals(c.source, token.text);
assertEquals(c.result, token.value.get!(string));
assertEquals(TokenKind.EOF, tokenizer.getToken().kind);
}
auto badCases = [
"'\\z'",
"'\\x'",
"'\\xa'",
"'\\xaz'",
"'\\u'",
"'\\u0'",
"'\\u01'",
"'\\u012'",
"'\\u012z'",
"'\\u012zA'",
"'\\ud800'",
"'\\udfff'",
"'\\U00110000'"
];
foreach (s; badCases) {
auto tokenizer = makeTokenizer(s);
auto e = expectThrows(tokenizer.getToken());
assertIn("invalid escape sequence", e.msg);
}
}
@Test
public void data() {
auto info = loadData(dataFilePath("testdata.txt"));
}
}
class ParserTests : BaseTest {
mixin UnitTest;
private Parser makeParser(string s) {
auto r = inputRangeObject(s.representation.map!(b => ubyte(b)));
return new Parser(r);
}
@Test
public void simpleFragments() {
auto p = makeParser("a + 4");
auto node = cast(BinaryNode) p.expr();
assertTrue(p.atEnd);
assertEquals(TokenKind.Plus, node.kind);
assertEquals(TokenKind.Word, node.left.kind);
assertEquals("a", (cast(Token) node.left).text);
assertEquals(TokenKind.Integer, node.right.kind);
assertEquals(4L, (cast(Token) node.right).value.get!(long));
p = makeParser("a.b.c.d");
node = cast(BinaryNode) p.expr();
assertTrue(p.atEnd);
assertEquals(TokenKind.Dot, node.kind);
assertEquals(TokenKind.Word, node.right.kind);
assertEquals("d", (cast(Token) node.right).text);
node = cast(BinaryNode) node.left;
assertEquals(TokenKind.Dot, node.kind);
assertEquals(TokenKind.Word, node.right.kind);
assertEquals("c", (cast(Token) node.right).text);
node = cast(BinaryNode) node.left;
assertEquals(TokenKind.Dot, node.kind);
assertEquals(TokenKind.Word, node.left.kind);
assertEquals("a", (cast(Token) node.left).text);
assertEquals(TokenKind.Word, node.right.kind);
assertEquals("b", (cast(Token) node.right).text);
}
@Test
public void slices() {
auto p = makeParser("foo[start:stop:step]");
auto node = cast(BinaryNode) p.expr();
auto expected = new BinaryNode(TokenKind.Colon, W("foo"), SN(W("start"), W("stop"), W("step")));
compareObjects(expected, node);
p = makeParser("foo[start:stop]");
node = cast(BinaryNode) p.expr();
expected = new BinaryNode(TokenKind.Colon, W("foo"), SN(W("start"), W("stop"), null));
compareObjects(expected, node);
p = makeParser("foo[start:stop:]");
node = cast(BinaryNode) p.expr();
expected = new BinaryNode(TokenKind.Colon, W("foo"), SN(W("start"), W("stop"), null));
compareObjects(expected, node);
p = makeParser("foo[start:]");
node = cast(BinaryNode) p.expr();
expected = new BinaryNode(TokenKind.Colon, W("foo"), SN(W("start"), null, null));
compareObjects(expected, node);
p = makeParser("foo[:stop]");
node = cast(BinaryNode) p.expr();
expected = new BinaryNode(TokenKind.Colon, W("foo"), SN(null, W("stop"), null));
compareObjects(expected, node);
p = makeParser("foo[:stop:]");
node = cast(BinaryNode) p.expr();
expected = new BinaryNode(TokenKind.Colon, W("foo"), SN(null, W("stop"), null));
compareObjects(expected, node);
p = makeParser("foo[::step]");
node = cast(BinaryNode) p.expr();
expected = new BinaryNode(TokenKind.Colon, W("foo"), SN(null, null, W("step")));
compareObjects(expected, node);
p = makeParser("foo[::]");
node = cast(BinaryNode) p.expr();
expected = new BinaryNode(TokenKind.Colon, W("foo"), SN(null, null, null));
compareObjects(expected, node);
p = makeParser("foo[:]");
node = cast(BinaryNode) p.expr();
expected = new BinaryNode(TokenKind.Colon, W("foo"), SN(null, null, null));
compareObjects(expected, node);
p = makeParser("foo[start::]");
node = cast(BinaryNode) p.expr();
expected = new BinaryNode(TokenKind.Colon, W("foo"), SN(W("start"), null, null));
compareObjects(expected, node);
p = makeParser("foo[start::step]");
node = cast(BinaryNode) p.expr();
expected = new BinaryNode(TokenKind.Colon, W("foo"), SN(W("start"), null, W("step")));
compareObjects(expected, node);
}
@Test
public void data() {
auto info = loadData(dataFilePath("testdata.txt"));
auto messages = [
"D01": "unexpected type for key: Integer",
"D02": "unexpected type for key: LeftBracket",
"D03": "unexpected type for key: LeftCurly"
];
foreach(k, v; info) {
auto p = makeParser(v);
if (k < "D01") {
auto node = cast(MappingNode) p.mappingBody();
assertTrue(p.atEnd);
}
else {
auto e = expectThrows(p.mappingBody());
assertIn(messages[k], e.msg);
}
}
}
@Test
public void json() {
auto f = File(dataFilePath("forms.conf"));
auto r = inputRangeObject(f.byChunk(8192).joiner);
auto p = new Parser(r);
auto node = cast(MappingNode) p.mapping();
auto d = toMap(node);
assertTrue("refs" in d);
assertTrue("fieldsets" in d);
assertTrue("forms" in d);
assertTrue("modals" in d);
assertTrue("pages" in d);
}
}
Variant VS(string s) {
Variant v = s;
return v;
}
Variant VN(long n) {
Variant v = n;
return v;
}
Variant VB(bool b) {
Variant v = b;
return v;
}
Variant VL(Variant[] list) {
Variant result = list;
return result;
}
Variant VM(Variant[string] map) {
Variant result = map;
return result;
}
class ConfigTests : BaseTest {
mixin UnitTest;
@Test
public void identifiers() {
alias Case = Tuple!(string, "source", bool, "result");
auto cases = [
Case("foo", true),
Case("\u0935\u092e\u0938", true),
Case("\u73b0\u4ee3\u6c49\u8bed\u5e38\u7528\u5b57\u8868", true),
Case("foo ", false),
Case("foo[", false),
Case("foo [", false),
Case("foo.", false),
Case("foo .", false),
Case("\u0935\u092e\u0938.", false),
Case("\u73b0\u4ee3\u6c49\u8bed\u5e38\u7528\u5b57\u8868.", false),
Case("9", false),
Case("9foo", false),
Case("hyphenated-key", false)
];
foreach (c; cases) {
auto r = isIdentifier(c.source);
assertEquals(c.result, r);
}
}
@Test
public void badPaths() {
alias Case = Tuple!(string, "source", string, "message");
auto cases = [
Case("foo[1, 2]", "invalid index at (1, 5): expected 1 expression, found 2"),
Case("foo[1] bar", "Invalid path: foo[1] bar"),
Case("foo.123", "Invalid path: foo.123"),
Case("foo.", "expected Word but got EOF"),
Case("foo[]", "invalid index at (1, 5): expected 1 expression, found 0"),
Case("foo[1a]", "invalid character in number: 1a"),
Case("4", null)
];
foreach (c; cases) {
auto message = format!"Invalid path: %s"(c.source);
auto e = expectThrows(parsePath(c.source));
assertIn(message, e.msg);
if (e.next !is null) {
assertIn(c.message, e.next.msg);
}
}
}
@Test
public void pathIteration() {
auto node = parsePath("foo[bar].baz['booz'].bozz[3].fizz[::3].fuzz ");
auto actual = unpackPath(node);
PathElement[] expected = [
PathElement(TokenKind.Dot, W("foo")),
PathElement(TokenKind.LeftBracket, W("bar")),
PathElement(TokenKind.Dot, W("baz")),
PathElement(TokenKind.LeftBracket, S("'booz'", "booz")),
PathElement(TokenKind.Dot, W("bozz")),
PathElement(TokenKind.LeftBracket, N(3)),
PathElement(TokenKind.Dot, W("fizz")),
PathElement(TokenKind.Colon, SN(null, null, N(3))),
PathElement(TokenKind.Dot, W("fuzz"))
];
assertEquals(expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
assertEquals(expected[i].kind, actual[i].kind);
compareObjects(expected[i].operand, actual[i].operand);
}
}
@Test
public void basic() {
auto cfg = new Config();
assertTrue(cfg.noDuplicates);
assertTrue(cfg.strictConversions);
assertFalse(cfg.cached);
cfg.cached = true;
assertTrue(cfg.cached);
}
@Test
public void duplicates() {
auto path = dataFilePath("derived", "dupes.cfg");
auto cfg = new Config();
auto e = expectThrows!ConfigException(cfg.loadFile(path));
assertEquals(e.message, "Duplicate key foo seen at (4, 1) (previously (1, 1))");
cfg.noDuplicates = false;
cfg.loadFile(path);
assertEquals("not again!", cfg["foo"].get!(string));
}
@Test
public void mainConfig() {
auto path = dataFilePath("derived", "main.cfg");
auto cfg = new Config();
cfg.includePath ~= dataFilePath("base");
cfg.loadFile(path);
auto logConf = cfg["logging"].get!(Config);
assertNotNull(logConf);
auto keys = ["loggers", "handlers", "formatters", "root"];
foreach (k; keys) {
assertTrue(k in logConf);
}
Variant v = "bar";
assertEquals(v, logConf.get("foo", v));
v = "baz";
assertEquals(v, logConf.get("foo.bar", v));
v = "bozz";
assertEquals(v, logConf.get("handlers.debug.levl", v));
auto e = expectThrows(logConf.get("handlers.file/filename"));
assertIn("Invalid path: ", e.msg);
e = expectThrows(logConf.get("\"handlers.file/filename"));
assertIn("Invalid path: ", e.msg);
assertEquals("run/server.log", logConf["handlers.file.filename"].get!(string));
assertEquals("run/server-debug.log", logConf["handlers.debug.filename"].get!(string));
assertEquals(["file", "error", "debug"], logConf["root.handlers"].get!(Variant[]));
assertEquals(["file", "error"], logConf["root.handlers[:2]"].get!(Variant[]));
assertEquals(["file", "debug"], logConf["root.handlers[::2]"].get!(Variant[]));
auto test = cfg["test"].get!(Config);
assertEquals(1.0e-7, test["float"].get!(double));
assertEquals(0.3, test["float2"].get!(double));
assertEquals(3.0, test["float3"].get!(double));
assertEquals(2, test["list[1]"].get!(long));
assertEquals("b", test["dict.a"].get!(string));
assertEquals(Date(2019, 3, 28), test["date"].get!(Date));
auto dt = DateTime(2019, 3, 28, 23, 27, 4);
auto dur = nsecs(314159000);
auto tz = new SimpleTimeZone(minutes(330));
auto expected = SysTime(dt, dur, cast(immutable(TimeZone)) tz);
assertEquals(expected, test["date_time"].get!(SysTime));
tz = new SimpleTimeZone(minutes(-330));
expected = SysTime(dt, dur, cast(immutable(TimeZone)) tz);
assertEquals(expected, test["neg_offset_time"].get!(SysTime));
dt = DateTime(2019, 3, 28, 23, 27, 4);
dur = nsecs(271828000);
auto st = SysTime(dt, dur);
assertEquals(st, test["alt_date_time"].get!(SysTime));
assertEquals(3.3, test["computed"].get!(double));
assertEquals(2.7, test["computed2"].get!(double));
assertEquals(0.9, test["computed3"].get!(double));
assertEquals(10.0, test["computed4"].get!(double));
assertEquals([
VS("derived_foo"), VS("derived_bar"), VS("derived_baz"),
VS("test_foo"), VS("test_bar"), VS("test_baz"),
VS("base_foo"), VS("base_bar"), VS("base_baz")
], cfg["combined_list"]);
assertEquals([
"foo_key": VS("base_foo"),
"bar_key": VS("base_bar"),
"baz_key": VS("base_baz"),
"base_foo_key": VS("base_foo"),
"base_bar_key": VS("base_bar"),
"base_baz_key": VS("base_baz"),
"derived_foo_key": VS("derived_foo"),
"derived_bar_key": VS("derived_bar"),
"derived_baz_key": VS("derived_baz"),
"test_foo_key": VS("test_foo"),
"test_bar_key": VS("test_bar"),
"test_baz_key": VS("test_baz")
], cfg["combined_map_1"]);
assertEquals([
"derived_foo_key": VS("derived_foo"),
"derived_bar_key": VS("derived_bar"),
"derived_baz_key": VS("derived_baz")
], cfg["combined_map_2"]);
auto n1 = cfg["number_1"].get!(long);
auto n2 = cfg["number_2"].get!(long);
assertEquals(n1 & n2, cfg["number_3"].get!(long));
assertEquals(n1 ^ n2, cfg["number_4"].get!(long));
alias Case = Tuple!(string, "source", string, "message");
auto cases = [
Case("logging[4]", "string required, but found 4"),
Case("logging[:4]", "slices can only operate on lists"),
Case("no_such_key", "Not found in configuration: no_such_key")
];
foreach (c; cases) {
try {
cfg[c.source];
}
catch (ConfigException ce) {
assertIn(ce.msg, c.message);
}
}
}
@Test
public void exampleConfig() {
auto path = dataFilePath("derived", "example.cfg");
auto cfg = new Config();
cfg.includePath ~= dataFilePath("base");
cfg.loadFile(path);
// strings
assertEquals(cfg["snowman_escaped"], cfg["snowman_unescaped"]);
assertEquals("\u2603", cfg["snowman_escaped"]);
assertEquals("\U0001f602",cfg[ "face_with_tears_of_joy"]);
assertEquals("\U0001f602", cfg["unescaped_face_with_tears_of_joy"]);
auto strings = cfg["strings"].get!(Variant[]);
assertEquals("Oscar Fingal O'Flahertie Wills Wilde", strings[0]);
assertEquals("size: 5\"", strings[1]);
version(Windows) {
assertEquals("Triple quoted form\r\ncan span\r\n'multiple' lines", strings[2]);
assertEquals("with \"either\"\r\nkind of 'quote' embedded within", strings[3]);
}
else {
assertEquals("Triple quoted form\ncan span\n'multiple' lines", strings[2]);
assertEquals("with \"either\"\nkind of 'quote' embedded within", strings[3]);
}
// special strings
static import std.process;
assertEquals(std.process.environment.get("HOME"), cfg["special_value_2"]);
auto sv3 = cfg["special_value_3"].get!(SysTime);
assertEquals(2019, sv3.year);
assertEquals(3, sv3.month);
assertEquals(28, sv3.day);
assertEquals(23, sv3.hour);
assertEquals(27, sv3.minute);
assertEquals(4, sv3.second);
assertEquals(nsecs(314159000), sv3.fracSecs);
assertEquals(minutes(330), (cast(SimpleTimeZone) sv3.timezone).utcOffset);
assertEquals("bar", cfg["special_value_4"]);
// integers
assertEquals(123L, cfg["decimal_integer"]);
assertEquals(0x123L, cfg["hexadecimal_integer"]);
assertEquals(83L, cfg["octal_integer"]);
assertEquals(0b000100100011L, cfg["binary_integer"]);
// floats
assertEquals(123.456, cfg["common_or_garden"].get!(double));
assertEquals(0.123, cfg["leading_zero_not_needed"].get!(double));
assertEquals(123.0, cfg["trailing_zero_not_needed"].get!(double));
assertEquals(1.0e6, cfg["scientific_large"].get!(double));
assertEquals(1.0e-7, cfg["scientific_small"].get!(double));
assertEquals(3.14159, cfg["expression_1"].get!(double));
// complex
assertEquals(complex(3.0, 2.0), cfg["expression_2"]);
assertEquals(complex(1.0, 3.0), cfg["list_value[4]"]);
// boolean
assertEquals(true, cfg["boolean_value"]);
assertEquals(false, cfg["opposite_boolean_value"]);
assertEquals(false, cfg["computed_boolean_2"]);
assertEquals(true, cfg["computed_boolean_1"]);
// list
assertEquals([VS("a"), VS("b"), VS("c")], cfg["incl_list"]);
// mapping
assertEquals(["bar": VS("baz"), "foo": VS("bar")], cfg["incl_mapping"].asDict());
assertEquals(["baz": VS("bozz"), "fizz": VS("buzz")], cfg["incl_mapping_body"].asDict());
}
@Test
public void context() {
auto context = ["bozz": VS("bozz-bozz")];
auto path = dataFilePath("derived", "context.cfg");
auto cfg = new Config();
cfg.context = context;
cfg.loadFile(path);
assertEquals("bozz-bozz", cfg["baz"]);
try {
cfg["bad"];
}
catch (ConfigException ce) {
assertIn(ce.msg, "unknown variable 'not_there'");
}
}
@Test
public void expressions() {
auto path = dataFilePath("derived", "test.cfg");
auto cfg = new Config(path);
assertEquals(["a": VS("b"), "c": VS("d")], cfg["dicts_added"]);
// nested lists and maps need to be dressed up as Variants.
Variant v1 = ["b": VS("c"), "w": VS("x")];
Variant v2 = ["e": VS("f"), "y": VS("z")];
assertEquals(["a": v1, "d": v2], cfg["nested_dicts_added"]);
assertEquals([VS("a"), VN(1), VS("b"), VN(2)], cfg["lists_added"]);
assertEquals([VN(1), VN(2)], cfg["list[:2]"]);
assertEquals(["a": VS("b")], cfg["dicts_subtracted"]);
Variant[string] empty;
assertEquals(empty, cfg["nested_dicts_subtracted"]);
assertEquals([
"a_list": VL([VN(1), VN(2), VM(["a": VN(3)])]),
"a_map": VM(["k1": VL([VS("b"), VS("c"), VM(["d": VS("e")])])])
], cfg["dict_with_nested_stuff"]);
assertEquals([VN(1), VN(2)], cfg["dict_with_nested_stuff.a_list[:2]"]);
assertEquals(-4L, cfg["unary"]);
assertEquals("mno", cfg["abcdefghijkl"]);
assertEquals(8L, cfg["power"]);
assertEquals(2.5, cfg["computed5"].get!(double));
assertEquals(2L, cfg["computed6"]);
assertEquals(complex(3.0, 1.0), cfg["c3"]);
assertEquals(complex(5.0, 5.0), cfg["c4"]);
assertEquals(2L, cfg["computed8"]);
assertEquals(160L, cfg["computed9"]);
assertEquals(62L, cfg["computed10"]);
assertEquals("A-4 a test_foo true 10 1e-07 1 b [a, c, e, g]Z", cfg["interp"]);
assertEquals("{a: b}", cfg["interp2"]);
alias Case = Tuple!(string, "source", string, "message");
auto cases = [
Case("bad_include", "@ operand must be a string"),
Case("computed7", "not found in configuration: float4"),
Case("bad_interp", "unable to convert ")
];
foreach (c; cases) {
try {
cfg[c.source];
}
catch (ConfigException ce) {
assertIn(c.message, ce.msg);
}
}
}
@Test
public void forms() {
auto path = dataFilePath("derived", "forms.cfg");
auto cfg = new Config();
cfg.includePath ~= dataFilePath("base");
cfg.loadFile(path);
alias Case = Tuple!(string, "source", Variant, "value");
auto cases = [
Case("modals.deletion.contents[0].id", VS("frm-deletion")),
Case("refs.delivery_address_field", VM([
"kind": VS("field"),
"type": VS("textarea"),
"name": VS("postal_address"),
"label": VS("Postal address"),
"label_i18n": VS("postal-address"),
"short_name": VS("address"),
"placeholder": VS("We need this for delivering to you"),
"ph_i18n": VS("your-postal-address"),
"message": VS(" "),
"required": VB(true),
"attrs": VM(["minlength": VN(10)]),
"grpclass": VS("col-md-6")
])),
Case("refs.delivery_instructions_field", VM([
"kind": VS("field"),
"type": VS("textarea"),
"name": VS("delivery_instructions"),
"label": VS("Delivery Instructions"),
"short_name": VS("notes"),
"placeholder": VS("Any special delivery instructions?"),
"message": VS(" "),
"label_i18n": VS("delivery-instructions"),
"ph_i18n": VS("any-special-delivery-instructions"),
"grpclass": VS("col-md-6")
])),
Case("refs.verify_field", VM([
"kind": VS("field"),
"type": VS("input"),
"name": VS("verification_code"),
"label": VS("Verification code"),
"label_i18n": VS("verification-code"),
"short_name": VS("verification code"),
"placeholder": VS("Your verification code (NOT a backup code)"),
"ph_i18n": VS("verification-not-backup-code"),
"attrs": VM([
"minlength": VN(6),
"maxlength": VN(6),
"autofocus": VB(true)]),
"append": VM([
"label": VS("Verify"),
"type": VS("submit"),
"classes": VS("btn-primary")]),
"message": VS(" "),
"required": VB(true)
])),
Case("refs.signup_password_field", VM([
"kind": VS("field"),
"type": VS("password"),
"label": VS("Password"),
"label_i18n": VS("password"),
"message": VS(" "),
"name": VS("password"),
"ph_i18n": VS("password-wanted-on-site"),
"placeholder": VS("The password you want to use on this site"),
"required": VB(true),
"toggle": VB(true)
])),
Case("refs.signup_password_conf_field", VM([
"kind": VS("field"),
"type": VS("password"),
"name": VS("password_conf"),
"label": VS("Password confirmation"),
"label_i18n": VS("password-confirmation"),
"placeholder": VS("The same password, again, to guard against mistyping"),
"ph_i18n": VS("same-password-again"),
"message": VS(" "),
"toggle": VB(true),
"required": VB(true)
])),
Case("fieldsets.signup_ident[0].contents[0]", VM([
"kind": VS("field"),
"type": VS("input"),
"name": VS("display_name"),
"label": VS("Your name"),
"label_i18n": VS("your-name"),
"placeholder": VS("Your full name"),
"ph_i18n": VS("your-full-name"),
"message": VS(" "),
"data_source": VS("user.display_name"),
"required": VB(true),
"attrs": VM(["autofocus": VB(true)]),
"grpclass": VS("col-md-6")
])),
Case("fieldsets.signup_ident[0].contents[1]", VM([
"kind": VS("field"),
"type": VS("input"),
"name": VS("familiar_name"),
"label": VS("Familiar name"),
"label_i18n": VS("familiar-name"),
"placeholder": VS("If not just the first word in your full name"),
"ph_i18n": VS("if-not-first-word"),
"data_source": VS("user.familiar_name"),
"message": VS(" "),
"grpclass": VS("col-md-6")
])),
Case("fieldsets.signup_ident[1].contents[0]", VM([
"kind": VS("field"),
"type": VS("email"),
"name": VS("email"),
"label": VS("Email address (used to sign in)"),
"label_i18n": VS("email-address"),
"short_name": VS("email address"),
"placeholder": VS("Your email address"),
"ph_i18n": VS("your-email-address"),
"message": VS(" "),
"required": VB(true),
"data_source": VS("user.email"),
"grpclass": VS("col-md-6")
])),
Case("fieldsets.signup_ident[1].contents[1]", VM([
"kind": VS("field"),
"type": VS("input"),
"name": VS("mobile_phone"),
"label": VS("Phone number"),
"label_i18n": VS("phone-number"),
"short_name": VS("phone number"),
"placeholder": VS("Your phone number"),
"ph_i18n": VS("your-phone-number"),
"classes": VS("numeric"),
"message": VS(" "),
"prepend": VM(["icon": VS("phone")]),
"attrs": VM(["maxlength": VN(10)]),
"required": VB(true),
"data_source": VS("customer.mobile_phone"),
"grpclass": VS("col-md-6")
]))
];
foreach (c; cases) {
assertEquals(c.value, cfg[c.source]);
}
}
@Test
public void pathAcrossIncludes() {
auto path = dataFilePath("base", "main.cfg");
auto cfg = new Config(path);
assertEquals("run/server.log", cfg["logging.appenders.file.filename"]);
assertTrue(cfg["logging.appenders.file.append"].get!(bool));
assertEquals("run/server-errors.log", cfg["logging.appenders.error.filename"]);
assertFalse(cfg["logging.appenders.error.append"].get!(bool));
assertEquals("https://freeotp.github.io/", cfg["redirects.freeotp.url"]);
assertFalse(cfg["redirects.freeotp.permanent"].get!(bool));
}
@Test
public void badConversions() {
auto cases = ["foo"];
auto cfg = new Config();
foreach (c; cases) {
cfg.strictConversions = true;
try {
cfg.convertString(c);
}
catch (ConfigException ce) {
assertIn(ce.msg, format!"unable to convert '%s'"(c));
}
cfg.strictConversions = false;
auto s = cfg.convertString(c);
assertEquals(c, s);
}
}
@Test
public void sources() {
auto cases = [
"foo[::2]",
"foo[:]",
"foo[:2]",
"foo[2:]",
"foo[::1]",
"foo[::-1]"
];
foreach (c; cases) {
auto node = parsePath(c);
auto s = toSource(node);
assertEquals(c, s);
}
}
@Test
public void circularReferences() {
auto path = dataFilePath("derived", "test.cfg");
auto cfg = new Config(path);
alias Case = Tuple!(string, "source", string, "message");
auto cases = [
Case("circ_list[1]", "Circular reference: circ_list[1] (42, 7)"),
Case("circ_map.a", "Circular reference: circ_map.a (49, 10), circ_map.b (47, 10), circ_map.c (48, 10)"),
];
foreach (c; cases) {
try {
cfg[c.source];
}
catch (CircularReferenceException cre) {
assertIn(cre.msg, c.message);
}
}
}
@Test
public void slicesAndIndices() {
auto path = dataFilePath("derived", "test.cfg");
auto cfg = new Config(path);
auto theList = [VS("a"), VS("b"), VS("c"), VS("d"), VS("e"), VS("f"), VS("g")];
// slices
assertEquals(theList, cfg["test_list[:]"]);
assertEquals(theList, cfg["test_list[::]"]);
assertEquals(theList, cfg["test_list[:20]"]);
assertEquals(theList, cfg["test_list[-20:20]"]);
assertEquals([VS("a"), VS("b"), VS("c"), VS("d")], cfg["test_list[-20:4]"]);
assertEquals([VS("c"), VS("d"), VS("e"), VS("f"), VS("g")], cfg["test_list[2:]"]);
assertEquals([VS("e"), VS("f"), VS("g")], cfg["test_list[-3:]"]);
assertEquals([VS("f"), VS("e"), VS("d")], cfg["test_list[-2:2:-1]"]);
assertEquals([VS("g"), VS("f"), VS("e"), VS("d"), VS("c"), VS("b"), VS("a")], cfg["test_list[::-1]"]);
assertEquals([VS("c"), VS("e")], cfg["test_list[2:-2:2]"]);
assertEquals([VS("a"), VS("c"), VS("e"), VS("g")], cfg["test_list[::2]"]);
assertEquals([VS("a"), VS("d"), VS("g")], cfg["test_list[::3]"]);
assertEquals([VS("a"), VS("g")], cfg["test_list[::2][::3]"]);
// indices
foreach (i, v; theList.enumerate()) {
assertEquals(v, cfg[format!"test_list[%d]"(i)]);
}
// negative indices
int n = to!int(theList.length);
for (int i = n; i > 0; i--) {
assertEquals(theList[n - i], cfg[format!"test_list[-%d]"(i)]);
}
// invalid indices
auto invalid = [n, n + 1, -(n + 1), -(n + 2)];
foreach(i; invalid) {
try {
cfg[format!"test_list[%d]"(i)];
}
catch (BadIndexException bie) {
}
}
}
@Test
public void absoluteIncludePath() {
auto path = absolutePath(dataFilePath("derived", "test.cfg"));
auto s = "test: @'foo'".replace("foo", path.replace("\\", "/"));
auto r = inputRangeObject(s.representation.map!(b => ubyte(b)));
auto cfg = new Config(r);
assertEquals(2, cfg["test.computed6"].get!(long));
}
@Test
public void nestedIncludePath() {
auto path = dataFilePath("base", "top.cfg");
auto cfg = new Config(path);
cfg.includePath ~= dataFilePath("derived");
cfg.includePath ~= dataFilePath("another");
assertEquals(42, cfg["level1.level2.final"].get!(long));
}
@Test
public void recursiveConfiguration() {
auto path = dataFilePath("derived", "recurse.cfg");
auto cfg = new Config(path);
auto e = expectThrows!ConfigException(cfg["recurse"]);
assertEquals(e.message, "configuration cannot include itself: recurse.cfg");
}
}
|
D
|
/**
WinRT driver implementation
Copyright: © 2012 Sönke Ludwig
Authors: Sönke Ludwig
License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
*/
module vibe.core.drivers.winrt;
version(VibeWinrtDriver)
{
import vibe.core.driver;
import vibe.inet.url;
import core.time;
class WinRTEventDriver : EventDriver {
private {
DriverCore m_core;
}
this(DriverCore core)
{
m_core = core;
}
int runEventLoop()
{
return 0;
}
int runEventLoopOnce()
{
return 0;
}
int processEvents()
{
return 0;
}
void exitEventLoop()
{
}
void runWorkerTask(void delegate() f)
{
}
WinRTFileStream openFile(string path, FileMode mode)
{
return new WinRTFileStream(path, mode);
}
DirectoryWatcher watchDirectory(Path path, bool recursive)
{
assert(false);
}
WinRTTCPConnection connectTCP(string host, ushort port)
{
assert(false);
}
void listenTCP(ushort port, void delegate(TCPConnection conn) conn_callback, string bind_address, TCPListenOptions options)
{
assert(false);
}
WinRTManualEvent createManualEvent()
{
assert(false);
}
WinRTTimer createTimer(void delegate() callback)
{
return new WinRTTimer(this, callback);
}
}
class WinRTManualEvent : ManualEvent {
void release()
{
}
void acquire()
{
}
bool amOwner()
{
assert(false);
}
@property int emitCount()
const {
assert(false);
}
void emit()
{
}
void wait()
{
}
}
class WinRTTimer : Timer {
private {
WinRTEventDriver m_driver;
void delegate() m_callback;
bool m_pending;
bool m_periodic;
}
this(WinRTEventDriver driver, void delegate() callback)
{
m_driver = driver;
m_callback = callback;
}
void release()
{
}
void acquire()
{
}
bool amOwner()
{
assert(false);
}
@property bool pending() { return m_pending; }
void rearm(Duration dur, bool periodic = false)
{
if( m_pending ) stop();
m_periodic = periodic;
//SetTimer(m_hwnd, id, seconds.total!"msecs"(), &timerProc);
}
void stop()
{
assert(m_pending);
//KillTimer(m_driver.m_hwnd, cast(size_t)cast(void*)this);
}
void wait()
{
while( m_pending )
m_driver.m_core.yieldForEvent();
}
}
class WinRTFileStream : FileStream {
this(string path, FileMode mode)
{
assert(false);
}
void release()
{
}
void acquire()
{
}
bool amOwner()
{
assert(false);
}
void close()
{
}
@property Path path() const { assert(false); }
@property ulong size()
const {
assert(false);
}
@property bool readable()
const {
assert(false);
}
@property bool writable()
const {
assert(false);
}
void seek(ulong offset)
{
}
ulong tell()
{
assert(false);
}
@property bool empty() { assert(false); }
@property ulong leastSize() { assert(false); }
@property bool dataAvailableForRead() { assert(false); }
const(ubyte)[] peek() { assert(false); }
void read(ubyte[] dst)
{
}
void write(in ubyte[] bytes, bool do_flush = true)
{
}
void flush()
{
}
void finalize()
{
}
void write(InputStream stream, ulong nbytes = 0, bool do_flush = true)
{
writeDefault(stream, nbytes, do_flush);
}
}
class WinRTTCPConnection : TCPConnection {
private {
bool m_tcpNoDelay;
Duration m_readTimeout;
}
void release()
{
}
void acquire()
{
}
bool amOwner()
{
assert(false);
}
@property void tcpNoDelay(bool enabled)
{
m_tcpNoDelay = enabled;
assert(false);
}
@property bool tcpNoDelay() const { return m_tcpNoDelay; }
@property void readTimeout(Duration v){
m_readTimeout = v;
assert(false);
}
@property Duration readTimeout() const { return m_readTimeout; }
void close()
{
}
@property bool connected()
const {
assert(false);
}
@property string peerAddress()
const {
assert(false);
}
bool waitForData(Duration timeout)
{
assert(false);
}
@property bool empty() { assert(false); }
@property ulong leastSize() { assert(false); }
@property bool dataAvailableForRead() { assert(false); }
const(ubyte)[] peek() { assert(false); }
void read(ubyte[] dst)
{
}
void write(in ubyte[] bytes, bool do_flush = true)
{
}
void flush()
{
}
void finalize()
{
}
void write(InputStream stream, ulong nbytes = 0, bool do_flush = true)
{
writeDefault(stream, nbytes, do_flush);
}
}
} // version(VibeWinrtDriver)
|
D
|
/Users/eric/rust_project/rust-cookbook-code/basic-2-read-write-integers/target/release/deps/libbyteorder-53c0c77d1faf3df3.rlib: /Users/eric/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/byteorder-1.2.2/src/lib.rs /Users/eric/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/byteorder-1.2.2/src/io.rs
/Users/eric/rust_project/rust-cookbook-code/basic-2-read-write-integers/target/release/deps/byteorder-53c0c77d1faf3df3.d: /Users/eric/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/byteorder-1.2.2/src/lib.rs /Users/eric/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/byteorder-1.2.2/src/io.rs
/Users/eric/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/byteorder-1.2.2/src/lib.rs:
/Users/eric/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/byteorder-1.2.2/src/io.rs:
|
D
|
/*********************************************************
Авторское право: (C) 2008 принадлежит Steven Schveighoffer.
Все права защищены
Лицензия: $(LICENSE)
**********************************************************/
module col.model.Iterator;
enum : бцел
{
/**
* Возвращается из длина(), когда length не поддерживается
*/
ДЛИНА_НЕ_ПОДДЕРЖИВАЕТСЯ = ~0
}
/**
* базовый итератор. Позволяет обходить по элементам объекта.
*/
interface Обходчик(З)
{
/**
*Если поддерживается, возвращает число элементов, которые будут итерированы.
*
* Если не поддерживается, возвращает ДЛИНА_НЕ_ПОДДЕРЖИВАЕТСЯ.
*/
бцел длина(); alias длина length;
/**
*оператор foreach.
*/
цел opApply(цел delegate(ref З з) дг);
}
/**
* Обходчик с ключами. Это позволяет видеть ключ элемента как и
* значение при итерации.
*/
interface Ключник(К, З) : Обходчик!(З)
{
alias Обходчик!(З).opApply opApply;
/**
* Итерировать по ключам и значениям одновременно
*/
цел opApply(цел delegate(ref К к, ref З з) дг);
}
/**
* Чистящий итератор используется для очистки значений из коллекции. Это выполняется путём
* сообщения итератору, который должен удалить обходчик, последнего итерированного значения.
*/
interface Чистящий(З)
{
/**
* Итерирует по значениям итератора, сообщая обх, какие значения
* удалить. Чтобы удали значение, установить чистить_ли в да перед выходом из
* цикла
*
* Прим.: укажите ref для параметра чистить_ли:
*
* -----
* foreach(ref чистить_ли, з; &чистящий.очистить){
* ...
* -----
*/
цел очистить(цел delegate(ref бул чистить_ли, ref З з) дг);
}
/**
* Чистящий обходчик для контейнеров с ключами.
*/
interface ЧистящийКлючи(К, З) : Чистящий!(З)
{
/**
* Итерировать по парам ключ/значение обходчика, сообщая ему, какие следует
* удалить.
*
* Прим.: укажите ref для параметра чистить_ли:
*
* -----
* foreach(ref чистить_ли, к, з; &чистящий.чисть_ключ){
* ...
* -----
*
* TODO: note this should have the name очистить, but because of asonine
* lookup rules, обх makes обх difficult to specify this version over the
* base version. Once this is fixed, обх's highly likely that this goes
* тыл to the name очистить.
*
* See bugzilla #2498
*/
цел чисть_ключ(цел delegate(ref бул чистить_ли, ref К к, ref З з) дг);
}
|
D
|
/Users/kidnapper/Documents/Jiaben_xcode8/DerivedData/Jaiben/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FacebookCore.build/Objects-normal/x86_64/GraphRequestProtocol.Bridge.o : /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestProtocol.Bridge.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEventParameterName.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEventName.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Internal/Extensions/Optional+OnSome.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphResponse.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestConnection.Delegate.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Common/SDKApplicationDelegate.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphResponseProtocol.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestProtocol.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Common/AccessToken.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEvent.Builtin.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphAPIVersion.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Permissions/Permission.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Permissions/ReadPermission.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Permissions/PublishPermission.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestConnection.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Internal/Extensions/Dictionary+KeyValueMap.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEventsLogger.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Common/SDKLoggingBehavior.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEventsLogger.FlushBehavior.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Common/SDKSettings.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.FetchResult.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestResult.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestDataAttachment.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEvent.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequest.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.PictureView.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/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFURL.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Target\ Support\ Files/FacebookCore/FacebookCore-umbrella.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Target\ Support\ Files/Bolts/Bolts-umbrella.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Target\ Support\ Files/FBSDKCoreKit/FBSDKCoreKit-umbrella.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFCancellationTokenSource.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFTaskCompletionSource.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKProfile.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKApplicationDelegate.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLinkResolving.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKCopying.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKMutableCopying.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLink.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFTask.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFCancellationToken.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAccessToken.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLinkNavigation.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFCancellationTokenRegistration.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequestConnection.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKButton.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKTestUsersManager.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLinkReturnToRefererController.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkResolver.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFWebViewAppLinkResolver.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphErrorRecoveryProcessor.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFExecutor.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKSettings.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFTask+Exceptions.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKMacros.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/Bolts.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKConstants.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppEvents.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLinkTarget.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequestDataAttachment.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFMeasurementEvent.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequest.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKProfilePictureView.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLinkReturnToRefererView.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKUtility.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkUtility.h /Users/kidnapper/Documents/Jiaben_xcode8/DerivedData/Jaiben/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FacebookCore.build/unextended-module.modulemap /Users/kidnapper/Documents/Jiaben_xcode8/DerivedData/Jaiben/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Bolts.build/module.modulemap /Users/kidnapper/Documents/Jiaben_xcode8/DerivedData/Jaiben/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FBSDKCoreKit.build/module.modulemap
/Users/kidnapper/Documents/Jiaben_xcode8/DerivedData/Jaiben/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FacebookCore.build/Objects-normal/x86_64/GraphRequestProtocol.Bridge~partial.swiftmodule : /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestProtocol.Bridge.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEventParameterName.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEventName.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Internal/Extensions/Optional+OnSome.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphResponse.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestConnection.Delegate.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Common/SDKApplicationDelegate.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphResponseProtocol.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestProtocol.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Common/AccessToken.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEvent.Builtin.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphAPIVersion.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Permissions/Permission.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Permissions/ReadPermission.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Permissions/PublishPermission.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestConnection.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Internal/Extensions/Dictionary+KeyValueMap.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEventsLogger.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Common/SDKLoggingBehavior.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEventsLogger.FlushBehavior.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Common/SDKSettings.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.FetchResult.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestResult.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestDataAttachment.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEvent.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequest.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.PictureView.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/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFURL.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Target\ Support\ Files/FacebookCore/FacebookCore-umbrella.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Target\ Support\ Files/Bolts/Bolts-umbrella.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Target\ Support\ Files/FBSDKCoreKit/FBSDKCoreKit-umbrella.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFCancellationTokenSource.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFTaskCompletionSource.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKProfile.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKApplicationDelegate.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLinkResolving.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKCopying.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKMutableCopying.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLink.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFTask.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFCancellationToken.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAccessToken.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLinkNavigation.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFCancellationTokenRegistration.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequestConnection.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKButton.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKTestUsersManager.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLinkReturnToRefererController.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkResolver.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFWebViewAppLinkResolver.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphErrorRecoveryProcessor.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFExecutor.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKSettings.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFTask+Exceptions.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKMacros.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/Bolts.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKConstants.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppEvents.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLinkTarget.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequestDataAttachment.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFMeasurementEvent.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequest.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKProfilePictureView.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLinkReturnToRefererView.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKUtility.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkUtility.h /Users/kidnapper/Documents/Jiaben_xcode8/DerivedData/Jaiben/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FacebookCore.build/unextended-module.modulemap /Users/kidnapper/Documents/Jiaben_xcode8/DerivedData/Jaiben/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Bolts.build/module.modulemap /Users/kidnapper/Documents/Jiaben_xcode8/DerivedData/Jaiben/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FBSDKCoreKit.build/module.modulemap
/Users/kidnapper/Documents/Jiaben_xcode8/DerivedData/Jaiben/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FacebookCore.build/Objects-normal/x86_64/GraphRequestProtocol.Bridge~partial.swiftdoc : /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestProtocol.Bridge.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEventParameterName.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEventName.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Internal/Extensions/Optional+OnSome.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphResponse.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestConnection.Delegate.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Common/SDKApplicationDelegate.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphResponseProtocol.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestProtocol.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Common/AccessToken.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEvent.Builtin.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphAPIVersion.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Permissions/Permission.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Permissions/ReadPermission.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Permissions/PublishPermission.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestConnection.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Internal/Extensions/Dictionary+KeyValueMap.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEventsLogger.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Common/SDKLoggingBehavior.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEventsLogger.FlushBehavior.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/Common/SDKSettings.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.FetchResult.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestResult.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestDataAttachment.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/AppEvents/AppEvent.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequest.swift /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.PictureView.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/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFURL.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Target\ Support\ Files/FacebookCore/FacebookCore-umbrella.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Target\ Support\ Files/Bolts/Bolts-umbrella.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Target\ Support\ Files/FBSDKCoreKit/FBSDKCoreKit-umbrella.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFCancellationTokenSource.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFTaskCompletionSource.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKProfile.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKApplicationDelegate.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLinkResolving.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKCopying.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKMutableCopying.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLink.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFTask.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFCancellationToken.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAccessToken.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLinkNavigation.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFCancellationTokenRegistration.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequestConnection.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKButton.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKTestUsersManager.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLinkReturnToRefererController.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkResolver.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFWebViewAppLinkResolver.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphErrorRecoveryProcessor.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFExecutor.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKSettings.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/BFTask+Exceptions.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKMacros.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/Common/Bolts.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKConstants.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppEvents.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLinkTarget.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequestDataAttachment.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFMeasurementEvent.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKGraphRequest.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKProfilePictureView.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/Bolts/Bolts/iOS/BFAppLinkReturnToRefererView.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKUtility.h /Users/kidnapper/Documents/Jiaben_xcode8/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/FBSDKAppLinkUtility.h /Users/kidnapper/Documents/Jiaben_xcode8/DerivedData/Jaiben/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FacebookCore.build/unextended-module.modulemap /Users/kidnapper/Documents/Jiaben_xcode8/DerivedData/Jaiben/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Bolts.build/module.modulemap /Users/kidnapper/Documents/Jiaben_xcode8/DerivedData/Jaiben/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FBSDKCoreKit.build/module.modulemap
|
D
|
/* THIS FILE GENERATED BY bcd.gen */
module bcd.fltk2.MenuBuild;
align(4):
public import bcd.bind;
public import bcd.fltk2.PopupMenu;
public import bcd.fltk2.Choice;
public import bcd.fltk2.MenuBar;
public import bcd.fltk2.Divider;
public import bcd.fltk2.Item;
public import bcd.fltk2.ItemGroup;
public import bcd.fltk2.Menu;
public import bcd.fltk2.Group;
public import bcd.fltk2.Widget;
public import bcd.fltk2.Style;
public import bcd.fltk2.FL_API;
public import bcd.fltk2.events;
public import bcd.fltk2.Rectangle;
public import bcd.fltk2.Color;
public import bcd.fltk2.Flags;
alias void function(Widget *, int) _BCD_func__259;
alias void function(Widget *) _BCD_func__261;
alias void function(Widget *, void *) _BCD_func__265;
alias bool function() _BCD_func__535;
|
D
|
/**
* TypeInfo support code.
*
* Copyright: Copyright Digital Mars 2004 - 2009.
* License: $(WEB www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
* Authors: Walter Bright
*/
/* Copyright Digital Mars 2004 - 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 rt.typeinfo.ti_dchar;
// dchar
class TypeInfo_w : TypeInfo
{
@trusted:
const:
pure:
nothrow:
override string toString() const pure nothrow @safe { return "dchar"; }
override size_t getHash(in void* p)
{
return *cast(dchar *)p;
}
override bool equals(in void* p1, in void* p2)
{
return *cast(dchar *)p1 == *cast(dchar *)p2;
}
override int compare(in void* p1, in void* p2)
{
return *cast(dchar *)p1 - *cast(dchar *)p2;
}
override @property size_t tsize() nothrow pure
{
return dchar.sizeof;
}
override void swap(void *p1, void *p2)
{
dchar t;
t = *cast(dchar *)p1;
*cast(dchar *)p1 = *cast(dchar *)p2;
*cast(dchar *)p2 = t;
}
override const(void)[] initializer() const @trusted
{
static immutable dchar c;
return (&c)[0 .. 1];
}
}
|
D
|
/Users/okasho/serverProject/tryswift/helloworld/swift/.build/debug/Polymorphic.build/String+Polymorphic.swift.o : /Users/okasho/serverProject/tryswift/helloworld/swift/Packages/Polymorphic-1.0.1/Sources/Polymorphic.swift /Users/okasho/serverProject/tryswift/helloworld/swift/Packages/Polymorphic-1.0.1/Sources/String+Polymorphic.swift /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/SwiftOnoneSupport.swiftmodule
/Users/okasho/serverProject/tryswift/helloworld/swift/.build/debug/Polymorphic.build/String+Polymorphic~partial.swiftmodule : /Users/okasho/serverProject/tryswift/helloworld/swift/Packages/Polymorphic-1.0.1/Sources/Polymorphic.swift /Users/okasho/serverProject/tryswift/helloworld/swift/Packages/Polymorphic-1.0.1/Sources/String+Polymorphic.swift /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/SwiftOnoneSupport.swiftmodule
/Users/okasho/serverProject/tryswift/helloworld/swift/.build/debug/Polymorphic.build/String+Polymorphic~partial.swiftdoc : /Users/okasho/serverProject/tryswift/helloworld/swift/Packages/Polymorphic-1.0.1/Sources/Polymorphic.swift /Users/okasho/serverProject/tryswift/helloworld/swift/Packages/Polymorphic-1.0.1/Sources/String+Polymorphic.swift /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/SwiftOnoneSupport.swiftmodule
|
D
|
/Users/Yowa/WorkSpace/Pokedex/Build/Intermediates/Pokedex.build/Debug/Fluent.build/Objects-normal/x86_64/Schema+Creator.o : /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Database/Database.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Database/Driver.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Entity/Entity.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Memory/Memory+Filters.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Memory/Memory+Group.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Memory/Memory+Sort.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Memory/MemoryDriver.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Preparation/Database+Preparation.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Preparation/Migration.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Preparation/Preparation.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Preparation/PreparationError.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Action.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Comparison.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Filter.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Group.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Join.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Limit.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Query.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Scope.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Sort.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Relations/Children.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Relations/Parent.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Relations/RelationError.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Relations/Siblings.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Schema/Database+Schema.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Schema/Schema+Creator.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Schema/Schema+Field.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Schema/Schema+Modifier.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Schema/Schema.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/SQL/GeneralSQLSerializer.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/SQL/SQL+Query.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/SQL/SQL+Schema.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/SQL/SQL.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/SQL/SQLSerializer.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Utilities/Fluent+Node.swift /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/SwiftOnoneSupport.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/Darwin.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/ObjectiveC.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/IOKit.swiftmodule /Users/Yowa/WorkSpace/Pokedex/Build/Products/Debug/Node.framework/Modules/Node.swiftmodule/x86_64.swiftmodule /Users/Yowa/WorkSpace/Pokedex/Build/Products/Debug/PathIndexable.framework/Modules/PathIndexable.swiftmodule/x86_64.swiftmodule /Users/Yowa/WorkSpace/Pokedex/Build/Products/Debug/Polymorphic.framework/Modules/Polymorphic.swiftmodule/x86_64.swiftmodule
/Users/Yowa/WorkSpace/Pokedex/Build/Intermediates/Pokedex.build/Debug/Fluent.build/Objects-normal/x86_64/Schema+Creator~partial.swiftmodule : /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Database/Database.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Database/Driver.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Entity/Entity.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Memory/Memory+Filters.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Memory/Memory+Group.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Memory/Memory+Sort.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Memory/MemoryDriver.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Preparation/Database+Preparation.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Preparation/Migration.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Preparation/Preparation.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Preparation/PreparationError.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Action.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Comparison.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Filter.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Group.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Join.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Limit.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Query.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Scope.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Sort.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Relations/Children.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Relations/Parent.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Relations/RelationError.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Relations/Siblings.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Schema/Database+Schema.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Schema/Schema+Creator.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Schema/Schema+Field.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Schema/Schema+Modifier.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Schema/Schema.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/SQL/GeneralSQLSerializer.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/SQL/SQL+Query.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/SQL/SQL+Schema.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/SQL/SQL.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/SQL/SQLSerializer.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Utilities/Fluent+Node.swift /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/SwiftOnoneSupport.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/Darwin.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/ObjectiveC.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/IOKit.swiftmodule /Users/Yowa/WorkSpace/Pokedex/Build/Products/Debug/Node.framework/Modules/Node.swiftmodule/x86_64.swiftmodule /Users/Yowa/WorkSpace/Pokedex/Build/Products/Debug/PathIndexable.framework/Modules/PathIndexable.swiftmodule/x86_64.swiftmodule /Users/Yowa/WorkSpace/Pokedex/Build/Products/Debug/Polymorphic.framework/Modules/Polymorphic.swiftmodule/x86_64.swiftmodule
/Users/Yowa/WorkSpace/Pokedex/Build/Intermediates/Pokedex.build/Debug/Fluent.build/Objects-normal/x86_64/Schema+Creator~partial.swiftdoc : /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Database/Database.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Database/Driver.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Entity/Entity.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Memory/Memory+Filters.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Memory/Memory+Group.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Memory/Memory+Sort.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Memory/MemoryDriver.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Preparation/Database+Preparation.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Preparation/Migration.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Preparation/Preparation.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Preparation/PreparationError.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Action.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Comparison.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Filter.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Group.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Join.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Limit.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Query.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Scope.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Query/Sort.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Relations/Children.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Relations/Parent.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Relations/RelationError.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Relations/Siblings.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Schema/Database+Schema.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Schema/Schema+Creator.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Schema/Schema+Field.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Schema/Schema+Modifier.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Schema/Schema.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/SQL/GeneralSQLSerializer.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/SQL/SQL+Query.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/SQL/SQL+Schema.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/SQL/SQL.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/SQL/SQLSerializer.swift /Users/Yowa/WorkSpace/Pokedex/Packages/Fluent-1.0.0/Sources/Fluent/Utilities/Fluent+Node.swift /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/SwiftOnoneSupport.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/Darwin.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/ObjectiveC.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/IOKit.swiftmodule /Users/Yowa/WorkSpace/Pokedex/Build/Products/Debug/Node.framework/Modules/Node.swiftmodule/x86_64.swiftmodule /Users/Yowa/WorkSpace/Pokedex/Build/Products/Debug/PathIndexable.framework/Modules/PathIndexable.swiftmodule/x86_64.swiftmodule /Users/Yowa/WorkSpace/Pokedex/Build/Products/Debug/Polymorphic.framework/Modules/Polymorphic.swiftmodule/x86_64.swiftmodule
|
D
|
// Written in the D programming language.
/**
This module implements the formatting functionality for strings and
I/O. It's comparable to C99's $(D vsprintf()) and uses a similar
format encoding scheme.
Macros: WIKI = Phobos/StdFormat
Copyright: Copyright Digital Mars 2000-.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(WEB digitalmars.com, Walter Bright), $(WEB erdani.com,
Andrei Alexandrescu), and Kenji Hara
Source: $(PHOBOSSRC std/_format.d)
*/
module std.format;
//debug=format; // uncomment to turn on debugging printf's
import core.stdc.stdio, core.stdc.stdlib, core.stdc.string, core.vararg;
import std.algorithm, std.array, std.ascii, std.bitmanip, std.conv,
std.exception, std.functional, std.math, std.range,
std.string, std.system, std.traits, std.typecons, std.typetuple,
std.utf;
version(unittest) {
import std.stdio;
import core.exception;
}
version (Win32) version (DigitalMars)
{
version = DigitalMarsC;
}
version (DigitalMarsC)
{
// This is DMC's internal floating point formatting function
extern (C)
{
extern shared char* function(int c, int flags, int precision,
in real* pdval,
char* buf, size_t* psl, int width) __pfloatfmt;
}
}
/**********************************************************************
* Signals a mismatch between a format and its corresponding argument.
*/
class FormatException : Exception
{
this()
{
super("format error");
}
this(string msg, string fn = __FILE__, size_t ln = __LINE__, Throwable next = null)
{
super(msg, fn, ln, next);
}
}
/++
$(RED Deprecated. It will be removed In January 2013.
Please use $(D FormatException) instead.)
+/
deprecated("Please use FormatException instead.")
alias FormatException FormatError;
/**********************************************************************
Interprets variadic argument list $(D args), formats them according
to $(D fmt), and sends the resulting characters to $(D w). The
encoding of the output is the same as $(D Char). The type $(D Writer)
must satisfy $(XREF range,isOutputRange!(Writer, Char)).
The variadic arguments are normally consumed in order. POSIX-style
$(WEB opengroup.org/onlinepubs/009695399/functions/printf.html,
positional parameter syntax) is also supported. Each argument is
formatted into a sequence of chars according to the format
specification, and the characters are passed to $(D w). As many
arguments as specified in the format string are consumed and
formatted. If there are fewer arguments than format specifiers, a
$(D FormatException) is thrown. If there are more remaining arguments
than needed by the format specification, they are ignored but only
if at least one argument was formatted.
The format string supports the formatting of array and nested array elements
via the grouping format specifiers $(B %() and $(B %)). Each
matching pair of $(B %() and $(B %)) corresponds with a single array
argument. The enclosed sub-format string is applied to individual array
elements. The trailing portion of the sub-format string following the
conversion specifier for the array element is interpreted as the array
delimiter, and is therefore omitted following the last array element. The
$(B %|) specifier may be used to explicitly indicate the start of the
delimiter, so that the preceding portion of the string will be included
following the last array element. (See below for explicit examples.)
Params:
w = Output is sent to this writer. Typical output writers include
$(XREF array,Appender!string) and $(XREF stdio,LockingTextWriter).
fmt = Format string.
args = Variadic argument list.
Returns: Formatted number of arguments.
Throws: Mismatched arguments and formats result in a $(D
FormatException) being thrown.
Format_String: <a name="format-string">$(I Format strings)</a>
consist of characters interspersed with $(I format
specifications). Characters are simply copied to the output (such
as putc) after any necessary conversion to the corresponding UTF-8
sequence.
The format string has the following grammar:
$(PRE
$(I FormatString):
$(I FormatStringItem)*
$(I FormatStringItem):
$(B '%%')
$(B '%') $(I Position) $(I Flags) $(I Width) $(I Precision) $(I FormatChar)
$(B '%$(LPAREN)') $(I FormatString) $(B '%$(RPAREN)')
$(I OtherCharacterExceptPercent)
$(I Position):
$(I empty)
$(I Integer) $(B '$')
$(I Flags):
$(I empty)
$(B '-') $(I Flags)
$(B '+') $(I Flags)
$(B '#') $(I Flags)
$(B '0') $(I Flags)
$(B ' ') $(I Flags)
$(I Width):
$(I empty)
$(I Integer)
$(B '*')
$(I Precision):
$(I empty)
$(B '.')
$(B '.') $(I Integer)
$(B '.*')
$(I Integer):
$(I Digit)
$(I Digit) $(I Integer)
$(I Digit):
$(B '0')|$(B '1')|$(B '2')|$(B '3')|$(B '4')|$(B '5')|$(B '6')|$(B '7')|$(B '8')|$(B '9')
$(I FormatChar):
$(B 's')|$(B 'b')|$(B 'd')|$(B 'o')|$(B 'x')|$(B 'X')|$(B 'e')|$(B 'E')|$(B 'f')|$(B 'F')|$(B 'g')|$(B 'G')|$(B 'a')|$(B 'A')
)
$(BOOKTABLE Flags affect formatting depending on the specifier as
follows., $(TR $(TH Flag) $(TH Types affected) $(TH Semantics))
$(TR $(TD $(B '-')) $(TD numeric) $(TD Left justify the result in
the field. It overrides any $(B 0) flag.))
$(TR $(TD $(B '+')) $(TD numeric) $(TD Prefix positive numbers in
a signed conversion with a $(B +). It overrides any $(I space)
flag.))
$(TR $(TD $(B '#')) $(TD integral ($(B 'o'))) $(TD Add to
precision as necessary so that the first digit of the octal
formatting is a '0', even if both the argument and the $(I
Precision) are zero.))
$(TR $(TD $(B '#')) $(TD integral ($(B 'x'), $(B 'X'))) $(TD If
non-zero, prefix result with $(B 0x) ($(B 0X)).))
$(TR $(TD $(B '#')) $(TD floating) $(TD Always insert the decimal
point and print trailing zeros.))
$(TR $(TD $(B '#')) $(TD numeric ($(B '0'))) $(TD Use leading
zeros to pad rather than spaces (except for the floating point
values $(D nan) and $(D infinity)). Ignore if there's a $(I
Precision).))
$(TR $(TD $(B ' ')) $(TD numeric)) $(TD Prefix positive
numbers in a signed conversion with a space.))
<dt>$(I Width)
<dd>
Specifies the minimum field width.
If the width is a $(B *), the next argument, which must be
of type $(B int), is taken as the width.
If the width is negative, it is as if the $(B -) was given
as a $(I Flags) character.
<dt>$(I Precision)
<dd> Gives the precision for numeric conversions.
If the precision is a $(B *), the next argument, which must be
of type $(B int), is taken as the precision. If it is negative,
it is as if there was no $(I Precision).
<dt>$(I FormatChar)
<dd>
<dl>
<dt>$(B 's')
<dd>The corresponding argument is formatted in a manner consistent
with its type:
<dl>
<dt>$(B bool)
<dd>The result is <tt>'true'</tt> or <tt>'false'</tt>.
<dt>integral types
<dd>The $(B %d) format is used.
<dt>floating point types
<dd>The $(B %g) format is used.
<dt>string types
<dd>The result is the string converted to UTF-8.
A $(I Precision) specifies the maximum number of characters
to use in the result.
<dt>classes derived from $(B Object)
<dd>The result is the string returned from the class instance's
$(B .toString()) method.
A $(I Precision) specifies the maximum number of characters
to use in the result.
<dt>non-string static and dynamic arrays
<dd>The result is [s<sub>0</sub>, s<sub>1</sub>, ...]
where s<sub>k</sub> is the kth element
formatted with the default format.
</dl>
<dt>$(B 'c')
<dd>The corresponding argument must be a character type.
<dt>$(B 'b','d','o','x','X')
<dd> The corresponding argument must be an integral type
and is formatted as an integer. If the argument is a signed type
and the $(I FormatChar) is $(B d) it is converted to
a signed string of characters, otherwise it is treated as
unsigned. An argument of type $(B bool) is formatted as '1'
or '0'. The base used is binary for $(B b), octal for $(B o),
decimal
for $(B d), and hexadecimal for $(B x) or $(B X).
$(B x) formats using lower case letters, $(B X) uppercase.
If there are fewer resulting digits than the $(I Precision),
leading zeros are used as necessary.
If the $(I Precision) is 0 and the number is 0, no digits
result.
<dt>$(B 'e','E')
<dd> A floating point number is formatted as one digit before
the decimal point, $(I Precision) digits after, the $(I FormatChar),
±, followed by at least a two digit exponent: $(I d.dddddd)e$(I ±dd).
If there is no $(I Precision), six
digits are generated after the decimal point.
If the $(I Precision) is 0, no decimal point is generated.
<dt>$(B 'f','F')
<dd> A floating point number is formatted in decimal notation.
The $(I Precision) specifies the number of digits generated
after the decimal point. It defaults to six. At least one digit
is generated before the decimal point. If the $(I Precision)
is zero, no decimal point is generated.
<dt>$(B 'g','G')
<dd> A floating point number is formatted in either $(B e) or
$(B f) format for $(B g); $(B E) or $(B F) format for
$(B G).
The $(B f) format is used if the exponent for an $(B e) format
is greater than -5 and less than the $(I Precision).
The $(I Precision) specifies the number of significant
digits, and defaults to six.
Trailing zeros are elided after the decimal point, if the fractional
part is zero then no decimal point is generated.
<dt>$(B 'a','A')
<dd> A floating point number is formatted in hexadecimal
exponential notation 0x$(I h.hhhhhh)p$(I ±d).
There is one hexadecimal digit before the decimal point, and as
many after as specified by the $(I Precision).
If the $(I Precision) is zero, no decimal point is generated.
If there is no $(I Precision), as many hexadecimal digits as
necessary to exactly represent the mantissa are generated.
The exponent is written in as few digits as possible,
but at least one, is in decimal, and represents a power of 2 as in
$(I h.hhhhhh)*2<sup>$(I ±d)</sup>.
The exponent for zero is zero.
The hexadecimal digits, x and p are in upper case if the
$(I FormatChar) is upper case.
</dl>
Floating point NaN's are formatted as $(B nan) if the
$(I FormatChar) is lower case, or $(B NAN) if upper.
Floating point infinities are formatted as $(B inf) or
$(B infinity) if the
$(I FormatChar) is lower case, or $(B INF) or $(B INFINITY) if upper.
</dl>
Examples:
-------------------------
import std.c.stdio;
import std.format;
void main()
{
auto writer = appender!string();
formattedWrite(writer, "%s is the ultimate %s.", 42, "answer");
assert(writer.data == "42 is the ultimate answer.");
// Clear the writer
writer = appender!string();
formattedWrite(writer, "Date: %2$s %1$s", "October", 5);
assert(writer.data == "Date: 5 October");
}
------------------------
The positional and non-positional styles can be mixed in the same
format string. (POSIX leaves this behavior undefined.) The internal
counter for non-positional parameters tracks the next parameter after
the largest positional parameter already used.
Example using array and nested array formatting:
-------------------------
import std.stdio;
void main()
{
writefln("My items are %(%s %).", [1,2,3]);
writefln("My items are %(%s, %).", [1,2,3]);
}
-------------------------
The output is:
<pre class=console>
My items are 1 2 3.
My items are 1, 2, 3.
</pre>
The trailing end of the sub-format string following the specifier for each
item is interpreted as the array delimiter, and is therefore omitted
following the last array item. The $(B %|) delimiter specifier may be used
to indicate where the delimiter begins, so that the portion of the format
string prior to it will be retained in the last array element:
-------------------------
import std.stdio;
void main()
{
writefln("My items are %(-%s-%|, %).", [1,2,3]);
}
-------------------------
which gives the output:
<pre class=console>
My items are -1-, -2-, -3-.
</pre>
These compound format specifiers may be nested in the case of a nested
array argument:
-------------------------
import std.stdio;
void main() {
auto mat = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
writefln("%(%(%d %)\n%)", mat);
writeln();
writefln("[%(%(%d %)\n %)]", mat);
writeln();
writefln("[%([%(%d %)]%|\n %)]", mat);
writeln();
}
-------------------------
The output is:
<pre class=console>
1 2 3
4 5 6
7 8 9
[1 2 3
4 5 6
7 8 9]
[[1 2 3]
[4 5 6]
[7 8 9]]
</pre>
Inside a compound format specifier, strings and characters are escaped
automatically. To avoid this behavior, add $(B '-') flag to
$(D "%$(LPAREN)").
-------------------------
import std.stdio;
void main()
{
writefln("My friends are %s.", ["John", "Nancy"]);
writefln("My friends are %(%s, %).", ["John", "Nancy"]);
writefln("My friends are %-(%s, %).", ["John", "Nancy"]);
}
-------------------------
which gives the output:
<pre class=console>
My friends are ["John", "Nancy"].
My friends are "John", "Nancy".
My friends are John, Nancy.
</pre>
*/
uint formattedWrite(Writer, Char, A...)(Writer w, in Char[] fmt, A args)
{
enum len = args.length;
void function(Writer, const(void)*, ref FormatSpec!Char) funs[len] = void;
const(void)* argsAddresses[len] = void;
if (!__ctfe)
{
foreach (i, arg; args)
{
funs[i] = &formatGeneric!(Writer, typeof(arg), Char);
// We can safely cast away shared because all data is either
// immutable or completely owned by this function.
argsAddresses[i] = cast(const(void*)) &args[ i ];
}
}
// Are we already done with formats? Then just dump each parameter in turn
uint currentArg = 0;
auto spec = FormatSpec!Char(fmt);
while (spec.writeUpToNextSpec(w))
{
if (currentArg == funs.length && !spec.indexStart)
{
// leftover spec?
enforceEx!FormatException(
fmt.length == 0,
text("Orphan format specifier: %", fmt));
break;
}
if (spec.width == spec.DYNAMIC)
{
auto width = to!(typeof(spec.width))(getNthInt(currentArg, args));
if (width < 0)
{
spec.flDash = true;
width = -width;
}
spec.width = width;
++currentArg;
}
else if (spec.width < 0)
{
// means: get width as a positional parameter
auto index = cast(uint) -spec.width;
assert(index > 0);
auto width = to!(typeof(spec.width))(getNthInt(index - 1, args));
if (currentArg < index) currentArg = index;
if (width < 0)
{
spec.flDash = true;
width = -width;
}
spec.width = width;
}
if (spec.precision == spec.DYNAMIC)
{
auto precision = to!(typeof(spec.precision))(
getNthInt(currentArg, args));
if (precision >= 0) spec.precision = precision;
// else negative precision is same as no precision
else spec.precision = spec.UNSPECIFIED;
++currentArg;
}
else if (spec.precision < 0)
{
// means: get precision as a positional parameter
auto index = cast(uint) -spec.precision;
assert(index > 0);
auto precision = to!(typeof(spec.precision))(
getNthInt(index- 1, args));
if (currentArg < index) currentArg = index;
if (precision >= 0) spec.precision = precision;
// else negative precision is same as no precision
else spec.precision = spec.UNSPECIFIED;
}
// Format!
if (spec.indexStart > 0)
{
// using positional parameters!
foreach (i; spec.indexStart - 1 .. spec.indexEnd)
{
if (funs.length <= i) break;
if (__ctfe)
formatNth(w, spec, i, args);
else
funs[i](w, argsAddresses[i], spec);
}
if (currentArg < spec.indexEnd) currentArg = spec.indexEnd;
}
else
{
if (__ctfe)
formatNth(w, spec, currentArg, args);
else
funs[currentArg](w, argsAddresses[currentArg], spec);
++currentArg;
}
}
return currentArg;
}
/**
Reads characters from input range $(D r), converts them according
to $(D fmt), and writes them to $(D args).
Returns:
On success, the function returns the number of variables filled. This count
can match the expected number of readings or fewer, even zero, if a
matching failure happens.
Example:
----
string s = "hello!124:34.5";
string a;
int b;
double c;
formattedRead(s, "%s!%s:%s", &a, &b, &c);
assert(a == "hello" && b == 124 && c == 34.5);
----
*/
uint formattedRead(R, Char, S...)(ref R r, const(Char)[] fmt, S args)
{
auto spec = FormatSpec!Char(fmt);
static if (!S.length)
{
spec.readUpToNextSpec(r);
enforce(spec.trailing.empty);
return 0;
}
else
{
// The function below accounts for '*' == fields meant to be
// read and skipped
void skipUnstoredFields()
{
for (;;)
{
spec.readUpToNextSpec(r);
if (spec.width != spec.DYNAMIC) break;
// must skip this field
skipData(r, spec);
}
}
skipUnstoredFields();
if (r.empty)
{
// Input is empty, nothing to read
return 0;
}
alias typeof(*args[0]) A;
static if (isTuple!A)
{
foreach (i, T; A.Types)
{
(*args[0])[i] = unformatValue!(T)(r, spec);
skipUnstoredFields();
}
}
else
{
*args[0] = unformatValue!(A)(r, spec);
}
return 1 + formattedRead(r, spec.trailing, args[1 .. $]);
}
}
unittest
{
string s = " 1.2 3.4 ";
double x, y, z;
assert(formattedRead(s, " %s %s %s ", &x, &y, &z) == 2);
assert(s.empty);
assert(x == 1.2);
assert(y == 3.4);
assert(isnan(z));
}
template FormatSpec(Char)
if (!is(Unqual!Char == Char))
{
alias FormatSpec!(Unqual!Char) FormatSpec;
}
/**
A General handler for $(D printf) style format specifiers. Used for building more
specific formatting functions.
Example:
----
auto a = appender!(string)();
auto fmt = "Number: %2.4e\nString: %s";
auto f = FormatSpec!char(fmt);
f.writeUpToNextSpec(a);
assert(a.data == "Number: ");
assert(f.trailing == "\nString: %s");
assert(f.spec == 'e');
assert(f.width == 2);
assert(f.precision == 4);
f.writeUpToNextSpec(a);
assert(a.data == "Number: \nString: ");
assert(f.trailing == "");
assert(f.spec == 's');
----
*/
struct FormatSpec(Char)
if (is(Unqual!Char == Char))
{
/**
Minimum _width, default $(D 0).
*/
int width = 0;
/**
Precision. Its semantics depends on the argument type. For
floating point numbers, _precision dictates the number of
decimals printed.
*/
int precision = UNSPECIFIED;
/**
Special value for width and precision. $(D DYNAMIC) width or
precision means that they were specified with $(D '*') in the
format string and are passed at runtime through the varargs.
*/
enum int DYNAMIC = int.max;
/**
Special value for precision, meaning the format specifier
contained no explicit precision.
*/
enum int UNSPECIFIED = DYNAMIC - 1;
/**
The actual format specifier, $(D 's') by default.
*/
char spec = 's';
/**
Index of the argument for positional parameters, from $(D 1) to
$(D ubyte.max). ($(D 0) means not used).
*/
ubyte indexStart;
/**
Index of the last argument for positional parameter range, from
$(D 1) to $(D ubyte.max). ($(D 0) means not used).
*/
ubyte indexEnd;
version(StdDdoc) {
/**
The format specifier contained a $(D '-') ($(D printf)
compatibility).
*/
bool flDash;
/**
The format specifier contained a $(D '0') ($(D printf)
compatibility).
*/
bool flZero;
/**
The format specifier contained a $(D ' ') ($(D printf)
compatibility).
*/
bool flSpace;
/**
The format specifier contained a $(D '+') ($(D printf)
compatibility).
*/
bool flPlus;
/**
The format specifier contained a $(D '#') ($(D printf)
compatibility).
*/
bool flHash;
// Fake field to allow compilation
ubyte allFlags;
}
else
{
union
{
mixin(bitfields!(
bool, "flDash", 1,
bool, "flZero", 1,
bool, "flSpace", 1,
bool, "flPlus", 1,
bool, "flHash", 1,
ubyte, "", 3));
ubyte allFlags;
}
}
/**
In case of a compound format specifier starting with $(D
"%$(LPAREN)") and ending with $(D "%$(RPAREN)"), $(D _nested)
contains the string contained within the two separators.
*/
const(Char)[] nested;
/**
In case of a compound format specifier, $(D _sep) contains the
string positioning after $(D "%|").
*/
const(Char)[] sep;
/**
$(D _trailing) contains the rest of the format string.
*/
const(Char)[] trailing;
/*
This string is inserted before each sequence (e.g. array)
formatted (by default $(D "[")).
*/
enum immutable(Char)[] seqBefore = "[";
/*
This string is inserted after each sequence formatted (by
default $(D "]")).
*/
enum immutable(Char)[] seqAfter = "]";
/*
This string is inserted after each element keys of a sequence (by
default $(D ":")).
*/
enum immutable(Char)[] keySeparator = ":";
/*
This string is inserted in between elements of a sequence (by
default $(D ", ")).
*/
enum immutable(Char)[] seqSeparator = ", ";
/**
Construct a new $(D FormatSpec) using the format string $(D fmt), no
processing is done until needed.
*/
this(in Char[] fmt)
{
trailing = fmt;
}
bool writeUpToNextSpec(OutputRange)(OutputRange writer)
{
if (trailing.empty) return false;
for (size_t i = 0; i < trailing.length; ++i)
{
if (trailing[i] != '%') continue;
if (trailing[++i] != '%')
{
// Spec found. Print, fill up the spec, and bailout
put(writer, trailing[0 .. i - 1]);
trailing = trailing[i .. $];
fillUp();
return true;
}
// Doubled! Now print whatever we had, then update the
// string and move on
put(writer, trailing[0 .. i - 1]);
trailing = trailing[i .. $];
i = 0;
}
// no format spec found
put(writer, trailing);
trailing = null;
return false;
}
unittest
{
auto w = appender!(char[])();
auto f = FormatSpec("abc%sdef%sghi");
f.writeUpToNextSpec(w);
assert(w.data == "abc", w.data);
assert(f.trailing == "def%sghi", text(f.trailing));
f.writeUpToNextSpec(w);
assert(w.data == "abcdef", w.data);
assert(f.trailing == "ghi");
// test with embedded %%s
f = FormatSpec("ab%%cd%%ef%sg%%h%sij");
w.clear();
f.writeUpToNextSpec(w);
assert(w.data == "ab%cd%ef" && f.trailing == "g%%h%sij", w.data);
f.writeUpToNextSpec(w);
assert(w.data == "ab%cd%efg%h" && f.trailing == "ij");
// bug4775
f = FormatSpec("%%%s");
w.clear();
f.writeUpToNextSpec(w);
assert(w.data == "%" && f.trailing == "");
f = FormatSpec("%%%%%s%%");
w.clear();
while (f.writeUpToNextSpec(w)) continue;
assert(w.data == "%%%");
}
private void fillUp()
{
// Reset content
if (__ctfe)
{
flDash = false;
flZero = false;
flSpace = false;
flPlus = false;
flHash = false;
}
else
{
allFlags = 0;
}
width = 0;
precision = UNSPECIFIED;
nested = null;
// Parse the spec (we assume we're past '%' already)
for (size_t i = 0; i < trailing.length; )
{
switch (trailing[i])
{
case '(':
// Embedded format specifier.
auto j = i + 1;
void check(bool condition)
{
enforce(
condition,
text("Incorrect format specifier: %", trailing[i .. $]));
}
// Get the matching balanced paren
for (uint innerParens;;)
{
check(j < trailing.length);
if (trailing[j++] != '%')
{
// skip, we're waiting for %( and %)
continue;
}
if (trailing[j] == '-') // for %-(
++j; // skip
if (trailing[j] == ')')
{
if (innerParens-- == 0) break;
}
else if (trailing[j] == '|')
{
if (innerParens == 0) break;
}
else if (trailing[j] == '(')
{
++innerParens;
}
}
if (trailing[j] == '|')
{
auto k = j;
for (++j;;)
{
if (trailing[j++] != '%')
continue;
if (trailing[j] == '%')
++j;
else if (trailing[j] == ')')
break;
else
throw new Exception(
text("Incorrect format specifier: %",
trailing[j .. $]));
}
nested = to!(typeof(nested))(trailing[i + 1 .. k - 1]);
sep = to!(typeof(nested))(trailing[k + 1 .. j - 1]);
}
else
{
nested = to!(typeof(nested))(trailing[i + 1 .. j - 1]);
sep = null;
}
//this = FormatSpec(innerTrailingSpec);
spec = '(';
// We practically found the format specifier
trailing = trailing[j + 1 .. $];
return;
case '-': flDash = true; ++i; break;
case '+': flPlus = true; ++i; break;
case '#': flHash = true; ++i; break;
case '0': flZero = true; ++i; break;
case ' ': flSpace = true; ++i; break;
case '*':
if (isDigit(trailing[++i]))
{
// a '*' followed by digits and '$' is a
// positional format
trailing = trailing[1 .. $];
width = -.parse!(typeof(width))(trailing);
i = 0;
enforceEx!FormatException(
trailing[i++] == '$',
"$ expected");
}
else
{
// read result
width = DYNAMIC;
}
break;
case '1': .. case '9':
auto tmp = trailing[i .. $];
const widthOrArgIndex = .parse!(uint)(tmp);
enforceEx!FormatException(
tmp.length,
text("Incorrect format specifier %", trailing[i .. $]));
i = tmp.ptr - trailing.ptr;
if (tmp.startsWith('$'))
{
// index of the form %n$
indexEnd = indexStart = to!ubyte(widthOrArgIndex);
++i;
}
else if (tmp.length && tmp[0] == ':')
{
// two indexes of the form %m:n$, or one index of the form %m:$
indexStart = to!ubyte(widthOrArgIndex);
tmp = tmp[1 .. $];
if (tmp.startsWith('$'))
{
indexEnd = indexEnd.max;
}
else
{
indexEnd = .parse!(typeof(indexEnd))(tmp);
}
i = tmp.ptr - trailing.ptr;
enforceEx!FormatException(
trailing[i++] == '$',
"$ expected");
}
else
{
// width
width = to!int(widthOrArgIndex);
}
break;
case '.':
// Precision
if (trailing[++i] == '*')
{
if (isDigit(trailing[++i]))
{
// a '.*' followed by digits and '$' is a
// positional precision
trailing = trailing[i .. $];
i = 0;
precision = -.parse!int(trailing);
enforceEx!FormatException(
trailing[i++] == '$',
"$ expected");
}
else
{
// read result
precision = DYNAMIC;
}
}
else if (trailing[i] == '-')
{
// negative precision, as good as 0
precision = 0;
auto tmp = trailing[i .. $];
.parse!(int)(tmp); // skip digits
i = tmp.ptr - trailing.ptr;
}
else if (isDigit(trailing[i]))
{
auto tmp = trailing[i .. $];
precision = .parse!int(tmp);
i = tmp.ptr - trailing.ptr;
}
else
{
// "." was specified, but nothing after it
precision = 0;
}
break;
default:
// this is the format char
spec = cast(char) trailing[i++];
trailing = trailing[i .. $];
return;
} // end switch
} // end for
throw new Exception(text("Incorrect format specifier: ", trailing));
}
//--------------------------------------------------------------------------
private bool readUpToNextSpec(R)(ref R r)
{
// Reset content
if (__ctfe)
{
flDash = false;
flZero = false;
flSpace = false;
flPlus = false;
flHash = false;
}
else
{
allFlags = 0;
}
width = 0;
precision = UNSPECIFIED;
nested = null;
// Parse the spec
while (trailing.length)
{
if (*trailing.ptr == '%')
{
if (trailing.length > 1 && trailing.ptr[1] == '%')
{
assert(!r.empty);
// Require a '%'
if (r.front != '%') break;
trailing = trailing[2 .. $];
r.popFront();
}
else
{
enforce(isLower(trailing[1]) || trailing[1] == '*' ||
trailing[1] == '(',
text("'%", trailing[1],
"' not supported with formatted read"));
trailing = trailing[1 .. $];
fillUp();
return true;
}
}
else
{
if (trailing.ptr[0] == ' ')
{
while (!r.empty && std.ascii.isWhite(r.front)) r.popFront();
//r = std.algorithm.find!(not!(std.ascii.isWhite))(r);
}
else
{
enforce(!r.empty,
text("parseToFormatSpec: Cannot find character `",
trailing.ptr[0], "' in the input string."));
if (r.front != trailing.front) break;
r.popFront();
}
trailing = trailing[std.utf.stride(trailing, 0) .. $];
}
}
return false;
}
private const string getCurFmtStr()
{
auto w = appender!string();
auto f = FormatSpec!Char("%s"); // for stringnize
put(w, '%');
if (indexStart != 0)
formatValue(w, indexStart, f), put(w, '$');
if (flDash) put(w, '-');
if (flZero) put(w, '0');
if (flSpace) put(w, ' ');
if (flPlus) put(w, '+');
if (flHash) put(w, '#');
if (width != 0)
formatValue(w, width, f);
if (precision != FormatSpec!Char.UNSPECIFIED)
put(w, '.'), formatValue(w, precision, f);
put(w, spec);
return w.data;
}
unittest
{
// issue 5237
auto w = appender!string();
auto f = FormatSpec!char("%.16f");
f.writeUpToNextSpec(w); // dummy eating
assert(f.spec == 'f');
auto fmt = f.getCurFmtStr();
assert(fmt == "%.16f");
}
private const(Char)[] headUpToNextSpec()
{
auto w = appender!(typeof(return))();
auto tr = trailing;
while (tr.length)
{
if (*tr.ptr == '%')
{
if (tr.length > 1 && tr.ptr[1] == '%')
{
tr = tr[2 .. $];
w.put('%');
}
else
break;
}
else
{
w.put(tr.front);
tr.popFront();
}
}
return w.data;
}
string toString()
{
return text("address = ", cast(void*) &this,
"\nwidth = ", width,
"\nprecision = ", precision,
"\nspec = ", spec,
"\nindexStart = ", indexStart,
"\nindexEnd = ", indexEnd,
"\nflDash = ", flDash,
"\nflZero = ", flZero,
"\nflSpace = ", flSpace,
"\nflPlus = ", flPlus,
"\nflHash = ", flHash,
"\nnested = ", nested,
"\ntrailing = ", trailing, "\n");
}
}
unittest
{
//Test the example
auto a = appender!(string)();
auto fmt = "Number: %2.4e\nString: %s";
auto f = FormatSpec!char(fmt);
f.writeUpToNextSpec(a);
assert(a.data == "Number: ");
assert(f.trailing == "\nString: %s");
assert(f.spec == 'e');
assert(f.width == 2);
assert(f.precision == 4);
f.writeUpToNextSpec(a);
assert(a.data == "Number: \nString: ");
assert(f.trailing == "");
assert(f.spec == 's');
}
/**
Helper function that returns a $(D FormatSpec) for a single specifier given
in $(D fmt)
Returns a $(D FormatSpec) with the specifier parsed.
Enforces giving only one specifier to the function.
*/
FormatSpec!Char singleSpec(Char)(Char[] fmt)
{
enforce(fmt.length >= 2, new Exception("fmt must be at least 2 characters long"));
enforce(fmt.front == '%', new Exception("fmt must start with a '%' character"));
static struct DummyOutputRange {
void put(C)(C[] buf) {} // eat elements
}
auto a = DummyOutputRange();
auto spec = FormatSpec!Char(fmt);
//dummy write
spec.writeUpToNextSpec(a);
enforce(spec.trailing.empty,
new Exception(text("Trailing characters in fmt string: '", spec.trailing)));
return spec;
}
unittest
{
auto spec = singleSpec("%2.3e");
assert(spec.trailing == "");
assert(spec.spec == 'e');
assert(spec.width == 2);
assert(spec.precision == 3);
assertThrown(singleSpec(""));
assertThrown(singleSpec("2.3e"));
assertThrown(singleSpec("%2.3eTest"));
}
/**
$(D bool)s are formatted as "true" or "false" with %s and as "1" or
"0" with integral-specific format specs.
*/
void formatValue(Writer, T, Char)(Writer w, T obj, ref FormatSpec!Char f)
if (is(BooleanTypeOf!T) && !is(T == enum) && !hasToString!(T, Char))
{
BooleanTypeOf!T val = obj;
if (f.spec == 's')
{
string s = val ? "true" : "false";
if (!f.flDash)
{
// right align
if (f.width > s.length)
foreach (i ; 0 .. f.width - s.length) put(w, ' ');
put(w, s);
}
else
{
// left align
put(w, s);
if (f.width > s.length)
foreach (i ; 0 .. f.width - s.length) put(w, ' ');
}
}
else
formatValue(w, cast(int) val, f);
}
unittest
{
formatTest( false, "false" );
formatTest( true, "true" );
class C1 { bool val; alias val this; this(bool v){ val = v; } }
class C2 { bool val; alias val this; this(bool v){ val = v; }
override string toString() const { return "C"; } }
formatTest( new C1(false), "false" );
formatTest( new C1(true), "true" );
formatTest( new C2(false), "C" );
formatTest( new C2(true), "C" );
struct S1 { bool val; alias val this; }
struct S2 { bool val; alias val this;
string toString() const { return "S"; } }
formatTest( S1(false), "false" );
formatTest( S1(true), "true" );
formatTest( S2(false), "S" );
formatTest( S2(true), "S" );
}
unittest
{
string t1 = format("[%6s] [%6s] [%-6s]", true, false, true);
assert(t1 == "[ true] [ false] [true ]");
string t2 = format("[%3s] [%-2s]", true, false);
assert(t2 == "[true] [false]");
}
/**
$(D null) literal is formatted as $(D "null").
*/
void formatValue(Writer, T, Char)(Writer w, T obj, ref FormatSpec!Char f)
if (is(T == typeof(null)) && !is(T == enum) && !hasToString!(T, Char))
{
enforceEx!FormatException(f.spec == 's', "null");
put(w, "null");
}
unittest
{
formatTest( null, "null" );
}
/**
Integrals are formatted like $(D printf) does.
*/
void formatValue(Writer, T, Char)(Writer w, T obj, ref FormatSpec!Char f)
if (is(IntegralTypeOf!T) && !is(T == enum) && !hasToString!(T, Char))
{
alias U = IntegralTypeOf!T;
U val = obj;
if (f.spec == 'r')
{
// raw write, skip all else and write the thing
auto begin = cast(const char*) &val;
if (std.system.endian == Endian.littleEndian && f.flPlus
|| std.system.endian == Endian.bigEndian && f.flDash)
{
// must swap bytes
foreach_reverse (i; 0 .. val.sizeof)
put(w, begin[i]);
}
else
{
foreach (i; 0 .. val.sizeof)
put(w, begin[i]);
}
return;
}
// Forward on to formatIntegral to handle both U and const(U)
// Saves duplication of code for both versions.
static if (isSigned!U)
formatIntegral(w, cast(long) val, f, Unsigned!U.max);
else
formatIntegral(w, cast(ulong) val, f, U.max);
}
private void formatIntegral(Writer, T, Char)(Writer w, const(T) val, ref FormatSpec!Char f, ulong mask)
{
FormatSpec!Char fs = f; // fs is copy for change its values.
T arg = val;
uint base =
fs.spec == 'x' || fs.spec == 'X' ? 16 :
fs.spec == 'o' ? 8 :
fs.spec == 'b' ? 2 :
fs.spec == 's' || fs.spec == 'd' || fs.spec == 'u' ? 10 :
0;
enforceEx!FormatException(
base > 0,
"integral");
bool negative = (base == 10 && arg < 0);
if (negative)
{
arg = -arg;
}
// All unsigned integral types should fit in ulong.
formatUnsigned(w, (cast(ulong) arg) & mask, fs, base, negative);
}
private void formatUnsigned(Writer, Char)(Writer w, ulong arg, ref FormatSpec!Char fs, uint base, bool negative)
{
if (fs.precision == fs.UNSPECIFIED)
{
// default precision for integrals is 1
fs.precision = 1;
}
else
{
// if a precision is specified, the '0' flag is ignored.
fs.flZero = false;
}
char leftPad = void;
if (!fs.flDash && !fs.flZero)
leftPad = ' ';
else if (!fs.flDash && fs.flZero)
leftPad = '0';
else
leftPad = 0;
// figure out sign and continue in unsigned mode
char forcedPrefix = void;
if (fs.flPlus) forcedPrefix = '+';
else if (fs.flSpace) forcedPrefix = ' ';
else forcedPrefix = 0;
if (base != 10)
{
// non-10 bases are always unsigned
forcedPrefix = 0;
}
else if (negative)
{
// argument is signed
forcedPrefix = '-';
}
// fill the digits
char[] digits = void;
{
char buffer[64]; // 64 bits in base 2 at most
uint i = buffer.length;
auto n = arg;
do
{
--i;
buffer[i] = cast(char) (n % base);
n /= base;
if (buffer[i] < 10) buffer[i] += '0';
else buffer[i] += (fs.spec == 'x' ? 'a' : 'A') - 10;
} while (n);
digits = buffer[i .. $]; // got the digits without the sign
}
// adjust precision to print a '0' for octal if alternate format is on
if (base == 8 && fs.flHash
&& (fs.precision <= digits.length)) // too low precision
{
//fs.precision = digits.length + (arg != 0);
forcedPrefix = '0';
}
// write left pad; write sign; write 0x or 0X; write digits;
// write right pad
// Writing left pad
ptrdiff_t spacesToPrint =
fs.width // start with the minimum width
- digits.length // take away digits to print
- (forcedPrefix != 0) // take away the sign if any
- (base == 16 && fs.flHash && arg ? 2 : 0); // 0x or 0X
const ptrdiff_t delta = fs.precision - digits.length;
if (delta > 0) spacesToPrint -= delta;
if (spacesToPrint > 0) // need to do some padding
{
if (leftPad == '0')
{
// pad with zeros
fs.precision =
cast(typeof(fs.precision)) (spacesToPrint + digits.length);
//to!(typeof(fs.precision))(spacesToPrint + digits.length);
}
else if (leftPad) foreach (i ; 0 .. spacesToPrint) put(w, ' ');
}
// write sign
if (forcedPrefix) put(w, forcedPrefix);
// write 0x or 0X
if (base == 16 && fs.flHash && arg) {
// @@@ overcome bug in dmd;
//w.write(fs.spec == 'x' ? "0x" : "0X"); //crashes the compiler
put(w, '0');
put(w, fs.spec == 'x' ? 'x' : 'X'); // x or X
}
// write the digits
if (arg || fs.precision)
{
ptrdiff_t zerosToPrint = fs.precision - digits.length;
foreach (i ; 0 .. zerosToPrint) put(w, '0');
put(w, digits);
}
// write the spaces to the right if left-align
if (!leftPad) foreach (i ; 0 .. spacesToPrint) put(w, ' ');
}
unittest
{
formatTest( 10, "10" );
class C1 { long val; alias val this; this(long v){ val = v; } }
class C2 { long val; alias val this; this(long v){ val = v; }
override string toString() const { return "C"; } }
formatTest( new C1(10), "10" );
formatTest( new C2(10), "C" );
struct S1 { long val; alias val this; }
struct S2 { long val; alias val this;
string toString() const { return "S"; } }
formatTest( S1(10), "10" );
formatTest( S2(10), "S" );
}
// bugzilla 9117
unittest
{
static struct Frop {}
static struct Foo
{
int n = 0;
alias n this;
T opCast(T) () if (is(T == Frop))
{
return Frop();
}
string toString()
{
return "Foo";
}
}
static struct Bar
{
Foo foo;
alias foo this;
string toString()
{
return "Bar";
}
}
const(char)[] result;
void put(const char[] s){ result ~= s; }
Foo foo;
formattedWrite(&put, "%s", foo); // OK
assert(result == "Foo");
result = null;
Bar bar;
formattedWrite(&put, "%s", bar); // NG
assert(result == "Bar");
}
/**
* Floating-point values are formatted like $(D printf) does.
*/
void formatValue(Writer, T, Char)(Writer w, T obj, ref FormatSpec!Char f)
if (is(FloatingPointTypeOf!T) && !is(T == enum) && !hasToString!(T, Char))
{
FormatSpec!Char fs = f; // fs is copy for change its values.
FloatingPointTypeOf!T val = obj;
if (fs.spec == 'r')
{
// raw write, skip all else and write the thing
auto begin = cast(const char*) &val;
if (std.system.endian == Endian.littleEndian && f.flPlus
|| std.system.endian == Endian.bigEndian && f.flDash)
{
// must swap bytes
foreach_reverse (i; 0 .. val.sizeof)
put(w, begin[i]);
}
else
{
foreach (i; 0 .. val.sizeof)
put(w, begin[i]);
}
return;
}
enforceEx!FormatException(
std.algorithm.find("fgFGaAeEs", fs.spec).length,
"floating");
version (Win64)
{
if (isnan(val)) // snprintf writes 1.#QNAN
{
version(none)
{
return formatValue(w, "nan", f);
}
else // FIXME:workaroun
{
auto s = "nan"[0 .. f.precision < $ ? f.precision : $];
if (!f.flDash)
{
// right align
if (f.width > s.length)
foreach (j ; 0 .. f.width - s.length) put(w, ' ');
put(w, s);
}
else
{
// left align
put(w, s);
if (f.width > s.length)
foreach (j ; 0 .. f.width - s.length) put(w, ' ');
}
return;
}
}
}
if (fs.spec == 's') fs.spec = 'g';
char sprintfSpec[1 /*%*/ + 5 /*flags*/ + 3 /*width.prec*/ + 2 /*format*/
+ 1 /*\0*/] = void;
sprintfSpec[0] = '%';
uint i = 1;
if (fs.flDash) sprintfSpec[i++] = '-';
if (fs.flPlus) sprintfSpec[i++] = '+';
if (fs.flZero) sprintfSpec[i++] = '0';
if (fs.flSpace) sprintfSpec[i++] = ' ';
if (fs.flHash) sprintfSpec[i++] = '#';
sprintfSpec[i .. i + 3] = "*.*";
i += 3;
if (is(Unqual!(typeof(val)) == real)) sprintfSpec[i++] = 'L';
sprintfSpec[i++] = fs.spec;
sprintfSpec[i] = 0;
//printf("format: '%s'; geeba: %g\n", sprintfSpec.ptr, val);
char[512] buf;
immutable n = snprintf(buf.ptr, buf.length,
sprintfSpec.ptr,
fs.width,
// negative precision is same as no precision specified
fs.precision == fs.UNSPECIFIED ? -1 : fs.precision,
val);
enforceEx!FormatException(
n >= 0,
"floating point formatting failure");
put(w, buf[0 .. strlen(buf.ptr)]);
}
unittest
{
foreach (T; TypeTuple!(float, double, real))
{
formatTest( to!( T)(5.5), "5.5" );
formatTest( to!( const T)(5.5), "5.5" );
formatTest( to!(immutable T)(5.5), "5.5" );
}
}
unittest
{
formatTest( 2.25, "2.25" );
class C1 { double val; alias val this; this(double v){ val = v; } }
class C2 { double val; alias val this; this(double v){ val = v; }
override string toString() const { return "C"; } }
formatTest( new C1(2.25), "2.25" );
formatTest( new C2(2.25), "C" );
struct S1 { double val; alias val this; }
struct S2 { double val; alias val this;
string toString() const { return "S"; } }
formatTest( S1(2.25), "2.25" );
formatTest( S2(2.25), "S" );
}
unittest
{
foreach (T; TypeTuple!(float, double, real))
{
formatTest( T.nan, "nan" );
}
}
/*
Formatting a $(D creal) is deprecated but still kept around for a while.
*/
void formatValue(Writer, T, Char)(Writer w, T obj, ref FormatSpec!Char f)
if (is(Unqual!T : creal) && !is(T == enum) && !hasToString!(T, Char))
{
creal val = obj;
formatValue(w, val.re, f);
put(w, '+');
formatValue(w, val.im, f);
put(w, 'i');
}
unittest
{
foreach (T; TypeTuple!(cfloat, cdouble, creal))
{
formatTest( to!( T)(1 + 1i), "1+1i" );
formatTest( to!( const T)(1 + 1i), "1+1i" );
formatTest( to!(immutable T)(1 + 1i), "1+1i" );
}
}
unittest
{
formatTest( 3+2.25i, "3+2.25i" );
class C1 { cdouble val; alias val this; this(cdouble v){ val = v; } }
class C2 { cdouble val; alias val this; this(cdouble v){ val = v; }
override string toString() const { return "C"; } }
formatTest( new C1(3+2.25i), "3+2.25i" );
formatTest( new C2(3+2.25i), "C" );
struct S1 { cdouble val; alias val this; }
struct S2 { cdouble val; alias val this;
string toString() const { return "S"; } }
formatTest( S1(3+2.25i), "3+2.25i" );
formatTest( S2(3+2.25i), "S" );
}
/*
Formatting an $(D ireal) is deprecated but still kept around for a while.
*/
void formatValue(Writer, T, Char)(Writer w, T obj, ref FormatSpec!Char f)
if (is(Unqual!T : ireal) && !is(T == enum) && !hasToString!(T, Char))
{
ireal val = obj;
formatValue(w, val.im, f);
put(w, 'i');
}
unittest
{
foreach (T; TypeTuple!(ifloat, idouble, ireal))
{
formatTest( to!( T)(1i), "1i" );
formatTest( to!( const T)(1i), "1i" );
formatTest( to!(immutable T)(1i), "1i" );
}
}
unittest
{
formatTest( 2.25i, "2.25i" );
class C1 { idouble val; alias val this; this(idouble v){ val = v; } }
class C2 { idouble val; alias val this; this(idouble v){ val = v; }
override string toString() const { return "C"; } }
formatTest( new C1(2.25i), "2.25i" );
formatTest( new C2(2.25i), "C" );
struct S1 { idouble val; alias val this; }
struct S2 { idouble val; alias val this;
string toString() const { return "S"; } }
formatTest( S1(2.25i), "2.25i" );
formatTest( S2(2.25i), "S" );
}
/**
Individual characters ($(D char), $(D wchar), or $(D dchar)) are
formatted as Unicode characters with %s and as integers with
integral-specific format specs.
*/
void formatValue(Writer, T, Char)(Writer w, T obj, ref FormatSpec!Char f)
if (is(CharTypeOf!T) && !is(T == enum) && !hasToString!(T, Char))
{
CharTypeOf!T val = obj;
if (f.spec == 's' || f.spec == 'c')
{
put(w, val);
}
else
{
formatValue(w, cast(uint) val, f);
}
}
unittest
{
formatTest( 'c', "c" );
class C1 { char val; alias val this; this(char v){ val = v; } }
class C2 { char val; alias val this; this(char v){ val = v; }
override string toString() const { return "C"; } }
formatTest( new C1('c'), "c" );
formatTest( new C2('c'), "C" );
struct S1 { char val; alias val this; }
struct S2 { char val; alias val this;
string toString() const { return "S"; } }
formatTest( S1('c'), "c" );
formatTest( S2('c'), "S" );
}
/**
Strings are formatted like $(D printf) does.
*/
void formatValue(Writer, T, Char)(Writer w, T obj, ref FormatSpec!Char f)
if (is(StringTypeOf!T) && !is(StaticArrayTypeOf!T) && !is(T == enum) && !hasToString!(T, Char))
{
Unqual!(StringTypeOf!T) val = obj; // for `alias this`, see bug5371
formatRange(w, val, f);
}
unittest
{
formatTest( "abc", "abc" );
}
unittest
{
// Test for bug 5371 for classes
class C1 { const string var; alias var this; this(string s){ var = s; } }
class C2 { string var; alias var this; this(string s){ var = s; } }
formatTest( new C1("c1"), "c1" );
formatTest( new C2("c2"), "c2" );
// Test for bug 5371 for structs
struct S1 { const string var; alias var this; }
struct S2 { string var; alias var this; }
formatTest( S1("s1"), "s1" );
formatTest( S2("s2"), "s2" );
}
unittest
{
class C3 { string val; alias val this; this(string s){ val = s; }
override string toString() const { return "C"; } }
formatTest( new C3("c3"), "C" );
struct S3 { string val; alias val this;
string toString() const { return "S"; } }
formatTest( S3("s3"), "S" );
}
/**
Static-size arrays are formatted as dynamic arrays.
*/
void formatValue(Writer, T, Char)(Writer w, auto ref T obj, ref FormatSpec!Char f)
if (is(StaticArrayTypeOf!T) && !is(T == enum) && !hasToString!(T, Char))
{
formatValue(w, obj[], f);
}
unittest // Test for issue 8310
{
FormatSpec!char f;
auto w = appender!string();
char[2] two = ['a', 'b'];
formatValue(w, two, f);
char[2] getTwo(){ return two; }
formatValue(w, getTwo(), f);
}
/**
Dynamic arrays are formatted as input ranges.
Specializations:
$(UL $(LI $(D void[]) is formatted like $(D ubyte[]).)
$(LI Const array is converted to input range by removing its qualifier.))
*/
void formatValue(Writer, T, Char)(Writer w, T obj, ref FormatSpec!Char f)
if (is(DynamicArrayTypeOf!T) && !is(StringTypeOf!T) && !is(T == enum) && !hasToString!(T, Char))
{
static if (is(const(ArrayTypeOf!T) == const(void[])))
{
formatValue(w, cast(const ubyte[])obj, f);
}
else static if (!isInputRange!T)
{
alias Unqual!(ArrayTypeOf!T) U;
static assert(isInputRange!U);
U val = obj;
formatValue(w, val, f);
}
else
{
formatRange(w, obj, f);
}
}
// alias this, input range I/F, and toString()
unittest
{
struct S(uint flags)
{
int[] arr;
static if (flags & 1)
alias arr this;
static if (flags & 2)
{
@property bool empty() const { return arr.length == 0; }
@property int front() const { return arr[0] * 2; }
void popFront() { arr = arr[1..$]; }
}
static if (flags & 4)
string toString() const { return "S"; }
}
formatTest(S!0b000([0, 1, 2]), "S!(0)([0, 1, 2])");
formatTest(S!0b001([0, 1, 2]), "[0, 1, 2]"); // Test for bug 7628
formatTest(S!0b010([0, 1, 2]), "[0, 2, 4]");
formatTest(S!0b011([0, 1, 2]), "[0, 2, 4]");
formatTest(S!0b100([0, 1, 2]), "S");
formatTest(S!0b101([0, 1, 2]), "S"); // Test for bug 7628
formatTest(S!0b110([0, 1, 2]), "S");
formatTest(S!0b111([0, 1, 2]), "S");
class C(uint flags)
{
int[] arr;
static if (flags & 1)
alias arr this;
this(int[] a) { arr = a; }
static if (flags & 2)
{
@property bool empty() const { return arr.length == 0; }
@property int front() const { return arr[0] * 2; }
void popFront() { arr = arr[1..$]; }
}
static if (flags & 4)
override string toString() const { return "C"; }
}
formatTest(new C!0b000([0, 1, 2]), (new C!0b000([])).toString());
formatTest(new C!0b001([0, 1, 2]), "[0, 1, 2]"); // Test for bug 7628
formatTest(new C!0b010([0, 1, 2]), "[0, 2, 4]");
formatTest(new C!0b011([0, 1, 2]), "[0, 2, 4]");
formatTest(new C!0b100([0, 1, 2]), "C");
formatTest(new C!0b101([0, 1, 2]), "C"); // Test for bug 7628
formatTest(new C!0b110([0, 1, 2]), "C");
formatTest(new C!0b111([0, 1, 2]), "C");
}
unittest
{
// void[]
void[] val0;
formatTest( val0, "[]" );
void[] val = cast(void[])cast(ubyte[])[1, 2, 3];
formatTest( val, "[1, 2, 3]" );
void[0] sval0 = [];
formatTest( sval0, "[]");
void[3] sval = cast(void[3])cast(ubyte[3])[1, 2, 3];
formatTest( sval, "[1, 2, 3]" );
}
unittest
{
// const(T[]) -> const(T)[]
const short[] a = [1, 2, 3];
formatTest( a, "[1, 2, 3]" );
struct S { const(int[]) arr; alias arr this; }
auto s = S([1,2,3]);
formatTest( s, "[1, 2, 3]" );
}
unittest
{
// 6640
struct Range
{
string value;
const @property bool empty(){ return !value.length; }
const @property dchar front(){ return value.front; }
void popFront(){ value.popFront(); }
const @property size_t length(){ return value.length; }
}
immutable table =
[
["[%s]", "[string]"],
["[%10s]", "[ string]"],
["[%-10s]", "[string ]"],
["[%(%02x %)]", "[73 74 72 69 6e 67]"],
["[%(%c %)]", "[s t r i n g]"],
];
foreach (e; table)
{
formatTest(e[0], "string", e[1]);
formatTest(e[0], Range("string"), e[1]);
}
}
unittest
{
// string literal from valid UTF sequence is encoding free.
foreach (StrType; TypeTuple!(string, wstring, dstring))
{
// Valid and printable (ASCII)
formatTest( [cast(StrType)"hello"],
`["hello"]` );
// 1 character escape sequences (' is not escaped in strings)
formatTest( [cast(StrType)"\"'\\\a\b\f\n\r\t\v"],
`["\"'\\\a\b\f\n\r\t\v"]` );
// Valid and non-printable code point (<= U+FF)
formatTest( [cast(StrType)"\x00\x10\x1F\x20test"],
`["\x00\x10\x1F test"]` );
// Valid and non-printable code point (<= U+FFFF)
formatTest( [cast(StrType)"\u200B..\u200F"],
`["\u200B..\u200F"]` );
// Valid and non-printable code point (<= U+10FFFF)
formatTest( [cast(StrType)"\U000E0020..\U000E007F"],
`["\U000E0020..\U000E007F"]` );
}
// invalid UTF sequence needs hex-string literal postfix (c/w/d)
{
// U+FFFF with UTF-8 (Invalid code point for interchange)
formatTest( [cast(string)[0xEF, 0xBF, 0xBF]],
`[x"EF BF BF"c]` );
// U+FFFF with UTF-16 (Invalid code point for interchange)
formatTest( [cast(wstring)[0xFFFF]],
`[x"FFFF"w]` );
// U+FFFF with UTF-32 (Invalid code point for interchange)
formatTest( [cast(dstring)[0xFFFF]],
`[x"FFFF"d]` );
}
}
unittest
{
// nested range formatting with array of string
formatTest( "%({%(%02x %)}%| %)", ["test", "msg"],
`{74 65 73 74} {6d 73 67}` );
}
unittest
{
// stop auto escaping inside range formatting
auto arr = ["hello", "world"];
formatTest( "%(%s, %)", arr, `"hello", "world"` );
formatTest( "%-(%s, %)", arr, `hello, world` );
auto aa1 = [1:"hello", 2:"world"];
formatTest( "%(%s:%s, %)", aa1, `1:"hello", 2:"world"` );
formatTest( "%-(%s:%s, %)", aa1, `1:hello, 2:world` );
auto aa2 = [1:["ab", "cd"], 2:["ef", "gh"]];
formatTest( "%-(%s:%s, %)", aa2, `1:["ab", "cd"], 2:["ef", "gh"]` );
formatTest( "%-(%s:%(%s%), %)", aa2, `1:"ab""cd", 2:"ef""gh"` );
formatTest( "%-(%s:%-(%s%)%|, %)", aa2, `1:abcd, 2:efgh` );
}
// input range formatting
private void formatRange(Writer, T, Char)(ref Writer w, ref T val, ref FormatSpec!Char f)
if (isInputRange!T)
{
// Formatting character ranges like string
static if (is(CharTypeOf!(ElementType!T)))
if (f.spec == 's')
{
static if (is(StringTypeOf!T))
{
auto s = val[0 .. f.precision < $ ? f.precision : $];
if (!f.flDash)
{
// right align
if (f.width > s.length)
foreach (i ; 0 .. f.width - s.length) put(w, ' ');
put(w, s);
}
else
{
// left align
put(w, s);
if (f.width > s.length)
foreach (i ; 0 .. f.width - s.length) put(w, ' ');
}
}
else
{
if (!f.flDash)
{
static if (hasLength!T)
{
// right align
auto len = val.length;
}
else static if (isForwardRange!T && !isInfinite!T)
{
auto len = walkLength(val.save);
}
else
{
enforce(f.width == 0, "Cannot right-align a range without length");
size_t len = 0;
}
if (f.precision != f.UNSPECIFIED && len > f.precision)
len = f.precision;
if (f.width > len)
foreach (i ; 0 .. f.width - len)
put(w, ' ');
if (f.precision == f.UNSPECIFIED)
put(w, val);
else
{
size_t printed = 0;
for (; !val.empty && printed < f.precision; val.popFront(), ++printed)
put(w, val.front);
}
}
else
{
size_t printed = void;
// left align
if (f.precision == f.UNSPECIFIED)
{
static if (hasLength!T)
{
printed = val.length;
put(w, val);
}
else
{
printed = 0;
for (; !val.empty; val.popFront(), ++printed)
put(w, val.front);
}
}
else
{
printed = 0;
for (; !val.empty && printed < f.precision; val.popFront(), ++printed)
put(w, val.front);
}
if (f.width > printed)
foreach (i ; 0 .. f.width - printed)
put(w, ' ');
}
}
return;
}
if (f.spec == 'r')
{
// raw writes
for (size_t i; !val.empty; val.popFront(), ++i)
{
formatValue(w, val.front, f);
}
}
else if (f.spec == 's')
{
put(w, f.seqBefore);
if (!val.empty)
{
formatElement(w, val.front, f);
val.popFront();
for (size_t i; !val.empty; val.popFront(), ++i)
{
put(w, f.seqSeparator);
formatElement(w, val.front, f);
}
}
static if (!isInfinite!T) put(w, f.seqAfter);
}
else if (f.spec == '(')
{
if (val.empty)
return;
// Nested specifier is to be used
for (;;)
{
auto fmt = FormatSpec!Char(f.nested);
fmt.writeUpToNextSpec(w);
if (f.flDash)
formatValue(w, val.front, fmt);
else
formatElement(w, val.front, fmt);
if (f.sep)
{
put(w, fmt.trailing);
val.popFront();
if (val.empty)
break;
put(w, f.sep);
}
else
{
val.popFront();
if (val.empty)
break;
put(w, fmt.trailing);
}
}
}
else
throw new Exception(text("Incorrect format specifier for range: %", f.spec));
}
// character formatting with ecaping
private void formatChar(Writer)(Writer w, in dchar c, in char quote)
{
if (std.uni.isGraphical(c))
{
if (c == quote || c == '\\')
put(w, '\\'), put(w, c);
else
put(w, c);
}
else if (c <= 0xFF)
{
put(w, '\\');
switch (c)
{
case '\a': put(w, 'a'); break;
case '\b': put(w, 'b'); break;
case '\f': put(w, 'f'); break;
case '\n': put(w, 'n'); break;
case '\r': put(w, 'r'); break;
case '\t': put(w, 't'); break;
case '\v': put(w, 'v'); break;
default:
formattedWrite(w, "x%02X", cast(uint)c);
}
}
else if (c <= 0xFFFF)
formattedWrite(w, "\\u%04X", cast(uint)c);
else
formattedWrite(w, "\\U%08X", cast(uint)c);
}
// undocumented
// string elements are formatted like UTF-8 string literals.
void formatElement(Writer, T, Char)(Writer w, T val, ref FormatSpec!Char f)
if (is(StringTypeOf!T) && !is(T == enum))
{
StringTypeOf!T str = val; // bug 8015
if (f.spec == 's')
{
try
{
// ignore other specifications and quote
auto app = appender!(typeof(val[0])[])();
put(app, '\"');
for (size_t i = 0; i < str.length; )
{
auto c = std.utf.decode(str, i);
// \uFFFE and \uFFFF are considered valid by isValidDchar,
// so need checking for interchange.
if (c == 0xFFFE || c == 0xFFFF)
goto LinvalidSeq;
formatChar(app, c, '"');
}
put(app, '\"');
put(w, app.data);
return;
}
catch (UTFException)
{
}
// If val contains invalid UTF sequence, formatted like HexString literal
LinvalidSeq:
static if (is(typeof(str[0]) : const(char)))
{
enum postfix = 'c';
alias const(ubyte)[] IntArr;
}
else static if (is(typeof(str[0]) : const(wchar)))
{
enum postfix = 'w';
alias const(ushort)[] IntArr;
}
else static if (is(typeof(str[0]) : const(dchar)))
{
enum postfix = 'd';
alias const(uint)[] IntArr;
}
formattedWrite(w, "x\"%(%02X %)\"%s", cast(IntArr)str, postfix);
}
else
formatValue(w, str, f);
}
unittest
{
// Test for bug 8015
import std.typecons;
struct MyStruct {
string str;
@property string toStr() {
return str;
}
alias toStr this;
}
Tuple!(MyStruct) t;
}
// undocumented
// character elements are formatted like UTF-8 character literals.
void formatElement(Writer, T, Char)(Writer w, T val, ref FormatSpec!Char f)
if (is(CharTypeOf!T) && !is(T == enum))
{
if (f.spec == 's')
{
put(w, '\'');
formatChar(w, val, '\'');
put(w, '\'');
}
else
formatValue(w, val, f);
}
// undocumented
// Maybe T is noncopyable struct, so receive it by 'auto ref'.
void formatElement(Writer, T, Char)(Writer w, auto ref T val, ref FormatSpec!Char f)
if (!is(StringTypeOf!T) && !is(CharTypeOf!T) || is(T == enum))
{
formatValue(w, val, f);
}
/**
Associative arrays are formatted by using $(D ':') and $(D ', ') as
separators, and enclosed by $(D '[') and $(D ']').
*/
void formatValue(Writer, T, Char)(Writer w, T obj, ref FormatSpec!Char f)
if (is(AssocArrayTypeOf!T) && !is(T == enum) && !hasToString!(T, Char))
{
AssocArrayTypeOf!T val = obj;
enforceEx!FormatException(
f.spec == 's' || f.spec == '(',
"associative");
enum const(Char)[] defSpec = "%s" ~ f.keySeparator ~ "%s" ~ f.seqSeparator;
auto fmtSpec = f.spec == '(' ? f.nested : defSpec;
size_t i = 0, end = val.length;
if (f.spec == 's')
put(w, f.seqBefore);
foreach (k, ref v; val)
{
auto fmt = FormatSpec!Char(fmtSpec);
fmt.writeUpToNextSpec(w);
if (f.flDash)
{
formatValue(w, k, fmt);
fmt.writeUpToNextSpec(w);
formatValue(w, v, fmt);
}
else
{
formatElement(w, k, fmt);
fmt.writeUpToNextSpec(w);
formatElement(w, v, fmt);
}
if (f.sep)
{
fmt.writeUpToNextSpec(w);
if (++i != end)
put(w, f.sep);
}
else
{
if (++i != end)
fmt.writeUpToNextSpec(w);
}
}
if (f.spec == 's')
put(w, f.seqAfter);
}
unittest
{
int[string] aa0;
formatTest( aa0, `[]` );
// elements escaping
formatTest( ["aaa":1, "bbb":2, "ccc":3],
`["aaa":1, "bbb":2, "ccc":3]` );
formatTest( ['c':"str"],
`['c':"str"]` );
formatTest( ['"':"\"", '\'':"'"],
`['"':"\"", '\'':"'"]` );
// range formatting for AA
auto aa3 = [1:"hello", 2:"world"];
// escape
formatTest( "{%(%s:%s $ %)}", aa3,
`{1:"hello" $ 2:"world"}`);
// use range formatting for key and value, and use %|
formatTest( "{%([%04d->%(%c.%)]%| $ %)}", aa3,
`{[0001->h.e.l.l.o] $ [0002->w.o.r.l.d]}` );
}
unittest
{
class C1 { int[char] val; alias val this; this(int[char] v){ val = v; } }
class C2 { int[char] val; alias val this; this(int[char] v){ val = v; }
override string toString() const { return "C"; } }
formatTest( new C1(['c':1, 'd':2]), `['c':1, 'd':2]` );
formatTest( new C2(['c':1, 'd':2]), "C" );
struct S1 { int[char] val; alias val this; }
struct S2 { int[char] val; alias val this;
string toString() const { return "S"; } }
formatTest( S1(['c':1, 'd':2]), `['c':1, 'd':2]` );
formatTest( S2(['c':1, 'd':2]), "S" );
}
template hasToString(T, Char)
{
static if(isPointer!T && !isAggregateType!T)
{
// X* does not have toString, even if X is aggregate type has toString.
enum hasToString = 0;
}
else static if (is(typeof({ T val = void; FormatSpec!Char f; val.toString((const(char)[] s){}, f); })))
{
enum hasToString = 4;
}
else static if (is(typeof({ T val = void; val.toString((const(char)[] s){}, "%s"); })))
{
enum hasToString = 3;
}
else static if (is(typeof({ T val = void; val.toString((const(char)[] s){}); })))
{
enum hasToString = 2;
}
else static if (is(typeof({ T val = void; return val.toString(); }()) S) && isSomeString!S)
{
enum hasToString = 1;
}
else
{
enum hasToString = 0;
}
}
// object formatting with toString
private void formatObject(Writer, T, Char)(ref Writer w, ref T val, ref FormatSpec!Char f)
if (hasToString!(T, Char))
{
static if (is(typeof(val.toString((const(char)[] s){}, f))))
{
val.toString((const(char)[] s) { put(w, s); }, f);
}
else static if (is(typeof(val.toString((const(char)[] s){}, "%s"))))
{
val.toString((const(char)[] s) { put(w, s); }, f.getCurFmtStr());
}
else static if (is(typeof(val.toString((const(char)[] s){}))))
{
val.toString((const(char)[] s) { put(w, s); });
}
else static if (is(typeof(val.toString()) S) && isSomeString!S)
{
put(w, val.toString());
}
else
static assert(0);
}
void enforceValidFormatSpec(T, Char)(ref FormatSpec!Char f)
{
static if (!isInputRange!T && hasToString!(T, Char) != 4)
{
enforceEx!FormatException(f.spec == 's',
format("Expected '%%s' format specifier for type '%s'", T.stringof));
}
}
unittest
{
static interface IF1 { }
class CIF1 : IF1 { }
static struct SF1 { }
static union UF1 { }
static class CF1 { }
static interface IF2 { string toString(); }
static class CIF2 : IF2 { override string toString() { return ""; } }
static struct SF2 { string toString() { return ""; } }
static union UF2 { string toString() { return ""; } }
static class CF2 { override string toString() { return ""; } }
static interface IK1 { void toString(scope void delegate(const(char)[]) sink,
FormatSpec!char) const; }
static class CIK1 : IK1 { override void toString(scope void delegate(const(char)[]) sink,
FormatSpec!char) const { sink("CIK1"); } }
static struct KS1 { void toString(scope void delegate(const(char)[]) sink,
FormatSpec!char) const { sink("KS1"); } }
static union KU1 { void toString(scope void delegate(const(char)[]) sink,
FormatSpec!char) const { sink("KU1"); } }
static class KC1 { void toString(scope void delegate(const(char)[]) sink,
FormatSpec!char) const { sink("KC1"); } }
IF1 cif1 = new CIF1;
assertThrown!FormatException(format("%f", cif1));
assertThrown!FormatException(format("%f", SF1()));
assertThrown!FormatException(format("%f", UF1()));
assertThrown!FormatException(format("%f", new CF1()));
IF2 cif2 = new CIF2;
assertThrown!FormatException(format("%f", cif2));
assertThrown!FormatException(format("%f", SF2()));
assertThrown!FormatException(format("%f", UF2()));
assertThrown!FormatException(format("%f", new CF2()));
IK1 cik1 = new CIK1;
assert(format("%f", cik1) == "CIK1");
assert(format("%f", KS1()) == "KS1");
assert(format("%f", KU1()) == "KU1");
assert(format("%f", new KC1()) == "KC1");
}
/**
Aggregates ($(D struct), $(D union), $(D class), and $(D interface)) are
basically formatted by calling $(D toString).
$(D toString) should have one of the following signatures:
---
const void toString(scope void delegate(const(char)[]) sink, FormatSpec fmt);
const void toString(scope void delegate(const(char)[]) sink, string fmt);
const void toString(scope void delegate(const(char)[]) sink);
const string toString();
---
For the class objects which have input range interface,
$(UL $(LI If the instance $(D toString) has overridden
$(D Object.toString), it is used.)
$(LI Otherwise, the objects are formatted as input range.))
For the struct and union objects which does not have $(D toString),
$(UL $(LI If they have range interface, formatted as input range.)
$(LI Otherwise, they are formatted like $(D Type(field1, filed2, ...)).))
Otherwise, are formatted just as their type name.
*/
void formatValue(Writer, T, Char)(Writer w, T val, ref FormatSpec!Char f)
if (is(T == class) && !is(T == enum))
{
enforceValidFormatSpec!(T, Char)(f);
// TODO: Change this once toString() works for shared objects.
static assert(!is(T == shared), "unable to format shared objects");
if (val is null)
put(w, "null");
else
{
static if (hasToString!(T, Char) > 1 || (!isInputRange!T && !is(BuiltinTypeOf!T)))
{
formatObject!(Writer, T, Char)(w, val, f);
}
else
{
//string delegate() dg = &val.toString;
Object o = val; // workaround
string delegate() dg = &o.toString;
if (dg.funcptr != &Object.toString) // toString is overridden
{
formatObject(w, val, f);
}
else static if (isInputRange!T)
{
formatRange(w, val, f);
}
else static if (is(BuiltinTypeOf!T X))
{
X x = val;
formatValue(w, x, f);
}
else
{
formatObject(w, val, f);
}
}
}
}
unittest
{
// class range (issue 5154)
auto c = inputRangeObject([1,2,3,4]);
formatTest( c, "[1, 2, 3, 4]" );
assert(c.empty);
c = null;
formatTest( c, "null" );
}
unittest
{
// 5354
// If the class has both range I/F and custom toString, the use of custom
// toString routine is prioritized.
// Enable the use of custom toString that gets a sink delegate
// for class formatting.
enum inputRangeCode =
q{
int[] arr;
this(int[] a){ arr = a; }
@property int front() const { return arr[0]; }
@property bool empty() const { return arr.length == 0; }
void popFront(){ arr = arr[1..$]; }
};
class C1
{
mixin(inputRangeCode);
void toString(scope void delegate(const(char)[]) dg, ref FormatSpec!char f) const { dg("[012]"); }
}
class C2
{
mixin(inputRangeCode);
void toString(scope void delegate(const(char)[]) dg, string f) const { dg("[012]"); }
}
class C3
{
mixin(inputRangeCode);
void toString(scope void delegate(const(char)[]) dg) const { dg("[012]"); }
}
class C4
{
mixin(inputRangeCode);
override string toString() const { return "[012]"; }
}
class C5
{
mixin(inputRangeCode);
}
formatTest( new C1([0, 1, 2]), "[012]" );
formatTest( new C2([0, 1, 2]), "[012]" );
formatTest( new C3([0, 1, 2]), "[012]" );
formatTest( new C4([0, 1, 2]), "[012]" );
formatTest( new C5([0, 1, 2]), "[0, 1, 2]" );
}
/// ditto
void formatValue(Writer, T, Char)(Writer w, T val, ref FormatSpec!Char f)
if (is(T == interface) && (hasToString!(T, Char) || !is(BuiltinTypeOf!T)) && !is(T == enum))
{
enforceValidFormatSpec!(T, Char)(f);
if (val is null)
put(w, "null");
else
{
static if (hasToString!(T, Char))
{
formatObject(w, val, f);
}
else static if (isInputRange!T)
{
formatRange(w, val, f);
}
else
{
formatValue(w, cast(Object)val, f);
}
}
}
unittest
{
// interface
InputRange!int i = inputRangeObject([1,2,3,4]);
formatTest( i, "[1, 2, 3, 4]" );
assert(i.empty);
i = null;
formatTest( i, "null" );
// interface (downcast to Object)
interface Whatever {}
class C : Whatever
{
override @property string toString() const { return "ab"; }
}
Whatever val = new C;
formatTest( val, "ab" );
}
/// ditto
// Maybe T is noncopyable struct, so receive it by 'auto ref'.
void formatValue(Writer, T, Char)(Writer w, auto ref T val, ref FormatSpec!Char f)
if ((is(T == struct) || is(T == union)) && (hasToString!(T, Char) || !is(BuiltinTypeOf!T)) && !is(T == enum))
{
enforceValidFormatSpec!(T, Char)(f);
static if (hasToString!(T, Char))
{
formatObject(w, val, f);
}
else static if (isInputRange!T)
{
formatRange(w, val, f);
}
else static if (is(T == struct))
{
enum left = T.stringof~"(";
enum separator = ", ";
enum right = ")";
put(w, left);
foreach (i, e; val.tupleof)
{
static if (0 < i && val.tupleof[i-1].offsetof == val.tupleof[i].offsetof)
{
static if (i == val.tupleof.length - 1 || val.tupleof[i].offsetof != val.tupleof[i+1].offsetof)
put(w, separator~val.tupleof[i].stringof[4..$]~"}");
else
put(w, separator~val.tupleof[i].stringof[4..$]);
}
else
{
static if (i+1 < val.tupleof.length && val.tupleof[i].offsetof == val.tupleof[i+1].offsetof)
put(w, (i > 0 ? separator : "")~"#{overlap "~val.tupleof[i].stringof[4..$]);
else
{
static if (i > 0)
put(w, separator);
formatElement(w, e, f);
}
}
}
put(w, right);
}
else
{
put(w, T.stringof);
}
}
unittest
{
// bug 4638
struct U8 { string toString() const { return "blah"; } }
struct U16 { wstring toString() const { return "blah"; } }
struct U32 { dstring toString() const { return "blah"; } }
formatTest( U8(), "blah" );
formatTest( U16(), "blah" );
formatTest( U32(), "blah" );
}
unittest
{
// 3890
struct Int{ int n; }
struct Pair{ string s; Int i; }
formatTest( Pair("hello", Int(5)),
`Pair("hello", Int(5))` );
}
unittest
{
// union formatting without toString
union U1
{
int n;
string s;
}
U1 u1;
formatTest( u1, "U1" );
// union formatting with toString
union U2
{
int n;
string s;
string toString() const { return s; }
}
U2 u2;
u2.s = "hello";
formatTest( u2, "hello" );
}
unittest
{
// 7230
static struct Bug7230
{
string s = "hello";
union {
string a;
int b;
double c;
}
long x = 10;
}
Bug7230 bug;
bug.b = 123;
FormatSpec!char f;
auto w = appender!(char[])();
formatValue(w, bug, f);
assert(w.data == `Bug7230("hello", #{overlap a, b, c}, 10)`);
}
unittest
{
static struct S{ @disable this(this); }
S s;
FormatSpec!char f;
auto w = appender!string();
formatValue(w, s, f);
assert(w.data == "S()");
}
/**
$(D enum) is formatted like its base value.
*/
void formatValue(Writer, T, Char)(Writer w, T val, ref FormatSpec!Char f)
if (is(T == enum))
{
if (f.spec == 's')
{
foreach (i, e; EnumMembers!T)
{
if (val == e)
{
formatValue(w, __traits(allMembers, T)[i], f);
return;
}
}
// val is not a member of T, output cast(T)rawValue instead.
put(w, "cast(" ~ T.stringof ~ ")");
static assert(!is(OriginalType!T == T));
}
formatValue(w, cast(OriginalType!T)val, f);
}
unittest
{
enum A { first, second, third }
formatTest( A.second, "second" );
formatTest( cast(A)72, "cast(A)72" );
}
unittest
{
enum A : string { one = "uno", two = "dos", three = "tres" }
formatTest( A.three, "three" );
formatTest( cast(A)"mill\ón", "cast(A)mill\ón" );
}
unittest
{
enum A : bool { no, yes }
formatTest( A.yes, "yes" );
formatTest( A.no, "no" );
}
unittest
{
// Test for bug 6892
enum Foo { A = 10 }
formatTest("%s", Foo.A, "A");
formatTest(">%4s<", Foo.A, "> A<");
formatTest("%04d", Foo.A, "0010");
formatTest("%+2u", Foo.A, "+10");
formatTest("%02x", Foo.A, "0a");
formatTest("%3o", Foo.A, " 12");
formatTest("%b", Foo.A, "1010");
}
/**
Pointers are formatted as hex integers.
*/
void formatValue(Writer, T, Char)(Writer w, T val, ref FormatSpec!Char f)
if (isPointer!T && !is(T == enum) && !hasToString!(T, Char))
{
if (val is null)
put(w, "null");
else
{
static if (isInputRange!T)
{
formatRange(w, *val, f);
}
else
{
const void * p = val;
if (f.spec == 's')
{
FormatSpec!Char fs = f; // fs is copy for change its values.
fs.spec = 'X';
formatValue(w, cast(ulong) p, fs);
}
else
{
enforceEx!FormatException(f.spec == 'X' || f.spec == 'x',
"Expected one of %s, %x or %X for pointer type.");
formatValue(w, cast(ulong) p, f);
}
}
}
}
unittest
{
// pointer
auto r = retro([1,2,3,4]);
auto p = &r;
formatTest( p, "[4, 3, 2, 1]" );
assert(p.empty);
p = null;
formatTest( p, "null" );
auto q = cast(void*)0xFFEECCAA;
formatTest( q, "FFEECCAA" );
}
unittest
{
// Test for issue 7869
struct S
{
string toString() const { return ""; }
}
S* p = null;
formatTest( p, "null" );
S* q = cast(S*)0xFFEECCAA;
formatTest( q, "FFEECCAA" );
}
unittest
{
// Test for issue 8186
class B
{
int*a;
this(){ a = new int; }
alias a this;
}
formatTest( B.init, "null" );
}
/**
Delegates are formatted by 'Attributes ReturnType delegate(Parameters)'
*/
void formatValue(Writer, T, Char)(Writer w, T val, ref FormatSpec!Char f)
if (is(T == delegate) && !is(T == enum) && !hasToString!(T, Char))
{
alias FunctionAttribute FA;
if (functionAttributes!T & FA.pure_) formatValue(w, "pure ", f);
if (functionAttributes!T & FA.nothrow_) formatValue(w, "nothrow ", f);
if (functionAttributes!T & FA.ref_) formatValue(w, "ref ", f);
if (functionAttributes!T & FA.property) formatValue(w, "@property ", f);
if (functionAttributes!T & FA.trusted) formatValue(w, "@trusted ", f);
if (functionAttributes!T & FA.safe) formatValue(w, "@safe ", f);
formatValue(w, ReturnType!(T).stringof,f);
formatValue(w, " delegate",f);
formatValue(w, ParameterTypeTuple!(T).stringof,f);
}
unittest
{
void func() {}
formatTest( &func, "void delegate()" );
}
/*
Formatting a $(D typedef) is deprecated but still kept around for a while.
*/
void formatValue(Writer, T, Char)(Writer w, T val, ref FormatSpec!Char f)
if (is(T == typedef))
{
static if (is(T U == typedef))
{
formatValue(w, cast(U) val, f);
}
}
/*
Formats an object of type 'D' according to 'f' and writes it to
'w'. The pointer 'arg' is assumed to point to an object of type
'D'. The untyped signature is for the sake of taking this function's
address.
*/
private void formatGeneric(Writer, D, Char)(Writer w, const(void)* arg, ref FormatSpec!Char f)
{
formatValue(w, *cast(D*) arg, f);
}
private void formatNth(Writer, Char, A...)(Writer w, ref FormatSpec!Char f, size_t index, A args)
{
static string gencode(size_t count)()
{
string result;
foreach (n; 0 .. count)
{
auto num = to!string(n);
result ~=
"case "~num~":"~
" formatValue(w, args["~num~"], f);"~
" break;";
}
return result;
}
switch (index)
{
mixin(gencode!(A.length)());
default:
assert(0, "n = "~cast(char)(index + '0'));
}
}
unittest
{
int[] a = [ 1, 3, 2 ];
formatTest( "testing %(%s & %) embedded", a,
"testing 1 & 3 & 2 embedded");
formatTest( "testing %((%s) %)) wyda3", a,
"testing (1) (3) (2) wyda3" );
int[0] empt = [];
formatTest( "(%s)", empt,
"([])" );
}
//------------------------------------------------------------------------------
// Fix for issue 1591
private int getNthInt(A...)(uint index, A args)
{
static if (A.length)
{
if (index)
{
return getNthInt(index - 1, args[1 .. $]);
}
static if (isIntegral!(typeof(args[0])))
{
return to!int(args[0]);
}
else
{
throw new FormatException("int expected");
}
}
else
{
throw new FormatException("int expected");
}
}
/* ======================== Unit Tests ====================================== */
version(unittest)
void formatTest(T)(T val, string expected, size_t ln = __LINE__, string fn = __FILE__)
{
FormatSpec!char f;
auto w = appender!string();
formatValue(w, val, f);
enforceEx!AssertError(
w.data == expected,
text("expected = `", expected, "`, result = `", w.data, "`"), fn, ln);
}
version(unittest)
void formatTest(T)(string fmt, T val, string expected, size_t ln = __LINE__, string fn = __FILE__)
{
auto w = appender!string();
formattedWrite(w, fmt, val);
enforceEx!AssertError(
w.data == expected,
text("expected = `", expected, "`, result = `", w.data, "`"), fn, ln);
}
unittest
{
auto stream = appender!string();
formattedWrite(stream, "%s", 1.1);
assert(stream.data == "1.1", stream.data);
stream = appender!string();
formattedWrite(stream, "%s", map!"a*a"([2, 3, 5]));
assert(stream.data == "[4, 9, 25]", stream.data);
// Test shared data.
stream = appender!string();
shared int s = 6;
formattedWrite(stream, "%s", s);
assert(stream.data == "6");
}
unittest
{
auto stream = appender!string();
formattedWrite(stream, "%u", 42);
assert(stream.data == "42", stream.data);
}
unittest
{
// testing raw writes
auto w = appender!(char[])();
uint a = 0x02030405;
formattedWrite(w, "%+r", a);
assert(w.data.length == 4 && w.data[0] == 2 && w.data[1] == 3
&& w.data[2] == 4 && w.data[3] == 5);
w.clear();
formattedWrite(w, "%-r", a);
assert(w.data.length == 4 && w.data[0] == 5 && w.data[1] == 4
&& w.data[2] == 3 && w.data[3] == 2);
}
unittest
{
// testing positional parameters
auto w = appender!(char[])();
formattedWrite(w,
"Numbers %2$s and %1$s are reversed and %1$s%2$s repeated",
42, 0);
assert(w.data == "Numbers 0 and 42 are reversed and 420 repeated",
w.data);
w.clear();
formattedWrite(w, "asd%s", 23);
assert(w.data == "asd23", w.data);
w.clear();
formattedWrite(w, "%s%s", 23, 45);
assert(w.data == "2345", w.data);
}
unittest
{
debug(format) printf("std.format.format.unittest\n");
auto stream = appender!(char[])();
//goto here;
formattedWrite(stream,
"hello world! %s %s ", true, 57, 1_000_000_000, 'x', " foo");
assert(stream.data == "hello world! true 57 ",
stream.data);
stream.clear();
formattedWrite(stream, "%g %A %s", 1.67, -1.28, float.nan);
// std.c.stdio.fwrite(stream.data.ptr, stream.data.length, 1, stderr);
/* The host C library is used to format floats. C99 doesn't
* specify what the hex digit before the decimal point is for
* %A. */
version (linux)
{
assert(stream.data == "1.67 -0X1.47AE147AE147BP+0 nan",
stream.data);
}
else version (OSX)
{
assert(stream.data == "1.67 -0X1.47AE147AE147BP+0 nan",
stream.data);
}
else
{
assert(stream.data == "1.67 -0X1.47AE147AE147BP+0 nan",
stream.data);
}
stream.clear();
formattedWrite(stream, "%x %X", 0x1234AF, 0xAFAFAFAF);
assert(stream.data == "1234af AFAFAFAF");
stream.clear();
formattedWrite(stream, "%b %o", 0x1234AF, 0xAFAFAFAF);
assert(stream.data == "100100011010010101111 25753727657");
stream.clear();
formattedWrite(stream, "%d %s", 0x1234AF, 0xAFAFAFAF);
assert(stream.data == "1193135 2947526575");
stream.clear();
// formattedWrite(stream, "%s", 1.2 + 3.4i);
// assert(stream.data == "1.2+3.4i");
// stream.clear();
formattedWrite(stream, "%a %A", 1.32, 6.78f);
//formattedWrite(stream, "%x %X", 1.32);
assert(stream.data == "0x1.51eb851eb851fp+0 0X1.B1EB86P+2");
stream.clear();
formattedWrite(stream, "%#06.*f",2,12.345);
assert(stream.data == "012.35");
stream.clear();
formattedWrite(stream, "%#0*.*f",6,2,12.345);
assert(stream.data == "012.35");
stream.clear();
const real constreal = 1;
formattedWrite(stream, "%g",constreal);
assert(stream.data == "1");
stream.clear();
formattedWrite(stream, "%7.4g:", 12.678);
assert(stream.data == " 12.68:");
stream.clear();
formattedWrite(stream, "%7.4g:", 12.678L);
assert(stream.data == " 12.68:");
stream.clear();
formattedWrite(stream, "%04f|%05d|%#05x|%#5x",-4.0,-10,1,1);
assert(stream.data == "-4.000000|-0010|0x001| 0x1",
stream.data);
stream.clear();
int i;
string s;
i = -10;
formattedWrite(stream, "%d|%3d|%03d|%1d|%01.4f",i,i,i,i,cast(double) i);
assert(stream.data == "-10|-10|-10|-10|-10.0000");
stream.clear();
i = -5;
formattedWrite(stream, "%d|%3d|%03d|%1d|%01.4f",i,i,i,i,cast(double) i);
assert(stream.data == "-5| -5|-05|-5|-5.0000");
stream.clear();
i = 0;
formattedWrite(stream, "%d|%3d|%03d|%1d|%01.4f",i,i,i,i,cast(double) i);
assert(stream.data == "0| 0|000|0|0.0000");
stream.clear();
i = 5;
formattedWrite(stream, "%d|%3d|%03d|%1d|%01.4f",i,i,i,i,cast(double) i);
assert(stream.data == "5| 5|005|5|5.0000");
stream.clear();
i = 10;
formattedWrite(stream, "%d|%3d|%03d|%1d|%01.4f",i,i,i,i,cast(double) i);
assert(stream.data == "10| 10|010|10|10.0000");
stream.clear();
formattedWrite(stream, "%.0d", 0);
assert(stream.data == "");
stream.clear();
formattedWrite(stream, "%.g", .34);
assert(stream.data == "0.3");
stream.clear();
stream.clear(); formattedWrite(stream, "%.0g", .34);
assert(stream.data == "0.3");
stream.clear(); formattedWrite(stream, "%.2g", .34);
assert(stream.data == "0.34");
stream.clear(); formattedWrite(stream, "%0.0008f", 1e-08);
assert(stream.data == "0.00000001");
stream.clear(); formattedWrite(stream, "%0.0008f", 1e-05);
assert(stream.data == "0.00001000");
//return;
//std.c.stdio.fwrite(stream.data.ptr, stream.data.length, 1, stderr);
s = "helloworld";
string r;
stream.clear(); formattedWrite(stream, "%.2s", s[0..5]);
assert(stream.data == "he");
stream.clear(); formattedWrite(stream, "%.20s", s[0..5]);
assert(stream.data == "hello");
stream.clear(); formattedWrite(stream, "%8s", s[0..5]);
assert(stream.data == " hello");
byte[] arrbyte = new byte[4];
arrbyte[0] = 100;
arrbyte[1] = -99;
arrbyte[3] = 0;
stream.clear(); formattedWrite(stream, "%s", arrbyte);
assert(stream.data == "[100, -99, 0, 0]", stream.data);
ubyte[] arrubyte = new ubyte[4];
arrubyte[0] = 100;
arrubyte[1] = 200;
arrubyte[3] = 0;
stream.clear(); formattedWrite(stream, "%s", arrubyte);
assert(stream.data == "[100, 200, 0, 0]", stream.data);
short[] arrshort = new short[4];
arrshort[0] = 100;
arrshort[1] = -999;
arrshort[3] = 0;
stream.clear(); formattedWrite(stream, "%s", arrshort);
assert(stream.data == "[100, -999, 0, 0]");
stream.clear(); formattedWrite(stream, "%s",arrshort);
assert(stream.data == "[100, -999, 0, 0]");
ushort[] arrushort = new ushort[4];
arrushort[0] = 100;
arrushort[1] = 20_000;
arrushort[3] = 0;
stream.clear(); formattedWrite(stream, "%s", arrushort);
assert(stream.data == "[100, 20000, 0, 0]");
int[] arrint = new int[4];
arrint[0] = 100;
arrint[1] = -999;
arrint[3] = 0;
stream.clear(); formattedWrite(stream, "%s", arrint);
assert(stream.data == "[100, -999, 0, 0]");
stream.clear(); formattedWrite(stream, "%s",arrint);
assert(stream.data == "[100, -999, 0, 0]");
long[] arrlong = new long[4];
arrlong[0] = 100;
arrlong[1] = -999;
arrlong[3] = 0;
stream.clear(); formattedWrite(stream, "%s", arrlong);
assert(stream.data == "[100, -999, 0, 0]");
stream.clear(); formattedWrite(stream, "%s",arrlong);
assert(stream.data == "[100, -999, 0, 0]");
ulong[] arrulong = new ulong[4];
arrulong[0] = 100;
arrulong[1] = 999;
arrulong[3] = 0;
stream.clear(); formattedWrite(stream, "%s", arrulong);
assert(stream.data == "[100, 999, 0, 0]");
string[] arr2 = new string[4];
arr2[0] = "hello";
arr2[1] = "world";
arr2[3] = "foo";
stream.clear(); formattedWrite(stream, "%s", arr2);
assert(stream.data == `["hello", "world", "", "foo"]`, stream.data);
stream.clear(); formattedWrite(stream, "%.8d", 7);
assert(stream.data == "00000007");
stream.clear(); formattedWrite(stream, "%.8x", 10);
assert(stream.data == "0000000a");
stream.clear(); formattedWrite(stream, "%-3d", 7);
assert(stream.data == "7 ");
stream.clear(); formattedWrite(stream, "%*d", -3, 7);
assert(stream.data == "7 ");
stream.clear(); formattedWrite(stream, "%.*d", -3, 7);
//writeln(stream.data);
assert(stream.data == "7");
// assert(false);
// typedef int myint;
// myint m = -7;
// stream.clear(); formattedWrite(stream, "", m);
// assert(stream.data == "-7");
stream.clear(); formattedWrite(stream, "%s", "abc"c);
assert(stream.data == "abc");
stream.clear(); formattedWrite(stream, "%s", "def"w);
assert(stream.data == "def", text(stream.data.length));
stream.clear(); formattedWrite(stream, "%s", "ghi"d);
assert(stream.data == "ghi");
here:
void* p = cast(void*)0xDEADBEEF;
stream.clear(); formattedWrite(stream, "%s", p);
assert(stream.data == "DEADBEEF", stream.data);
stream.clear(); formattedWrite(stream, "%#x", 0xabcd);
assert(stream.data == "0xabcd");
stream.clear(); formattedWrite(stream, "%#X", 0xABCD);
assert(stream.data == "0XABCD");
stream.clear(); formattedWrite(stream, "%#o", octal!12345);
assert(stream.data == "012345");
stream.clear(); formattedWrite(stream, "%o", 9);
assert(stream.data == "11");
stream.clear(); formattedWrite(stream, "%+d", 123);
assert(stream.data == "+123");
stream.clear(); formattedWrite(stream, "%+d", -123);
assert(stream.data == "-123");
stream.clear(); formattedWrite(stream, "% d", 123);
assert(stream.data == " 123");
stream.clear(); formattedWrite(stream, "% d", -123);
assert(stream.data == "-123");
stream.clear(); formattedWrite(stream, "%%");
assert(stream.data == "%");
stream.clear(); formattedWrite(stream, "%d", true);
assert(stream.data == "1");
stream.clear(); formattedWrite(stream, "%d", false);
assert(stream.data == "0");
stream.clear(); formattedWrite(stream, "%d", 'a');
assert(stream.data == "97", stream.data);
wchar wc = 'a';
stream.clear(); formattedWrite(stream, "%d", wc);
assert(stream.data == "97");
dchar dc = 'a';
stream.clear(); formattedWrite(stream, "%d", dc);
assert(stream.data == "97");
byte b = byte.max;
stream.clear(); formattedWrite(stream, "%x", b);
assert(stream.data == "7f");
stream.clear(); formattedWrite(stream, "%x", ++b);
assert(stream.data == "80");
stream.clear(); formattedWrite(stream, "%x", ++b);
assert(stream.data == "81");
short sh = short.max;
stream.clear(); formattedWrite(stream, "%x", sh);
assert(stream.data == "7fff");
stream.clear(); formattedWrite(stream, "%x", ++sh);
assert(stream.data == "8000");
stream.clear(); formattedWrite(stream, "%x", ++sh);
assert(stream.data == "8001");
i = int.max;
stream.clear(); formattedWrite(stream, "%x", i);
assert(stream.data == "7fffffff");
stream.clear(); formattedWrite(stream, "%x", ++i);
assert(stream.data == "80000000");
stream.clear(); formattedWrite(stream, "%x", ++i);
assert(stream.data == "80000001");
stream.clear(); formattedWrite(stream, "%x", 10);
assert(stream.data == "a");
stream.clear(); formattedWrite(stream, "%X", 10);
assert(stream.data == "A");
stream.clear(); formattedWrite(stream, "%x", 15);
assert(stream.data == "f");
stream.clear(); formattedWrite(stream, "%X", 15);
assert(stream.data == "F");
Object c = null;
stream.clear(); formattedWrite(stream, "%s", c);
assert(stream.data == "null");
enum TestEnum
{
Value1, Value2
}
stream.clear(); formattedWrite(stream, "%s", TestEnum.Value2);
assert(stream.data == "Value2", stream.data);
stream.clear(); formattedWrite(stream, "%s", cast(TestEnum)5);
assert(stream.data == "cast(TestEnum)5", stream.data);
//immutable(char[5])[int] aa = ([3:"hello", 4:"betty"]);
//stream.clear(); formattedWrite(stream, "%s", aa.values);
//std.c.stdio.fwrite(stream.data.ptr, stream.data.length, 1, stderr);
//assert(stream.data == "[[h,e,l,l,o],[b,e,t,t,y]]");
//stream.clear(); formattedWrite(stream, "%s", aa);
//assert(stream.data == "[3:[h,e,l,l,o],4:[b,e,t,t,y]]");
static const dchar[] ds = ['a','b'];
for (int j = 0; j < ds.length; ++j)
{
stream.clear(); formattedWrite(stream, " %d", ds[j]);
if (j == 0)
assert(stream.data == " 97");
else
assert(stream.data == " 98");
}
stream.clear(); formattedWrite(stream, "%.-3d", 7);
assert(stream.data == "7", ">" ~ stream.data ~ "<");
// systematic test
const string[] flags = [ "-", "+", "#", "0", " ", "" ];
const string[] widths = [ "", "0", "4", "20" ];
const string[] precs = [ "", ".", ".0", ".4", ".20" ];
const string formats = "sdoxXeEfFgGaA";
/+
foreach (flag1; flags)
foreach (flag2; flags)
foreach (flag3; flags)
foreach (flag4; flags)
foreach (flag5; flags)
foreach (width; widths)
foreach (prec; precs)
foreach (format; formats)
{
stream.clear();
auto fmt = "%" ~ flag1 ~ flag2 ~ flag3
~ flag4 ~ flag5 ~ width ~ prec ~ format
~ '\0';
fmt = fmt[0 .. $ - 1]; // keep it zero-term
char buf[256];
buf[0] = 0;
switch (format)
{
case 's':
formattedWrite(stream, fmt, "wyda");
snprintf(buf.ptr, buf.length, fmt.ptr,
"wyda\0".ptr);
break;
case 'd':
formattedWrite(stream, fmt, 456);
snprintf(buf.ptr, buf.length, fmt.ptr,
456);
break;
case 'o':
formattedWrite(stream, fmt, 345);
snprintf(buf.ptr, buf.length, fmt.ptr,
345);
break;
case 'x':
formattedWrite(stream, fmt, 63546);
snprintf(buf.ptr, buf.length, fmt.ptr,
63546);
break;
case 'X':
formattedWrite(stream, fmt, 12566);
snprintf(buf.ptr, buf.length, fmt.ptr,
12566);
break;
case 'e':
formattedWrite(stream, fmt, 3245.345234);
snprintf(buf.ptr, buf.length, fmt.ptr,
3245.345234);
break;
case 'E':
formattedWrite(stream, fmt, 3245.2345234);
snprintf(buf.ptr, buf.length, fmt.ptr,
3245.2345234);
break;
case 'f':
formattedWrite(stream, fmt, 3245234.645675);
snprintf(buf.ptr, buf.length, fmt.ptr,
3245234.645675);
break;
case 'F':
formattedWrite(stream, fmt, 213412.43);
snprintf(buf.ptr, buf.length, fmt.ptr,
213412.43);
break;
case 'g':
formattedWrite(stream, fmt, 234134.34);
snprintf(buf.ptr, buf.length, fmt.ptr,
234134.34);
break;
case 'G':
formattedWrite(stream, fmt, 23141234.4321);
snprintf(buf.ptr, buf.length, fmt.ptr,
23141234.4321);
break;
case 'a':
formattedWrite(stream, fmt, 21341234.2134123);
snprintf(buf.ptr, buf.length, fmt.ptr,
21341234.2134123);
break;
case 'A':
formattedWrite(stream, fmt, 1092384098.45234);
snprintf(buf.ptr, buf.length, fmt.ptr,
1092384098.45234);
break;
default:
break;
}
auto exp = buf[0 .. strlen(buf.ptr)];
if (stream.data != exp)
{
writeln("Format: \"", fmt, '"');
writeln("Expected: >", exp, "<");
writeln("Actual: >", stream.data,
"<");
assert(false);
}
}+/
}
unittest
{
immutable(char[5])[int] aa = ([3:"hello", 4:"betty"]);
if (false) writeln(aa.keys);
assert(aa[3] == "hello");
assert(aa[4] == "betty");
// if (false)
// {
// writeln(aa.values[0]);
// writeln(aa.values[1]);
// writefln("%s", typeid(typeof(aa.values)));
// writefln("%s", aa[3]);
// writefln("%s", aa[4]);
// writefln("%s", aa.values);
// //writefln("%s", aa);
// wstring a = "abcd";
// writefln(a);
// dstring b = "abcd";
// writefln(b);
// }
auto stream = appender!(char[])();
alias TypeTuple!(byte, ubyte, short, ushort, int, uint, long, ulong,
float, double, real) AllNumerics;
foreach (T; AllNumerics)
{
T value = 1;
stream.clear();
formattedWrite(stream, "%s", value);
assert(stream.data == "1");
}
//auto r = std.string.format("%s", aa.values);
stream.clear(); formattedWrite(stream, "%s", aa);
//assert(stream.data == "[3:[h,e,l,l,o],4:[b,e,t,t,y]]", stream.data);
// r = std.string.format("%s", aa);
// assert(r == "[3:[h,e,l,l,o],4:[b,e,t,t,y]]");
}
unittest
{
string s = "hello!124:34.5";
string a;
int b;
double c;
formattedRead(s, "%s!%s:%s", &a, &b, &c);
assert(a == "hello" && b == 124 && c == 34.5);
}
version(unittest)
void formatReflectTest(T)(ref T val, string fmt, string formatted, string fn = __FILE__, size_t ln = __LINE__)
{
auto w = appender!string();
formattedWrite(w, fmt, val);
auto input = w.data;
enforceEx!AssertError(
input == formatted,
input, fn, ln);
T val2;
formattedRead(input, fmt, &val2);
static if (isAssociativeArray!T)
if (__ctfe)
{
alias val aa1;
alias val2 aa2;
//assert(aa1 == aa2);
assert(aa1.length == aa2.length);
assert(aa1.keys == aa2.keys);
//assert(aa1.values == aa2.values);
assert(aa1.values.length == aa2.values.length);
foreach (i; 0 .. aa1.values.length)
assert(aa1.values[i] == aa2.values[i]);
//foreach (i, key; aa1.keys)
// assert(aa1.values[i] == aa1[key]);
//foreach (i, key; aa2.keys)
// assert(aa2.values[i] == aa2[key]);
return;
}
enforceEx!AssertError(
val == val2,
input, fn, ln);
}
version(unittest)
@property void checkCTFEable(alias dg)()
{
static assert({ dg(); return true; }());
dg();
}
unittest
{
void booleanTest()
{
auto b = true;
formatReflectTest(b, "%s", `true`);
formatReflectTest(b, "%b", `1`);
formatReflectTest(b, "%o", `1`);
formatReflectTest(b, "%d", `1`);
formatReflectTest(b, "%u", `1`);
formatReflectTest(b, "%x", `1`);
}
void integerTest()
{
auto n = 127;
formatReflectTest(n, "%s", `127`);
formatReflectTest(n, "%b", `1111111`);
formatReflectTest(n, "%o", `177`);
formatReflectTest(n, "%d", `127`);
formatReflectTest(n, "%u", `127`);
formatReflectTest(n, "%x", `7f`);
}
void floatingTest()
{
auto f = 3.14;
formatReflectTest(f, "%s", `3.14`);
formatReflectTest(f, "%e", `3.140000e+00`);
formatReflectTest(f, "%f", `3.140000`);
formatReflectTest(f, "%g", `3.14`);
}
void charTest()
{
auto c = 'a';
formatReflectTest(c, "%s", `a`);
formatReflectTest(c, "%c", `a`);
formatReflectTest(c, "%b", `1100001`);
formatReflectTest(c, "%o", `141`);
formatReflectTest(c, "%d", `97`);
formatReflectTest(c, "%u", `97`);
formatReflectTest(c, "%x", `61`);
}
void strTest()
{
auto s = "hello";
formatReflectTest(s, "%s", `hello`);
formatReflectTest(s, "%(%c,%)", `h,e,l,l,o`);
formatReflectTest(s, "%(%s,%)", `'h','e','l','l','o'`);
formatReflectTest(s, "[%(<%c>%| $ %)]", `[<h> $ <e> $ <l> $ <l> $ <o>]`);
}
void daTest()
{
auto a = [1,2,3,4];
formatReflectTest(a, "%s", `[1, 2, 3, 4]`);
formatReflectTest(a, "[%(%s; %)]", `[1; 2; 3; 4]`);
formatReflectTest(a, "[%(<%s>%| $ %)]", `[<1> $ <2> $ <3> $ <4>]`);
}
void saTest()
{
int[4] sa = [1,2,3,4];
formatReflectTest(sa, "%s", `[1, 2, 3, 4]`);
formatReflectTest(sa, "[%(%s; %)]", `[1; 2; 3; 4]`);
formatReflectTest(sa, "[%(<%s>%| $ %)]", `[<1> $ <2> $ <3> $ <4>]`);
}
void aaTest()
{
auto aa = [1:"hello", 2:"world"];
formatReflectTest(aa, "%s", `[1:"hello", 2:"world"]`);
formatReflectTest(aa, "[%(%s->%s, %)]", `[1->"hello", 2->"world"]`);
formatReflectTest(aa, "{%([%s=%(%c%)]%|; %)}", `{[1=hello]; [2=world]}`);
}
checkCTFEable!({
booleanTest();
integerTest();
if (!__ctfe) floatingTest(); // snprintf
charTest();
strTest();
daTest();
saTest();
aaTest();
return true;
});
}
//------------------------------------------------------------------------------
private void skipData(Range, Char)(ref Range input, ref FormatSpec!Char spec)
{
switch (spec.spec)
{
case 'c': input.popFront(); break;
case 'd':
if (input.front == '+' || input.front == '-') input.popFront();
goto case 'u';
case 'u':
while (!input.empty && isDigit(input.front)) input.popFront();
break;
default:
assert(false,
text("Format specifier not understood: %", spec.spec));
}
}
private template acceptedSpecs(T)
{
static if (isIntegral!T) enum acceptedSpecs = "bdosuxX";
else static if (isFloatingPoint!T) enum acceptedSpecs = "seEfgG";
else static if (isSomeChar!T) enum acceptedSpecs = "bcdosuxX"; // integral + 'c'
else enum acceptedSpecs = "";
}
/**
* Reads a boolean value and returns it.
*/
T unformatValue(T, Range, Char)(ref Range input, ref FormatSpec!Char spec)
if (isInputRange!Range && is(Unqual!T == bool))
{
if (spec.spec == 's')
{
return parse!T(input);
}
enforce(std.algorithm.find(acceptedSpecs!long, spec.spec).length,
text("Wrong unformat specifier '%", spec.spec , "' for ", T.stringof));
return unformatValue!long(input, spec) != 0;
}
unittest
{
string line;
bool f1;
line = "true";
formattedRead(line, "%s", &f1);
assert(f1);
line = "TrUE";
formattedRead(line, "%s", &f1);
assert(f1);
line = "false";
formattedRead(line, "%s", &f1);
assert(!f1);
line = "fALsE";
formattedRead(line, "%s", &f1);
assert(!f1);
line = "1";
formattedRead(line, "%d", &f1);
assert(f1);
line = "-1";
formattedRead(line, "%d", &f1);
assert(f1);
line = "0";
formattedRead(line, "%d", &f1);
assert(!f1);
line = "-0";
formattedRead(line, "%d", &f1);
assert(!f1);
}
/**
* Reads null literal and returns it.
*/
T unformatValue(T, Range, Char)(ref Range input, ref FormatSpec!Char spec)
if (isInputRange!Range && is(T == typeof(null)))
{
enforce(spec.spec == 's',
text("Wrong unformat specifier '%", spec.spec , "' for ", T.stringof));
return parse!T(input);
}
/**
Reads an integral value and returns it.
*/
T unformatValue(T, Range, Char)(ref Range input, ref FormatSpec!Char spec)
if (isInputRange!Range && isIntegral!T && !is(T == enum))
{
enforce(std.algorithm.find(acceptedSpecs!T, spec.spec).length,
text("Wrong unformat specifier '%", spec.spec , "' for ", T.stringof));
enforce(spec.width == 0); // TODO
uint base =
spec.spec == 'x' || spec.spec == 'X' ? 16 :
spec.spec == 'o' ? 8 :
spec.spec == 'b' ? 2 :
spec.spec == 's' || spec.spec == 'd' || spec.spec == 'u' ? 10 : 0;
assert(base != 0);
return parse!T(input, base);
}
/**
Reads a floating-point value and returns it.
*/
T unformatValue(T, Range, Char)(ref Range input, ref FormatSpec!Char spec)
if (isFloatingPoint!T && !is(T == enum))
{
if (spec.spec == 'r')
{
// raw read
//enforce(input.length >= T.sizeof);
enforce(isSomeString!Range || ElementType!(Range).sizeof == 1);
union X
{
ubyte[T.sizeof] raw;
T typed;
}
X x;
foreach (i; 0 .. T.sizeof)
{
static if (isSomeString!Range)
{
x.raw[i] = input[0];
input = input[1 .. $];
}
else
{
// TODO: recheck this
x.raw[i] = cast(ubyte) input.front;
input.popFront();
}
}
return x.typed;
}
enforce(std.algorithm.find(acceptedSpecs!T, spec.spec).length,
text("Wrong unformat specifier '%", spec.spec , "' for ", T.stringof));
return parse!T(input);
}
version(none)unittest
{
union A
{
char[float.sizeof] untyped;
float typed;
}
A a;
a.typed = 5.5;
char[] input = a.untyped[];
float witness;
formattedRead(input, "%r", &witness);
assert(witness == a.typed);
}
unittest
{
char[] line = "1 2".dup;
int a, b;
formattedRead(line, "%s %s", &a, &b);
assert(a == 1 && b == 2);
line = "10 2 3".dup;
formattedRead(line, "%d ", &a);
assert(a == 10);
assert(line == "2 3");
Tuple!(int, float) t;
line = "1 2.125".dup;
formattedRead(line, "%d %g", &t);
assert(t[0] == 1 && t[1] == 2.125);
line = "1 7643 2.125".dup;
formattedRead(line, "%s %*u %s", &t);
assert(t[0] == 1 && t[1] == 2.125);
}
/**
* Reads one character and returns it.
*/
T unformatValue(T, Range, Char)(ref Range input, ref FormatSpec!Char spec)
if (isInputRange!Range && isSomeChar!T && !is(T == enum))
{
if (spec.spec == 's' || spec.spec == 'c')
{
auto result = to!T(input.front);
input.popFront();
return result;
}
enforce(std.algorithm.find(acceptedSpecs!T, spec.spec).length,
text("Wrong unformat specifier '%", spec.spec , "' for ", T.stringof));
static if (T.sizeof == 1)
return unformatValue!ubyte(input, spec);
else static if (T.sizeof == 2)
return unformatValue!ushort(input, spec);
else static if (T.sizeof == 4)
return unformatValue!uint(input, spec);
else
static assert(0);
}
unittest
{
string line;
char c1, c2;
line = "abc";
formattedRead(line, "%s%c", &c1, &c2);
assert(c1 == 'a' && c2 == 'b');
assert(line == "c");
}
/**
Reads a string and returns it.
*/
T unformatValue(T, Range, Char)(ref Range input, ref FormatSpec!Char spec)
if (isInputRange!Range && isSomeString!T && !is(T == enum))
{
if (spec.spec == '(')
{
return unformatRange!T(input, spec);
}
enforce(spec.spec == 's',
text("Wrong unformat specifier '%", spec.spec , "' for ", T.stringof));
static if (isStaticArray!T)
{
T result;
auto app = result[];
}
else
auto app = appender!T();
if (spec.trailing.empty)
{
for (; !input.empty; input.popFront())
{
static if (isStaticArray!T)
if (app.empty)
break;
app.put(input.front);
}
}
else
{
auto end = spec.trailing.front;
for (; !input.empty && input.front != end; input.popFront())
{
static if (isStaticArray!T)
if (app.empty)
break;
app.put(input.front);
}
}
static if (isStaticArray!T)
{
enforce(app.empty, "need more input");
return result;
}
else
return app.data;
}
unittest
{
string line;
string s1, s2;
line = "hello, world";
formattedRead(line, "%s", &s1);
assert(s1 == "hello, world", s1);
line = "hello, world;yah";
formattedRead(line, "%s;%s", &s1, &s2);
assert(s1 == "hello, world", s1);
assert(s2 == "yah", s2);
line = `['h','e','l','l','o']`;
string s3;
formattedRead(line, "[%(%s,%)]", &s3);
assert(s3 == "hello");
line = `"hello"`;
string s4;
formattedRead(line, "\"%(%c%)\"", &s4);
assert(s4 == "hello");
}
/**
Reads an array (except for string types) and returns it.
*/
T unformatValue(T, Range, Char)(ref Range input, ref FormatSpec!Char spec)
if (isInputRange!Range && isArray!T && !isSomeString!T && !is(T == enum))
{
if (spec.spec == '(')
{
return unformatRange!T(input, spec);
}
enforce(spec.spec == 's',
text("Wrong unformat specifier '%", spec.spec , "' for ", T.stringof));
return parse!T(input);
}
unittest
{
string line;
line = "[1,2,3]";
int[] s1;
formattedRead(line, "%s", &s1);
assert(s1 == [1,2,3]);
}
unittest
{
string line;
line = "[1,2,3]";
int[] s1;
formattedRead(line, "[%(%s,%)]", &s1);
assert(s1 == [1,2,3]);
line = `["hello", "world"]`;
string[] s2;
formattedRead(line, "[%(%s, %)]", &s2);
assert(s2 == ["hello", "world"]);
line = "123 456";
int[] s3;
formattedRead(line, "%(%s %)", &s3);
assert(s3 == [123, 456]);
line = "h,e,l,l,o; w,o,r,l,d";
string[] s4;
formattedRead(line, "%(%(%c,%); %)", &s4);
assert(s4 == ["hello", "world"]);
}
unittest
{
string line;
int[4] sa1;
line = `[1,2,3,4]`;
formattedRead(line, "%s", &sa1);
assert(sa1 == [1,2,3,4]);
int[4] sa2;
line = `[1,2,3]`;
assertThrown(formattedRead(line, "%s", &sa2));
int[4] sa3;
line = `[1,2,3,4,5]`;
assertThrown(formattedRead(line, "%s", &sa3));
}
unittest
{
string input;
int[4] sa1;
input = `[1,2,3,4]`;
formattedRead(input, "[%(%s,%)]", &sa1);
assert(sa1 == [1,2,3,4]);
int[4] sa2;
input = `[1,2,3]`;
assertThrown(formattedRead(input, "[%(%s,%)]", &sa2));
}
unittest
{
// 7241
string input = "a";
auto spec = FormatSpec!char("%s");
spec.readUpToNextSpec(input);
auto result = unformatValue!(dchar[1])(input, spec);
assert(result[0] == 'a');
}
/**
* Reads an associative array and returns it.
*/
T unformatValue(T, Range, Char)(ref Range input, ref FormatSpec!Char spec)
if (isInputRange!Range && isAssociativeArray!T && !is(T == enum))
{
if (spec.spec == '(')
{
return unformatRange!T(input, spec);
}
enforce(spec.spec == 's',
text("Wrong unformat specifier '%", spec.spec , "' for ", T.stringof));
return parse!T(input);
}
unittest
{
string line;
string[int] aa1;
line = `[1:"hello", 2:"world"]`;
formattedRead(line, "%s", &aa1);
assert(aa1 == [1:"hello", 2:"world"]);
int[string] aa2;
line = `{"hello"=1; "world"=2}`;
formattedRead(line, "{%(%s=%s; %)}", &aa2);
assert(aa2 == ["hello":1, "world":2]);
int[string] aa3;
line = `{[hello=1]; [world=2]}`;
formattedRead(line, "{%([%(%c%)=%s]%|; %)}", &aa3);
assert(aa3 == ["hello":1, "world":2]);
}
//debug = unformatRange;
private T unformatRange(T, Range, Char)(ref Range input, ref FormatSpec!Char spec)
in
{
assert(spec.spec == '(');
}
body
{
debug (unformatRange) printf("unformatRange:\n");
T result;
static if (isStaticArray!T)
{
size_t i;
}
const(Char)[] cont = spec.trailing;
for (size_t j = 0; j < spec.trailing.length; ++j)
{
if (spec.trailing[j] == '%')
{
cont = spec.trailing[0 .. j];
break;
}
}
debug (unformatRange) printf("\t");
debug (unformatRange) if (!input.empty) printf("input.front = %c, ", input.front);
debug (unformatRange) printf("cont = %.*s\n", cont);
bool checkEnd()
{
return input.empty || !cont.empty && input.front == cont.front;
}
if (!checkEnd())
{
for (;;)
{
auto fmt = FormatSpec!Char(spec.nested);
fmt.readUpToNextSpec(input);
enforce(!input.empty);
debug (unformatRange) printf("\t) spec = %c, front = %c ", fmt.spec, input.front);
static if (isStaticArray!T)
{
result[i++] = unformatElement!(typeof(T.init[0]))(input, fmt);
}
else static if (isDynamicArray!T)
{
result ~= unformatElement!(ElementType!T)(input, fmt);
}
else static if (isAssociativeArray!T)
{
auto key = unformatElement!(typeof(T.keys[0]))(input, fmt);
fmt.readUpToNextSpec(input); // eat key separator
result[key] = unformatElement!(typeof(T.values[0]))(input, fmt);
}
debug (unformatRange) {
if (input.empty) printf("-> front = [empty] ");
else printf("-> front = %c ", input.front);
}
static if (isStaticArray!T)
{
debug (unformatRange) printf("i = %u < %u\n", i, T.length);
enforce(i <= T.length);
}
auto sep =
spec.sep ? fmt.readUpToNextSpec(input), spec.sep
: fmt.trailing;
debug (unformatRange) {
if (!sep.empty && !input.empty) printf("-> %c, sep = %.*s\n", input.front, sep);
else printf("\n");
}
if (checkEnd())
break;
if (!sep.empty && input.front == sep.front)
{
while (!sep.empty)
{
enforce(!input.empty);
enforce(input.front == sep.front);
input.popFront();
sep.popFront();
}
debug (unformatRange) printf("input.front = %c\n", input.front);
}
}
}
static if (isStaticArray!T)
{
enforce(i == T.length);
}
return result;
}
// Undocumented
T unformatElement(T, Range, Char)(ref Range input, ref FormatSpec!Char spec)
if (isInputRange!Range)
{
static if (isSomeString!T)
{
if (spec.spec == 's')
{
return parseElement!T(input);
}
}
else static if (isSomeChar!T)
{
if (spec.spec == 's')
{
return parseElement!T(input);
}
}
return unformatValue!T(input, spec);
}
// Legacy implementation
enum Mangle : char
{
Tvoid = 'v',
Tbool = 'b',
Tbyte = 'g',
Tubyte = 'h',
Tshort = 's',
Tushort = 't',
Tint = 'i',
Tuint = 'k',
Tlong = 'l',
Tulong = 'm',
Tfloat = 'f',
Tdouble = 'd',
Treal = 'e',
Tifloat = 'o',
Tidouble = 'p',
Tireal = 'j',
Tcfloat = 'q',
Tcdouble = 'r',
Tcreal = 'c',
Tchar = 'a',
Twchar = 'u',
Tdchar = 'w',
Tarray = 'A',
Tsarray = 'G',
Taarray = 'H',
Tpointer = 'P',
Tfunction = 'F',
Tident = 'I',
Tclass = 'C',
Tstruct = 'S',
Tenum = 'E',
Ttypedef = 'T',
Tdelegate = 'D',
Tconst = 'x',
Timmutable = 'y',
}
// return the TypeInfo for a primitive type and null otherwise. This
// is required since for arrays of ints we only have the mangled char
// to work from. If arrays always subclassed TypeInfo_Array this
// routine could go away.
private TypeInfo primitiveTypeInfo(Mangle m)
{
// BUG: should fix this in static this() to avoid double checked locking bug
__gshared TypeInfo[Mangle] dic;
if (!dic.length) {
dic = [
Mangle.Tvoid : typeid(void),
Mangle.Tbool : typeid(bool),
Mangle.Tbyte : typeid(byte),
Mangle.Tubyte : typeid(ubyte),
Mangle.Tshort : typeid(short),
Mangle.Tushort : typeid(ushort),
Mangle.Tint : typeid(int),
Mangle.Tuint : typeid(uint),
Mangle.Tlong : typeid(long),
Mangle.Tulong : typeid(ulong),
Mangle.Tfloat : typeid(float),
Mangle.Tdouble : typeid(double),
Mangle.Treal : typeid(real),
Mangle.Tifloat : typeid(ifloat),
Mangle.Tidouble : typeid(idouble),
Mangle.Tireal : typeid(ireal),
Mangle.Tcfloat : typeid(cfloat),
Mangle.Tcdouble : typeid(cdouble),
Mangle.Tcreal : typeid(creal),
Mangle.Tchar : typeid(char),
Mangle.Twchar : typeid(wchar),
Mangle.Tdchar : typeid(dchar)
];
}
auto p = m in dic;
return p ? *p : null;
}
// This stuff has been removed from the docs and is planned for deprecation.
/*
* Interprets variadic argument list pointed to by argptr whose types
* are given by arguments[], formats them according to embedded format
* strings in the variadic argument list, and sends the resulting
* characters to putc.
*
* The variadic arguments are consumed in order. Each is formatted
* into a sequence of chars, using the default format specification
* for its type, and the characters are sequentially passed to putc.
* If a $(D char[]), $(D wchar[]), or $(D dchar[]) argument is
* encountered, it is interpreted as a format string. As many
* arguments as specified in the format string are consumed and
* formatted according to the format specifications in that string and
* passed to putc. If there are too few remaining arguments, a
* $(D FormatException) is thrown. If there are more remaining arguments than
* needed by the format specification, the default processing of
* arguments resumes until they are all consumed.
*
* Params:
* putc = Output is sent do this delegate, character by character.
* arguments = Array of $(D TypeInfo)s, one for each argument to be formatted.
* argptr = Points to variadic argument list.
*
* Throws:
* Mismatched arguments and formats result in a $(D FormatException) being thrown.
*
* Format_String:
* <a name="format-string">$(I Format strings)</a>
* consist of characters interspersed with
* $(I format specifications). Characters are simply copied
* to the output (such as putc) after any necessary conversion
* to the corresponding UTF-8 sequence.
*
* A $(I format specification) starts with a '%' character,
* and has the following grammar:
<pre>
$(I FormatSpecification):
$(B '%%')
$(B '%') $(I Flags) $(I Width) $(I Precision) $(I FormatChar)
$(I Flags):
$(I empty)
$(B '-') $(I Flags)
$(B '+') $(I Flags)
$(B '#') $(I Flags)
$(B '0') $(I Flags)
$(B ' ') $(I Flags)
$(I Width):
$(I empty)
$(I Integer)
$(B '*')
$(I Precision):
$(I empty)
$(B '.')
$(B '.') $(I Integer)
$(B '.*')
$(I Integer):
$(I Digit)
$(I Digit) $(I Integer)
$(I Digit):
$(B '0')
$(B '1')
$(B '2')
$(B '3')
$(B '4')
$(B '5')
$(B '6')
$(B '7')
$(B '8')
$(B '9')
$(I FormatChar):
$(B 's')
$(B 'b')
$(B 'd')
$(B 'o')
$(B 'x')
$(B 'X')
$(B 'e')
$(B 'E')
$(B 'f')
$(B 'F')
$(B 'g')
$(B 'G')
$(B 'a')
$(B 'A')
</pre>
<dl>
<dt>$(I Flags)
<dl>
<dt>$(B '-')
<dd>
Left justify the result in the field.
It overrides any $(B 0) flag.
<dt>$(B '+')
<dd>Prefix positive numbers in a signed conversion with a $(B +).
It overrides any $(I space) flag.
<dt>$(B '#')
<dd>Use alternative formatting:
<dl>
<dt>For $(B 'o'):
<dd> Add to precision as necessary so that the first digit
of the octal formatting is a '0', even if both the argument
and the $(I Precision) are zero.
<dt> For $(B 'x') ($(B 'X')):
<dd> If non-zero, prefix result with $(B 0x) ($(B 0X)).
<dt> For floating point formatting:
<dd> Always insert the decimal point.
<dt> For $(B 'g') ($(B 'G')):
<dd> Do not elide trailing zeros.
</dl>
<dt>$(B '0')
<dd> For integer and floating point formatting when not nan or
infinity, use leading zeros
to pad rather than spaces.
Ignore if there's a $(I Precision).
<dt>$(B ' ')
<dd>Prefix positive numbers in a signed conversion with a space.
</dl>
<dt>$(I Width)
<dd>
Specifies the minimum field width.
If the width is a $(B *), the next argument, which must be
of type $(B int), is taken as the width.
If the width is negative, it is as if the $(B -) was given
as a $(I Flags) character.
<dt>$(I Precision)
<dd> Gives the precision for numeric conversions.
If the precision is a $(B *), the next argument, which must be
of type $(B int), is taken as the precision. If it is negative,
it is as if there was no $(I Precision).
<dt>$(I FormatChar)
<dd>
<dl>
<dt>$(B 's')
<dd>The corresponding argument is formatted in a manner consistent
with its type:
<dl>
<dt>$(B bool)
<dd>The result is <tt>'true'</tt> or <tt>'false'</tt>.
<dt>integral types
<dd>The $(B %d) format is used.
<dt>floating point types
<dd>The $(B %g) format is used.
<dt>string types
<dd>The result is the string converted to UTF-8.
A $(I Precision) specifies the maximum number of characters
to use in the result.
<dt>classes derived from $(B Object)
<dd>The result is the string returned from the class instance's
$(B .toString()) method.
A $(I Precision) specifies the maximum number of characters
to use in the result.
<dt>non-string static and dynamic arrays
<dd>The result is [s<sub>0</sub>, s<sub>1</sub>, ...]
where s<sub>k</sub> is the kth element
formatted with the default format.
</dl>
<dt>$(B 'b','d','o','x','X')
<dd> The corresponding argument must be an integral type
and is formatted as an integer. If the argument is a signed type
and the $(I FormatChar) is $(B d) it is converted to
a signed string of characters, otherwise it is treated as
unsigned. An argument of type $(B bool) is formatted as '1'
or '0'. The base used is binary for $(B b), octal for $(B o),
decimal
for $(B d), and hexadecimal for $(B x) or $(B X).
$(B x) formats using lower case letters, $(B X) uppercase.
If there are fewer resulting digits than the $(I Precision),
leading zeros are used as necessary.
If the $(I Precision) is 0 and the number is 0, no digits
result.
<dt>$(B 'e','E')
<dd> A floating point number is formatted as one digit before
the decimal point, $(I Precision) digits after, the $(I FormatChar),
±, followed by at least a two digit exponent: $(I d.dddddd)e$(I ±dd).
If there is no $(I Precision), six
digits are generated after the decimal point.
If the $(I Precision) is 0, no decimal point is generated.
<dt>$(B 'f','F')
<dd> A floating point number is formatted in decimal notation.
The $(I Precision) specifies the number of digits generated
after the decimal point. It defaults to six. At least one digit
is generated before the decimal point. If the $(I Precision)
is zero, no decimal point is generated.
<dt>$(B 'g','G')
<dd> A floating point number is formatted in either $(B e) or
$(B f) format for $(B g); $(B E) or $(B F) format for
$(B G).
The $(B f) format is used if the exponent for an $(B e) format
is greater than -5 and less than the $(I Precision).
The $(I Precision) specifies the number of significant
digits, and defaults to six.
Trailing zeros are elided after the decimal point, if the fractional
part is zero then no decimal point is generated.
<dt>$(B 'a','A')
<dd> A floating point number is formatted in hexadecimal
exponential notation 0x$(I h.hhhhhh)p$(I ±d).
There is one hexadecimal digit before the decimal point, and as
many after as specified by the $(I Precision).
If the $(I Precision) is zero, no decimal point is generated.
If there is no $(I Precision), as many hexadecimal digits as
necessary to exactly represent the mantissa are generated.
The exponent is written in as few digits as possible,
but at least one, is in decimal, and represents a power of 2 as in
$(I h.hhhhhh)*2<sup>$(I ±d)</sup>.
The exponent for zero is zero.
The hexadecimal digits, x and p are in upper case if the
$(I FormatChar) is upper case.
</dl>
Floating point NaN's are formatted as $(B nan) if the
$(I FormatChar) is lower case, or $(B NAN) if upper.
Floating point infinities are formatted as $(B inf) or
$(B infinity) if the
$(I FormatChar) is lower case, or $(B INF) or $(B INFINITY) if upper.
</dl>
Example:
-------------------------
import std.c.stdio;
import std.format;
void myPrint(...)
{
void putc(char c)
{
fputc(c, stdout);
}
std.format.doFormat(&putc, _arguments, _argptr);
}
...
int x = 27;
// prints 'The answer is 27:6'
myPrint("The answer is %s:", x, 6);
------------------------
*/
void doFormat(void delegate(dchar) putc, TypeInfo[] arguments, va_list argptr)
{
TypeInfo ti;
Mangle m;
uint flags;
int field_width;
int precision;
enum : uint
{
FLdash = 1,
FLplus = 2,
FLspace = 4,
FLhash = 8,
FLlngdbl = 0x20,
FL0pad = 0x40,
FLprecision = 0x80,
}
static TypeInfo skipCI(TypeInfo valti)
{
for (;;)
{
if (valti.classinfo.name.length == 18 &&
valti.classinfo.name[9..18] == "Invariant")
valti = (cast(TypeInfo_Invariant)valti).next;
else if (valti.classinfo.name.length == 14 &&
valti.classinfo.name[9..14] == "Const")
valti = (cast(TypeInfo_Const)valti).next;
else
break;
}
return valti;
}
void formatArg(char fc)
{
bool vbit;
ulong vnumber;
char vchar;
dchar vdchar;
Object vobject;
real vreal;
creal vcreal;
Mangle m2;
int signed = 0;
uint base = 10;
int uc;
char[ulong.sizeof * 8] tmpbuf; // long enough to print long in binary
const(char)* prefix = "";
string s;
void putstr(const char[] s)
{
//printf("putstr: s = %.*s, flags = x%x\n", s.length, s.ptr, flags);
ptrdiff_t padding = field_width -
(strlen(prefix) + toUCSindex(s, s.length));
ptrdiff_t prepad = 0;
ptrdiff_t postpad = 0;
if (padding > 0)
{
if (flags & FLdash)
postpad = padding;
else
prepad = padding;
}
if (flags & FL0pad)
{
while (*prefix)
putc(*prefix++);
while (prepad--)
putc('0');
}
else
{
while (prepad--)
putc(' ');
while (*prefix)
putc(*prefix++);
}
foreach (dchar c; s)
putc(c);
while (postpad--)
putc(' ');
}
void putreal(real v)
{
//printf("putreal %Lg\n", vreal);
switch (fc)
{
case 's':
fc = 'g';
break;
case 'f', 'F', 'e', 'E', 'g', 'G', 'a', 'A':
break;
default:
//printf("fc = '%c'\n", fc);
Lerror:
throw new FormatException("floating");
}
version (DigitalMarsC)
{
uint sl;
char[] fbuf = tmpbuf;
if (!(flags & FLprecision))
precision = 6;
while (1)
{
sl = fbuf.length;
prefix = (*__pfloatfmt)(fc, flags | FLlngdbl,
precision, &v, cast(char*)fbuf, &sl, field_width);
if (sl != -1)
break;
sl = fbuf.length * 2;
fbuf = (cast(char*)alloca(sl * char.sizeof))[0 .. sl];
}
putstr(fbuf[0 .. sl]);
}
else
{
ptrdiff_t sl;
char[] fbuf = tmpbuf;
char[12] format;
format[0] = '%';
int i = 1;
if (flags & FLdash)
format[i++] = '-';
if (flags & FLplus)
format[i++] = '+';
if (flags & FLspace)
format[i++] = ' ';
if (flags & FLhash)
format[i++] = '#';
if (flags & FL0pad)
format[i++] = '0';
format[i + 0] = '*';
format[i + 1] = '.';
format[i + 2] = '*';
format[i + 3] = 'L';
format[i + 4] = fc;
format[i + 5] = 0;
if (!(flags & FLprecision))
precision = -1;
while (1)
{
sl = fbuf.length;
int n;
version (Win64)
{
if(isnan(v)) // snprintf writes 1.#QNAN
n = snprintf(fbuf.ptr, sl, "nan");
else
n = snprintf(fbuf.ptr, sl, format.ptr, field_width,
precision, cast(double)v);
}
else
n = snprintf(fbuf.ptr, sl, format.ptr, field_width,
precision, v);
//printf("format = '%s', n = %d\n", cast(char*)format, n);
if (n >= 0 && n < sl)
{ sl = n;
break;
}
if (n < 0)
sl = sl * 2;
else
sl = n + 1;
fbuf = (cast(char*)alloca(sl * char.sizeof))[0 .. sl];
}
putstr(fbuf[0 .. sl]);
}
return;
}
static Mangle getMan(TypeInfo ti)
{
auto m = cast(Mangle)ti.classinfo.name[9];
if (ti.classinfo.name.length == 20 &&
ti.classinfo.name[9..20] == "StaticArray")
m = cast(Mangle)'G';
return m;
}
/* p = pointer to the first element in the array
* len = number of elements in the array
* valti = type of the elements
*/
void putArray(void* p, size_t len, TypeInfo valti)
{
//printf("\nputArray(len = %u), tsize = %u\n", len, valti.tsize);
putc('[');
valti = skipCI(valti);
size_t tsize = valti.tsize;
auto argptrSave = argptr;
auto tiSave = ti;
auto mSave = m;
ti = valti;
//printf("\n%.*s\n", valti.classinfo.name.length, valti.classinfo.name.ptr);
m = getMan(valti);
while (len--)
{
//doFormat(putc, (&valti)[0 .. 1], p);
version (Win64)
{
void* q = void;
if (tsize > 8 && m != Mangle.Tsarray)
{ q = p;
argptr = &q;
}
else
argptr = p;
formatArg('s');
p += tsize;
}
else
{
version (X86)
argptr = p;
else version(X86_64)
{ __va_list va;
va.stack_args = p;
argptr = &va;
}
else
static assert(false, "unsupported platform");
formatArg('s');
p += tsize;
}
if (len > 0) putc(',');
}
m = mSave;
ti = tiSave;
argptr = argptrSave;
putc(']');
}
void putAArray(ubyte[long] vaa, TypeInfo valti, TypeInfo keyti)
{
putc('[');
bool comma=false;
auto argptrSave = argptr;
auto tiSave = ti;
auto mSave = m;
valti = skipCI(valti);
keyti = skipCI(keyti);
foreach(ref fakevalue; vaa)
{
if (comma) putc(',');
comma = true;
void *pkey = &fakevalue;
version (D_LP64)
pkey -= (long.sizeof + 15) & ~(15);
else
pkey -= (long.sizeof + size_t.sizeof - 1) & ~(size_t.sizeof - 1);
// the key comes before the value
auto keysize = keyti.tsize;
version (D_LP64)
auto keysizet = (keysize + 15) & ~(15);
else
auto keysizet = (keysize + size_t.sizeof - 1) & ~(size_t.sizeof - 1);
void* pvalue = pkey + keysizet;
//doFormat(putc, (&keyti)[0..1], pkey);
m = getMan(keyti);
version (X86)
argptr = pkey;
else version (Win64)
{
void* q = void;
if (keysize > 8 && m != Mangle.Tsarray)
{ q = pkey;
argptr = &q;
}
else
argptr = pkey;
}
else version (X86_64)
{ __va_list va;
va.stack_args = pkey;
argptr = &va;
}
else static assert(false, "unsupported platform");
ti = keyti;
formatArg('s');
putc(':');
//doFormat(putc, (&valti)[0..1], pvalue);
m = getMan(valti);
version (X86)
argptr = pvalue;
else version (Win64)
{
void* q2 = void;
auto valuesize = valti.tsize;
if (valuesize > 8 && m != Mangle.Tsarray)
{ q2 = pvalue;
argptr = &q2;
}
else
argptr = pvalue;
}
else version (X86_64)
{ __va_list va2;
va2.stack_args = pvalue;
argptr = &va2;
}
else static assert(false, "unsupported platform");
ti = valti;
formatArg('s');
}
m = mSave;
ti = tiSave;
argptr = argptrSave;
putc(']');
}
//printf("formatArg(fc = '%c', m = '%c')\n", fc, m);
switch (m)
{
case Mangle.Tbool:
vbit = va_arg!(bool)(argptr);
if (fc != 's')
{ vnumber = vbit;
goto Lnumber;
}
putstr(vbit ? "true" : "false");
return;
case Mangle.Tchar:
vchar = va_arg!(char)(argptr);
if (fc != 's')
{ vnumber = vchar;
goto Lnumber;
}
L2:
putstr((&vchar)[0 .. 1]);
return;
case Mangle.Twchar:
vdchar = va_arg!(wchar)(argptr);
goto L1;
case Mangle.Tdchar:
vdchar = va_arg!(dchar)(argptr);
L1:
if (fc != 's')
{ vnumber = vdchar;
goto Lnumber;
}
if (vdchar <= 0x7F)
{ vchar = cast(char)vdchar;
goto L2;
}
else
{ if (!isValidDchar(vdchar))
throw new UTFException("invalid dchar in format");
char[4] vbuf;
putstr(toUTF8(vbuf, vdchar));
}
return;
case Mangle.Tbyte:
signed = 1;
vnumber = va_arg!(byte)(argptr);
goto Lnumber;
case Mangle.Tubyte:
vnumber = va_arg!(ubyte)(argptr);
goto Lnumber;
case Mangle.Tshort:
signed = 1;
vnumber = va_arg!(short)(argptr);
goto Lnumber;
case Mangle.Tushort:
vnumber = va_arg!(ushort)(argptr);
goto Lnumber;
case Mangle.Tint:
signed = 1;
vnumber = va_arg!(int)(argptr);
goto Lnumber;
case Mangle.Tuint:
Luint:
vnumber = va_arg!(uint)(argptr);
goto Lnumber;
case Mangle.Tlong:
signed = 1;
vnumber = cast(ulong)va_arg!(long)(argptr);
goto Lnumber;
case Mangle.Tulong:
Lulong:
vnumber = va_arg!(ulong)(argptr);
goto Lnumber;
case Mangle.Tclass:
vobject = va_arg!(Object)(argptr);
if (vobject is null)
s = "null";
else
s = vobject.toString();
goto Lputstr;
case Mangle.Tpointer:
vnumber = cast(ulong)va_arg!(void*)(argptr);
if (fc != 'x') uc = 1;
flags |= FL0pad;
if (!(flags & FLprecision))
{ flags |= FLprecision;
precision = (void*).sizeof;
}
base = 16;
goto Lnumber;
case Mangle.Tfloat:
case Mangle.Tifloat:
if (fc == 'x' || fc == 'X')
goto Luint;
vreal = va_arg!(float)(argptr);
goto Lreal;
case Mangle.Tdouble:
case Mangle.Tidouble:
if (fc == 'x' || fc == 'X')
goto Lulong;
vreal = va_arg!(double)(argptr);
goto Lreal;
case Mangle.Treal:
case Mangle.Tireal:
vreal = va_arg!(real)(argptr);
goto Lreal;
case Mangle.Tcfloat:
vcreal = va_arg!(cfloat)(argptr);
goto Lcomplex;
case Mangle.Tcdouble:
vcreal = va_arg!(cdouble)(argptr);
goto Lcomplex;
case Mangle.Tcreal:
vcreal = va_arg!(creal)(argptr);
goto Lcomplex;
case Mangle.Tsarray:
version (X86)
putArray(argptr, (cast(TypeInfo_StaticArray)ti).len, cast()(cast(TypeInfo_StaticArray)ti).next);
else version (Win64)
putArray(argptr, (cast(TypeInfo_StaticArray)ti).len, cast()(cast(TypeInfo_StaticArray)ti).next);
else
putArray((cast(__va_list*)argptr).stack_args, (cast(TypeInfo_StaticArray)ti).len, cast()(cast(TypeInfo_StaticArray)ti).next);
return;
case Mangle.Tarray:
int mi = 10;
if (ti.classinfo.name.length == 14 &&
ti.classinfo.name[9..14] == "Array")
{ // array of non-primitive types
TypeInfo tn = cast()(cast(TypeInfo_Array)ti).next;
tn = skipCI(tn);
switch (cast(Mangle)tn.classinfo.name[9])
{
case Mangle.Tchar: goto LarrayChar;
case Mangle.Twchar: goto LarrayWchar;
case Mangle.Tdchar: goto LarrayDchar;
default:
break;
}
void[] va = va_arg!(void[])(argptr);
putArray(va.ptr, va.length, tn);
return;
}
if (ti.classinfo.name.length == 25 &&
ti.classinfo.name[9..25] == "AssociativeArray")
{ // associative array
ubyte[long] vaa = va_arg!(ubyte[long])(argptr);
putAArray(vaa,
cast()(cast(TypeInfo_AssociativeArray)ti).next,
(cast(TypeInfo_AssociativeArray)ti).key);
return;
}
while (1)
{
m2 = cast(Mangle)ti.classinfo.name[mi];
switch (m2)
{
case Mangle.Tchar:
LarrayChar:
s = va_arg!(string)(argptr);
goto Lputstr;
case Mangle.Twchar:
LarrayWchar:
wchar[] sw = va_arg!(wchar[])(argptr);
s = toUTF8(sw);
goto Lputstr;
case Mangle.Tdchar:
LarrayDchar:
auto sd = va_arg!(dstring)(argptr);
s = toUTF8(sd);
Lputstr:
if (fc != 's')
throw new FormatException("string");
if (flags & FLprecision && precision < s.length)
s = s[0 .. precision];
putstr(s);
break;
case Mangle.Tconst:
case Mangle.Timmutable:
mi++;
continue;
default:
TypeInfo ti2 = primitiveTypeInfo(m2);
if (!ti2)
goto Lerror;
void[] va = va_arg!(void[])(argptr);
putArray(va.ptr, va.length, ti2);
}
return;
}
assert(0);
case Mangle.Ttypedef:
ti = (cast(TypeInfo_Typedef)ti).base;
m = cast(Mangle)ti.classinfo.name[9];
formatArg(fc);
return;
case Mangle.Tenum:
ti = (cast(TypeInfo_Enum)ti).base;
m = cast(Mangle)ti.classinfo.name[9];
formatArg(fc);
return;
case Mangle.Tstruct:
{ TypeInfo_Struct tis = cast(TypeInfo_Struct)ti;
if (tis.xtoString is null)
throw new FormatException("Can't convert " ~ tis.toString()
~ " to string: \"string toString()\" not defined");
version(X86)
{
s = tis.xtoString(argptr);
argptr += (tis.tsize + 3) & ~3;
}
else version(Win64)
{
void* p = argptr;
if (tis.tsize > 8)
p = *cast(void**)p;
s = tis.xtoString(p);
argptr += size_t.sizeof;
}
else version (X86_64)
{
void[32] parmn = void; // place to copy struct if passed in regs
void* p;
auto tsize = tis.tsize;
TypeInfo arg1, arg2;
if (!tis.argTypes(arg1, arg2)) // if could be passed in regs
{ assert(tsize <= parmn.length);
p = parmn.ptr;
va_arg(argptr, tis, p);
}
else
{ /* Avoid making a copy of the struct; take advantage of
* it always being passed in memory
*/
// The arg may have more strict alignment than the stack
auto talign = tis.talign;
__va_list* ap = cast(__va_list*)argptr;
p = cast(void*)((cast(size_t)ap.stack_args + talign - 1) & ~(talign - 1));
ap.stack_args = cast(void*)(cast(size_t)p + ((tsize + size_t.sizeof - 1) & ~(size_t.sizeof - 1)));
}
s = tis.xtoString(p);
}
else
static assert(0);
goto Lputstr;
}
default:
goto Lerror;
}
Lnumber:
switch (fc)
{
case 's':
case 'd':
if (signed)
{ if (cast(long)vnumber < 0)
{ prefix = "-";
vnumber = -vnumber;
}
else if (flags & FLplus)
prefix = "+";
else if (flags & FLspace)
prefix = " ";
}
break;
case 'b':
signed = 0;
base = 2;
break;
case 'o':
signed = 0;
base = 8;
break;
case 'X':
uc = 1;
if (flags & FLhash && vnumber)
prefix = "0X";
signed = 0;
base = 16;
break;
case 'x':
if (flags & FLhash && vnumber)
prefix = "0x";
signed = 0;
base = 16;
break;
default:
goto Lerror;
}
if (!signed)
{
switch (m)
{
case Mangle.Tbyte:
vnumber &= 0xFF;
break;
case Mangle.Tshort:
vnumber &= 0xFFFF;
break;
case Mangle.Tint:
vnumber &= 0xFFFFFFFF;
break;
default:
break;
}
}
if (flags & FLprecision && fc != 'p')
flags &= ~FL0pad;
if (vnumber < base)
{
if (vnumber == 0 && precision == 0 && flags & FLprecision &&
!(fc == 'o' && flags & FLhash))
{
putstr(null);
return;
}
if (precision == 0 || !(flags & FLprecision))
{ vchar = cast(char)('0' + vnumber);
if (vnumber < 10)
vchar = cast(char)('0' + vnumber);
else
vchar = cast(char)((uc ? 'A' - 10 : 'a' - 10) + vnumber);
goto L2;
}
}
ptrdiff_t n = tmpbuf.length;
char c;
int hexoffset = uc ? ('A' - ('9' + 1)) : ('a' - ('9' + 1));
while (vnumber)
{
c = cast(char)((vnumber % base) + '0');
if (c > '9')
c += hexoffset;
vnumber /= base;
tmpbuf[--n] = c;
}
if (tmpbuf.length - n < precision && precision < tmpbuf.length)
{
ptrdiff_t m = tmpbuf.length - precision;
tmpbuf[m .. n] = '0';
n = m;
}
else if (flags & FLhash && fc == 'o')
prefix = "0";
putstr(tmpbuf[n .. tmpbuf.length]);
return;
Lreal:
putreal(vreal);
return;
Lcomplex:
putreal(vcreal.re);
putc('+');
putreal(vcreal.im);
putc('i');
return;
Lerror:
throw new FormatException("formatArg");
}
for (int j = 0; j < arguments.length; )
{
ti = arguments[j++];
//printf("arg[%d]: '%.*s' %d\n", j, ti.classinfo.name.length, ti.classinfo.name.ptr, ti.classinfo.name.length);
//ti.print();
flags = 0;
precision = 0;
field_width = 0;
ti = skipCI(ti);
int mi = 9;
do
{
if (ti.classinfo.name.length <= mi)
goto Lerror;
m = cast(Mangle)ti.classinfo.name[mi++];
} while (m == Mangle.Tconst || m == Mangle.Timmutable);
if (m == Mangle.Tarray)
{
if (ti.classinfo.name.length == 14 &&
ti.classinfo.name[9..14] == "Array")
{
TypeInfo tn = cast()(cast(TypeInfo_Array)ti).next;
tn = skipCI(tn);
switch (cast(Mangle)tn.classinfo.name[9])
{
case Mangle.Tchar:
case Mangle.Twchar:
case Mangle.Tdchar:
ti = tn;
mi = 9;
break;
default:
break;
}
}
L1:
Mangle m2 = cast(Mangle)ti.classinfo.name[mi];
string fmt; // format string
wstring wfmt;
dstring dfmt;
/* For performance reasons, this code takes advantage of the
* fact that most format strings will be ASCII, and that the
* format specifiers are always ASCII. This means we only need
* to deal with UTF in a couple of isolated spots.
*/
switch (m2)
{
case Mangle.Tchar:
fmt = va_arg!(string)(argptr);
break;
case Mangle.Twchar:
wfmt = va_arg!(wstring)(argptr);
fmt = toUTF8(wfmt);
break;
case Mangle.Tdchar:
dfmt = va_arg!(dstring)(argptr);
fmt = toUTF8(dfmt);
break;
case Mangle.Tconst:
case Mangle.Timmutable:
mi++;
goto L1;
default:
formatArg('s');
continue;
}
for (size_t i = 0; i < fmt.length; )
{ dchar c = fmt[i++];
dchar getFmtChar()
{ // Valid format specifier characters will never be UTF
if (i == fmt.length)
throw new FormatException("invalid specifier");
return fmt[i++];
}
int getFmtInt()
{ int n;
while (1)
{
n = n * 10 + (c - '0');
if (n < 0) // overflow
throw new FormatException("int overflow");
c = getFmtChar();
if (c < '0' || c > '9')
break;
}
return n;
}
int getFmtStar()
{ Mangle m;
TypeInfo ti;
if (j == arguments.length)
throw new FormatException("too few arguments");
ti = arguments[j++];
m = cast(Mangle)ti.classinfo.name[9];
if (m != Mangle.Tint)
throw new FormatException("int argument expected");
return va_arg!(int)(argptr);
}
if (c != '%')
{
if (c > 0x7F) // if UTF sequence
{
i--; // back up and decode UTF sequence
c = std.utf.decode(fmt, i);
}
Lputc:
putc(c);
continue;
}
// Get flags {-+ #}
flags = 0;
while (1)
{
c = getFmtChar();
switch (c)
{
case '-': flags |= FLdash; continue;
case '+': flags |= FLplus; continue;
case ' ': flags |= FLspace; continue;
case '#': flags |= FLhash; continue;
case '0': flags |= FL0pad; continue;
case '%': if (flags == 0)
goto Lputc;
break;
default: break;
}
break;
}
// Get field width
field_width = 0;
if (c == '*')
{
field_width = getFmtStar();
if (field_width < 0)
{ flags |= FLdash;
field_width = -field_width;
}
c = getFmtChar();
}
else if (c >= '0' && c <= '9')
field_width = getFmtInt();
if (flags & FLplus)
flags &= ~FLspace;
if (flags & FLdash)
flags &= ~FL0pad;
// Get precision
precision = 0;
if (c == '.')
{ flags |= FLprecision;
//flags &= ~FL0pad;
c = getFmtChar();
if (c == '*')
{
precision = getFmtStar();
if (precision < 0)
{ precision = 0;
flags &= ~FLprecision;
}
c = getFmtChar();
}
else if (c >= '0' && c <= '9')
precision = getFmtInt();
}
if (j == arguments.length)
goto Lerror;
ti = arguments[j++];
ti = skipCI(ti);
mi = 9;
do
{
m = cast(Mangle)ti.classinfo.name[mi++];
} while (m == Mangle.Tconst || m == Mangle.Timmutable);
if (c > 0x7F) // if UTF sequence
goto Lerror; // format specifiers can't be UTF
formatArg(cast(char)c);
}
}
else
{
formatArg('s');
}
}
return;
Lerror:
throw new FormatException();
}
/* ======================== Unit Tests ====================================== */
unittest
{
int i;
string s;
debug(format) printf("std.format.format.unittest\n");
s = std.string.format("hello world! %s %s %s%s%s", true, 57, 1_000_000_000, 'x', " foo");
assert(s == "hello world! true 57 1000000000x foo");
s = std.string.format("%s %A %s", 1.67, -1.28, float.nan);
/* The host C library is used to format floats.
* C99 doesn't specify what the hex digit before the decimal point
* is for %A.
*/
//version (linux)
// assert(s == "1.67 -0XA.3D70A3D70A3D8P-3 nan");
//else version (OSX)
// assert(s == "1.67 -0XA.3D70A3D70A3D8P-3 nan", s);
//else
assert(s == "1.67 -0X1.47AE147AE147BP+0 nan", s);
s = std.string.format("%x %X", 0x1234AF, 0xAFAFAFAF);
assert(s == "1234af AFAFAFAF");
s = std.string.format("%b %o", 0x1234AF, 0xAFAFAFAF);
assert(s == "100100011010010101111 25753727657");
s = std.string.format("%d %s", 0x1234AF, 0xAFAFAFAF);
assert(s == "1193135 2947526575");
//version(X86_64)
//{
// pragma(msg, "several format tests disabled on x86_64 due to bug 5625");
//}
//else
//{
s = std.string.format("%s", 1.2 + 3.4i);
assert(s == "1.2+3.4i", s);
//s = std.string.format("%x %X", 1.32, 6.78f);
//assert(s == "3ff51eb851eb851f 40D8F5C3");
//}
s = std.string.format("%#06.*f",2,12.345);
assert(s == "012.35");
s = std.string.format("%#0*.*f",6,2,12.345);
assert(s == "012.35");
s = std.string.format("%7.4g:", 12.678);
assert(s == " 12.68:");
s = std.string.format("%7.4g:", 12.678L);
assert(s == " 12.68:");
s = std.string.format("%04f|%05d|%#05x|%#5x",-4.0,-10,1,1);
assert(s == "-4.000000|-0010|0x001| 0x1");
i = -10;
s = std.string.format("%d|%3d|%03d|%1d|%01.4f",i,i,i,i,cast(double) i);
assert(s == "-10|-10|-10|-10|-10.0000");
i = -5;
s = std.string.format("%d|%3d|%03d|%1d|%01.4f",i,i,i,i,cast(double) i);
assert(s == "-5| -5|-05|-5|-5.0000");
i = 0;
s = std.string.format("%d|%3d|%03d|%1d|%01.4f",i,i,i,i,cast(double) i);
assert(s == "0| 0|000|0|0.0000");
i = 5;
s = std.string.format("%d|%3d|%03d|%1d|%01.4f",i,i,i,i,cast(double) i);
assert(s == "5| 5|005|5|5.0000");
i = 10;
s = std.string.format("%d|%3d|%03d|%1d|%01.4f",i,i,i,i,cast(double) i);
assert(s == "10| 10|010|10|10.0000");
s = std.string.format("%.0d", 0);
assert(s == "");
s = std.string.format("%.g", .34);
assert(s == "0.3");
s = std.string.format("%.0g", .34);
assert(s == "0.3");
s = std.string.format("%.2g", .34);
assert(s == "0.34");
s = std.string.format("%0.0008f", 1e-08);
assert(s == "0.00000001");
s = std.string.format("%0.0008f", 1e-05);
assert(s == "0.00001000");
s = "helloworld";
string r;
r = std.string.format("%.2s", s[0..5]);
assert(r == "he");
r = std.string.format("%.20s", s[0..5]);
assert(r == "hello");
r = std.string.format("%8s", s[0..5]);
assert(r == " hello");
byte[] arrbyte = new byte[4];
arrbyte[0] = 100;
arrbyte[1] = -99;
arrbyte[3] = 0;
r = std.string.format("%s", arrbyte);
assert(r == "[100, -99, 0, 0]");
ubyte[] arrubyte = new ubyte[4];
arrubyte[0] = 100;
arrubyte[1] = 200;
arrubyte[3] = 0;
r = std.string.format("%s", arrubyte);
assert(r == "[100, 200, 0, 0]");
short[] arrshort = new short[4];
arrshort[0] = 100;
arrshort[1] = -999;
arrshort[3] = 0;
r = std.string.format("%s", arrshort);
assert(r == "[100, -999, 0, 0]");
ushort[] arrushort = new ushort[4];
arrushort[0] = 100;
arrushort[1] = 20_000;
arrushort[3] = 0;
r = std.string.format("%s", arrushort);
assert(r == "[100, 20000, 0, 0]");
int[] arrint = new int[4];
arrint[0] = 100;
arrint[1] = -999;
arrint[3] = 0;
r = std.string.format("%s", arrint);
assert(r == "[100, -999, 0, 0]");
long[] arrlong = new long[4];
arrlong[0] = 100;
arrlong[1] = -999;
arrlong[3] = 0;
r = std.string.format("%s", arrlong);
assert(r == "[100, -999, 0, 0]");
ulong[] arrulong = new ulong[4];
arrulong[0] = 100;
arrulong[1] = 999;
arrulong[3] = 0;
r = std.string.format("%s", arrulong);
assert(r == "[100, 999, 0, 0]");
string[] arr2 = new string[4];
arr2[0] = "hello";
arr2[1] = "world";
arr2[3] = "foo";
r = std.string.format("%s", arr2);
assert(r == `["hello", "world", "", "foo"]`);
r = std.string.format("%.8d", 7);
assert(r == "00000007");
r = std.string.format("%.8x", 10);
assert(r == "0000000a");
r = std.string.format("%-3d", 7);
assert(r == "7 ");
r = std.string.format("%*d", -3, 7);
assert(r == "7 ");
r = std.string.format("%.*d", -3, 7);
assert(r == "7");
//typedef int myint;
//myint m = -7;
//r = std.string.format(m);
//assert(r == "-7");
r = std.string.format("abc"c);
assert(r == "abc");
r = std.string.format("def"w);
assert(r == "def");
r = std.string.format("ghi"d);
assert(r == "ghi");
void* p = cast(void*)0xDEADBEEF;
r = std.string.format("%s", p);
assert(r == "DEADBEEF");
r = std.string.format("%#x", 0xabcd);
assert(r == "0xabcd");
r = std.string.format("%#X", 0xABCD);
assert(r == "0XABCD");
r = std.string.format("%#o", octal!12345);
assert(r == "012345");
r = std.string.format("%o", 9);
assert(r == "11");
r = std.string.format("%+d", 123);
assert(r == "+123");
r = std.string.format("%+d", -123);
assert(r == "-123");
r = std.string.format("% d", 123);
assert(r == " 123");
r = std.string.format("% d", -123);
assert(r == "-123");
r = std.string.format("%%");
assert(r == "%");
r = std.string.format("%d", true);
assert(r == "1");
r = std.string.format("%d", false);
assert(r == "0");
r = std.string.format("%d", 'a');
assert(r == "97");
wchar wc = 'a';
r = std.string.format("%d", wc);
assert(r == "97");
dchar dc = 'a';
r = std.string.format("%d", dc);
assert(r == "97");
byte b = byte.max;
r = std.string.format("%x", b);
assert(r == "7f");
r = std.string.format("%x", ++b);
assert(r == "80");
r = std.string.format("%x", ++b);
assert(r == "81");
short sh = short.max;
r = std.string.format("%x", sh);
assert(r == "7fff");
r = std.string.format("%x", ++sh);
assert(r == "8000");
r = std.string.format("%x", ++sh);
assert(r == "8001");
i = int.max;
r = std.string.format("%x", i);
assert(r == "7fffffff");
r = std.string.format("%x", ++i);
assert(r == "80000000");
r = std.string.format("%x", ++i);
assert(r == "80000001");
r = std.string.format("%x", 10);
assert(r == "a");
r = std.string.format("%X", 10);
assert(r == "A");
r = std.string.format("%x", 15);
assert(r == "f");
r = std.string.format("%X", 15);
assert(r == "F");
Object c = null;
r = std.string.format("%s", c);
assert(r == "null");
enum TestEnum
{
Value1, Value2
}
r = std.string.format("%s", TestEnum.Value2);
assert(r == "Value2");
immutable(char[5])[int] aa = ([3:"hello", 4:"betty"]);
r = std.string.format("%s", aa.values);
assert(r == `["hello", "betty"]`);
r = std.string.format("%s", aa);
assert(r == `[3:"hello", 4:"betty"]`);
static const dchar[] ds = ['a','b'];
for (int j = 0; j < ds.length; ++j)
{
r = std.string.format(" %d", ds[j]);
if (j == 0)
assert(r == " 97");
else
assert(r == " 98");
}
r = std.string.format(">%14d<, %s", 15, [1,2,3]);
assert(r == "> 15<, [1, 2, 3]");
assert(std.string.format("%8s", "bar") == " bar");
assert(std.string.format("%8s", "b\u00e9ll\u00f4") == " b\u00e9ll\u00f4");
}
unittest
{
// bugzilla 3479
auto stream = appender!(char[])();
formattedWrite(stream, "%2$.*1$d", 12, 10);
assert(stream.data == "000000000010", stream.data);
}
|
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/parse.d, _parse.d)
* Documentation: https://dlang.org/phobos/dmd_parse.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/parse.d
*/
module dmd.parse;
import core.stdc.stdio;
import core.stdc.string;
import dmd.globals;
import dmd.id;
import dmd.identifier;
import dmd.lexer;
import dmd.errors;
import dmd.root.filename;
import dmd.root.outbuffer;
import dmd.root.rmem;
import dmd.root.rootobject;
import dmd.root.string;
import dmd.tokens;
// How multiple declarations are parsed.
// If 1, treat as C.
// If 0, treat:
// int *p, i;
// as:
// int* p;
// int* i;
private enum CDECLSYNTAX = 0;
// Support C cast syntax:
// (type)(expression)
private enum CCASTSYNTAX = 1;
// Support postfix C array declarations, such as
// int a[3][4];
private enum CARRAYDECL = 1;
/**********************************
* Set operator precedence for each operator.
*
* Used by hdrgen
*/
immutable PREC[TOK.max_] precedence =
[
TOK.type : PREC.expr,
TOK.error : PREC.expr,
TOK.objcClassReference : PREC.expr, // Objective-C class reference, same as TOK.type
TOK.typeof_ : PREC.primary,
TOK.mixin_ : PREC.primary,
TOK.import_ : PREC.primary,
TOK.dotVariable : PREC.primary,
TOK.scope_ : PREC.primary,
TOK.identifier : PREC.primary,
TOK.this_ : PREC.primary,
TOK.super_ : PREC.primary,
TOK.int64 : PREC.primary,
TOK.float64 : PREC.primary,
TOK.complex80 : PREC.primary,
TOK.null_ : PREC.primary,
TOK.string_ : PREC.primary,
TOK.arrayLiteral : PREC.primary,
TOK.assocArrayLiteral : PREC.primary,
TOK.classReference : PREC.primary,
TOK.file : PREC.primary,
TOK.fileFullPath : PREC.primary,
TOK.line : PREC.primary,
TOK.moduleString : PREC.primary,
TOK.functionString : PREC.primary,
TOK.prettyFunction : PREC.primary,
TOK.typeid_ : PREC.primary,
TOK.is_ : PREC.primary,
TOK.assert_ : PREC.primary,
TOK.halt : PREC.primary,
TOK.template_ : PREC.primary,
TOK.dSymbol : PREC.primary,
TOK.function_ : PREC.primary,
TOK.variable : PREC.primary,
TOK.symbolOffset : PREC.primary,
TOK.structLiteral : PREC.primary,
TOK.arrayLength : PREC.primary,
TOK.delegatePointer : PREC.primary,
TOK.delegateFunctionPointer : PREC.primary,
TOK.remove : PREC.primary,
TOK.tuple : PREC.primary,
TOK.traits : PREC.primary,
TOK.default_ : PREC.primary,
TOK.overloadSet : PREC.primary,
TOK.void_ : PREC.primary,
TOK.vectorArray : PREC.primary,
// post
TOK.dotTemplateInstance : PREC.primary,
TOK.dotIdentifier : PREC.primary,
TOK.dotTemplateDeclaration : PREC.primary,
TOK.dot : PREC.primary,
TOK.dotType : PREC.primary,
TOK.plusPlus : PREC.primary,
TOK.minusMinus : PREC.primary,
TOK.prePlusPlus : PREC.primary,
TOK.preMinusMinus : PREC.primary,
TOK.call : PREC.primary,
TOK.slice : PREC.primary,
TOK.array : PREC.primary,
TOK.index : PREC.primary,
TOK.delegate_ : PREC.unary,
TOK.address : PREC.unary,
TOK.star : PREC.unary,
TOK.negate : PREC.unary,
TOK.uadd : PREC.unary,
TOK.not : PREC.unary,
TOK.tilde : PREC.unary,
TOK.delete_ : PREC.unary,
TOK.new_ : PREC.unary,
TOK.newAnonymousClass : PREC.unary,
TOK.cast_ : PREC.unary,
TOK.vector : PREC.unary,
TOK.pow : PREC.pow,
TOK.mul : PREC.mul,
TOK.div : PREC.mul,
TOK.mod : PREC.mul,
TOK.add : PREC.add,
TOK.min : PREC.add,
TOK.concatenate : PREC.add,
TOK.leftShift : PREC.shift,
TOK.rightShift : PREC.shift,
TOK.unsignedRightShift : PREC.shift,
TOK.lessThan : PREC.rel,
TOK.lessOrEqual : PREC.rel,
TOK.greaterThan : PREC.rel,
TOK.greaterOrEqual : PREC.rel,
TOK.in_ : PREC.rel,
/* Note that we changed precedence, so that < and != have the same
* precedence. This change is in the parser, too.
*/
TOK.equal : PREC.rel,
TOK.notEqual : PREC.rel,
TOK.identity : PREC.rel,
TOK.notIdentity : PREC.rel,
TOK.and : PREC.and,
TOK.xor : PREC.xor,
TOK.or : PREC.or,
TOK.andAnd : PREC.andand,
TOK.orOr : PREC.oror,
TOK.question : PREC.cond,
TOK.assign : PREC.assign,
TOK.construct : PREC.assign,
TOK.blit : PREC.assign,
TOK.addAssign : PREC.assign,
TOK.minAssign : PREC.assign,
TOK.concatenateAssign : PREC.assign,
TOK.concatenateElemAssign : PREC.assign,
TOK.concatenateDcharAssign : PREC.assign,
TOK.mulAssign : PREC.assign,
TOK.divAssign : PREC.assign,
TOK.modAssign : PREC.assign,
TOK.powAssign : PREC.assign,
TOK.leftShiftAssign : PREC.assign,
TOK.rightShiftAssign : PREC.assign,
TOK.unsignedRightShiftAssign : PREC.assign,
TOK.andAssign : PREC.assign,
TOK.orAssign : PREC.assign,
TOK.xorAssign : PREC.assign,
TOK.comma : PREC.expr,
TOK.declaration : PREC.expr,
TOK.interval : PREC.assign,
];
enum ParseStatementFlags : int
{
semi = 1, // empty ';' statements are allowed, but deprecated
scope_ = 2, // start a new scope
curly = 4, // { } statement is required
curlyScope = 8, // { } starts a new scope
semiOk = 0x10, // empty ';' are really ok
}
private struct PrefixAttributes(AST)
{
StorageClass storageClass;
AST.Expression depmsg;
LINK link;
AST.Prot protection;
bool setAlignment;
AST.Expression ealign;
AST.Expressions* udas;
const(char)* comment;
}
/*****************************
* Destructively extract storage class from pAttrs.
*/
private StorageClass getStorageClass(AST)(PrefixAttributes!(AST)* pAttrs)
{
StorageClass stc = AST.STC.undefined_;
if (pAttrs)
{
stc = pAttrs.storageClass;
pAttrs.storageClass = AST.STC.undefined_;
}
return stc;
}
/**************************************
* dump mixin expansion to file for better debugging
*/
private bool writeMixin(const(char)[] s, ref Loc loc)
{
if (!global.params.mixinOut)
return false;
OutBuffer* ob = global.params.mixinOut;
ob.writestring("// expansion at ");
ob.writestring(loc.toChars());
ob.writenl();
global.params.mixinLines++;
loc = Loc(global.params.mixinFile, global.params.mixinLines + 1, loc.charnum);
// write by line to create consistent line endings
size_t lastpos = 0;
for (size_t i = 0; i < s.length; ++i)
{
// detect LF and CRLF
const c = s[i];
if (c == '\n' || (c == '\r' && i+1 < s.length && s[i+1] == '\n'))
{
ob.writestring(s[lastpos .. i]);
ob.writenl();
global.params.mixinLines++;
if (c == '\r')
++i;
lastpos = i + 1;
}
}
if(lastpos < s.length)
ob.writestring(s[lastpos .. $]);
if (s.length == 0 || s[$-1] != '\n')
{
ob.writenl(); // ensure empty line after expansion
global.params.mixinLines++;
}
ob.writenl();
global.params.mixinLines++;
return true;
}
/***********************************************************
*/
final class Parser(AST) : Lexer
{
AST.ModuleDeclaration* md;
alias STC = AST.STC;
private
{
AST.Module mod;
LINK linkage;
CPPMANGLE cppmangle;
Loc endloc; // set to location of last right curly
int inBrackets; // inside [] of array index or slice
Loc lookingForElse; // location of lonely if looking for an else
}
/*********************
* Use this constructor for string mixins.
* Input:
* loc location in source file of mixin
*/
extern (D) this(const ref Loc loc, AST.Module _module, const(char)[] input, bool doDocComment)
{
super(_module ? _module.srcfile.toChars() : null, input.ptr, 0, input.length, doDocComment, false);
//printf("Parser::Parser()\n");
scanloc = loc;
if (!writeMixin(input, scanloc) && loc.filename)
{
/* Create a pseudo-filename for the mixin string, as it may not even exist
* in the source file.
*/
char* filename = cast(char*)mem.xmalloc(strlen(loc.filename) + 7 + (loc.linnum).sizeof * 3 + 1);
sprintf(filename, "%s-mixin-%d", loc.filename, cast(int)loc.linnum);
scanloc.filename = filename;
}
mod = _module;
linkage = LINK.d;
//nextToken(); // start up the scanner
}
extern (D) this(AST.Module _module, const(char)[] input, bool doDocComment)
{
super(_module ? _module.srcfile.toChars() : null, input.ptr, 0, input.length, doDocComment, false);
//printf("Parser::Parser()\n");
mod = _module;
linkage = LINK.d;
//nextToken(); // start up the scanner
}
AST.Dsymbols* parseModule()
{
const comment = token.blockComment;
bool isdeprecated = false;
AST.Expression msg = null;
AST.Expressions* udas = null;
AST.Dsymbols* decldefs;
AST.Dsymbol lastDecl = mod; // for attaching ddoc unittests to module decl
Token* tk;
if (skipAttributes(&token, &tk) && tk.value == TOK.module_)
{
while (token.value != TOK.module_)
{
switch (token.value)
{
case TOK.deprecated_:
{
// deprecated (...) module ...
if (isdeprecated)
error("there is only one deprecation attribute allowed for module declaration");
isdeprecated = true;
nextToken();
if (token.value == TOK.leftParentheses)
{
check(TOK.leftParentheses);
msg = parseAssignExp();
check(TOK.rightParentheses);
}
break;
}
case TOK.at:
{
AST.Expressions* exps = null;
const stc = parseAttribute(&exps);
if (stc & atAttrGroup)
{
error("`@%s` attribute for module declaration is not supported", token.toChars());
}
else
{
udas = AST.UserAttributeDeclaration.concat(udas, exps);
}
if (stc)
nextToken();
break;
}
default:
{
error("`module` expected instead of `%s`", token.toChars());
nextToken();
break;
}
}
}
}
if (udas)
{
auto a = new AST.Dsymbols();
auto udad = new AST.UserAttributeDeclaration(udas, a);
mod.userAttribDecl = udad;
}
// ModuleDeclation leads off
if (token.value == TOK.module_)
{
const loc = token.loc;
nextToken();
if (token.value != TOK.identifier)
{
error("identifier expected following `module`");
goto Lerr;
}
AST.Identifiers* a = null;
Identifier id = token.ident;
while (nextToken() == TOK.dot)
{
if (!a)
a = new AST.Identifiers();
a.push(id);
nextToken();
if (token.value != TOK.identifier)
{
error("identifier expected following `package`");
goto Lerr;
}
id = token.ident;
}
md = new AST.ModuleDeclaration(loc, a, id, msg, isdeprecated);
if (token.value != TOK.semicolon)
error("`;` expected following module declaration instead of `%s`", token.toChars());
nextToken();
addComment(mod, comment);
}
decldefs = parseDeclDefs(0, &lastDecl);
if (token.value != TOK.endOfFile)
{
error(token.loc, "unrecognized declaration");
goto Lerr;
}
return decldefs;
Lerr:
while (token.value != TOK.semicolon && token.value != TOK.endOfFile)
nextToken();
nextToken();
return new AST.Dsymbols();
}
/**
* Parses a `deprecated` declaration
*
* Params:
* msg = Deprecated message, if any.
* Used to support overriding a deprecated storage class with
* a deprecated declaration with a message, but to error
* if both declaration have a message.
*
* Returns:
* Whether the deprecated declaration has a message
*/
private bool parseDeprecatedAttribute(ref AST.Expression msg)
{
if (peekNext() != TOK.leftParentheses)
return false;
nextToken();
check(TOK.leftParentheses);
AST.Expression e = parseAssignExp();
check(TOK.rightParentheses);
if (msg)
{
error("conflicting storage class `deprecated(%s)` and `deprecated(%s)`", msg.toChars(), e.toChars());
}
msg = e;
return true;
}
AST.Dsymbols* parseDeclDefs(int once, AST.Dsymbol* pLastDecl = null, PrefixAttributes!AST* pAttrs = null)
{
AST.Dsymbol lastDecl = null; // used to link unittest to its previous declaration
if (!pLastDecl)
pLastDecl = &lastDecl;
const linksave = linkage; // save global state
//printf("Parser::parseDeclDefs()\n");
auto decldefs = new AST.Dsymbols();
do
{
// parse result
AST.Dsymbol s = null;
AST.Dsymbols* a = null;
PrefixAttributes!AST attrs;
if (!once || !pAttrs)
{
pAttrs = &attrs;
pAttrs.comment = token.blockComment.ptr;
}
AST.Prot.Kind prot;
StorageClass stc;
AST.Condition condition;
linkage = linksave;
switch (token.value)
{
case TOK.enum_:
{
/* Determine if this is a manifest constant declaration,
* or a conventional enum.
*/
const tv = peekNext();
if (tv == TOK.leftCurly || tv == TOK.colon)
s = parseEnum();
else if (tv != TOK.identifier)
goto Ldeclaration;
else
{
const nextv = peekNext2();
if (nextv == TOK.leftCurly || nextv == TOK.colon || nextv == TOK.semicolon)
s = parseEnum();
else
goto Ldeclaration;
}
break;
}
case TOK.import_:
a = parseImport();
// keep pLastDecl
break;
case TOK.template_:
s = cast(AST.Dsymbol)parseTemplateDeclaration();
break;
case TOK.mixin_:
{
const loc = token.loc;
switch (peekNext())
{
case TOK.leftParentheses:
{
// mixin(string)
nextToken();
auto exps = parseArguments();
check(TOK.semicolon);
s = new AST.CompileDeclaration(loc, exps);
break;
}
case TOK.template_:
// mixin template
nextToken();
s = cast(AST.Dsymbol)parseTemplateDeclaration(true);
break;
default:
s = parseMixin();
break;
}
break;
}
case TOK.wchar_:
case TOK.dchar_:
case TOK.bool_:
case TOK.char_:
case TOK.int8:
case TOK.uns8:
case TOK.int16:
case TOK.uns16:
case TOK.int32:
case TOK.uns32:
case TOK.int64:
case TOK.uns64:
case TOK.int128:
case TOK.uns128:
case TOK.float32:
case TOK.float64:
case TOK.float80:
case TOK.imaginary32:
case TOK.imaginary64:
case TOK.imaginary80:
case TOK.complex32:
case TOK.complex64:
case TOK.complex80:
case TOK.void_:
case TOK.alias_:
case TOK.identifier:
case TOK.super_:
case TOK.typeof_:
case TOK.dot:
case TOK.vector:
case TOK.struct_:
case TOK.union_:
case TOK.class_:
case TOK.interface_:
case TOK.traits:
Ldeclaration:
a = parseDeclarations(false, pAttrs, pAttrs.comment);
if (a && a.dim)
*pLastDecl = (*a)[a.dim - 1];
break;
case TOK.this_:
if (peekNext() == TOK.dot)
goto Ldeclaration;
s = parseCtor(pAttrs);
break;
case TOK.tilde:
s = parseDtor(pAttrs);
break;
case TOK.invariant_:
const tv = peekNext();
if (tv == TOK.leftParentheses || tv == TOK.leftCurly)
{
// invariant { statements... }
// invariant() { statements... }
// invariant (expression);
s = parseInvariant(pAttrs);
break;
}
error("invariant body expected, not `%s`", token.toChars());
goto Lerror;
case TOK.unittest_:
if (global.params.useUnitTests || global.params.doDocComments || global.params.doHdrGeneration)
{
s = parseUnitTest(pAttrs);
if (*pLastDecl)
(*pLastDecl).ddocUnittest = cast(AST.UnitTestDeclaration)s;
}
else
{
// Skip over unittest block by counting { }
Loc loc = token.loc;
int braces = 0;
while (1)
{
nextToken();
switch (token.value)
{
case TOK.leftCurly:
++braces;
continue;
case TOK.rightCurly:
if (--braces)
continue;
nextToken();
break;
case TOK.endOfFile:
/* { */
error(loc, "closing `}` of unittest not found before end of file");
goto Lerror;
default:
continue;
}
break;
}
// Workaround 14894. Add an empty unittest declaration to keep
// the number of symbols in this scope independent of -unittest.
s = new AST.UnitTestDeclaration(loc, token.loc, STC.undefined_, null);
}
break;
case TOK.new_:
s = parseNew(pAttrs);
break;
case TOK.colon:
case TOK.leftCurly:
error("declaration expected, not `%s`", token.toChars());
goto Lerror;
case TOK.rightCurly:
case TOK.endOfFile:
if (once)
error("declaration expected, not `%s`", token.toChars());
return decldefs;
case TOK.static_:
{
const next = peekNext();
if (next == TOK.this_)
s = parseStaticCtor(pAttrs);
else if (next == TOK.tilde)
s = parseStaticDtor(pAttrs);
else if (next == TOK.assert_)
s = parseStaticAssert();
else if (next == TOK.if_)
{
condition = parseStaticIfCondition();
AST.Dsymbols* athen;
if (token.value == TOK.colon)
athen = parseBlock(pLastDecl);
else
{
const lookingForElseSave = lookingForElse;
lookingForElse = token.loc;
athen = parseBlock(pLastDecl);
lookingForElse = lookingForElseSave;
}
AST.Dsymbols* aelse = null;
if (token.value == TOK.else_)
{
const elseloc = token.loc;
nextToken();
aelse = parseBlock(pLastDecl);
checkDanglingElse(elseloc);
}
s = new AST.StaticIfDeclaration(condition, athen, aelse);
}
else if (next == TOK.import_)
{
a = parseImport();
// keep pLastDecl
}
else if (next == TOK.foreach_ || next == TOK.foreach_reverse_)
{
s = parseForeach!(true,true)(token.loc, pLastDecl);
}
else
{
stc = STC.static_;
goto Lstc;
}
break;
}
case TOK.const_:
if (peekNext() == TOK.leftParentheses)
goto Ldeclaration;
stc = STC.const_;
goto Lstc;
case TOK.immutable_:
if (peekNext() == TOK.leftParentheses)
goto Ldeclaration;
stc = STC.immutable_;
goto Lstc;
case TOK.shared_:
{
const next = peekNext();
if (next == TOK.leftParentheses)
goto Ldeclaration;
if (next == TOK.static_)
{
TOK next2 = peekNext2();
if (next2 == TOK.this_)
{
s = parseSharedStaticCtor(pAttrs);
break;
}
if (next2 == TOK.tilde)
{
s = parseSharedStaticDtor(pAttrs);
break;
}
}
stc = STC.shared_;
goto Lstc;
}
case TOK.inout_:
if (peekNext() == TOK.leftParentheses)
goto Ldeclaration;
stc = STC.wild;
goto Lstc;
case TOK.final_:
stc = STC.final_;
goto Lstc;
case TOK.auto_:
stc = STC.auto_;
goto Lstc;
case TOK.scope_:
stc = STC.scope_;
goto Lstc;
case TOK.override_:
stc = STC.override_;
goto Lstc;
case TOK.abstract_:
stc = STC.abstract_;
goto Lstc;
case TOK.synchronized_:
stc = STC.synchronized_;
goto Lstc;
case TOK.nothrow_:
stc = STC.nothrow_;
goto Lstc;
case TOK.pure_:
stc = STC.pure_;
goto Lstc;
case TOK.ref_:
stc = STC.ref_;
goto Lstc;
case TOK.gshared:
stc = STC.gshared;
goto Lstc;
case TOK.at:
{
AST.Expressions* exps = null;
stc = parseAttribute(&exps);
if (stc)
goto Lstc; // it's a predefined attribute
// no redundant/conflicting check for UDAs
pAttrs.udas = AST.UserAttributeDeclaration.concat(pAttrs.udas, exps);
goto Lautodecl;
}
Lstc:
pAttrs.storageClass = appendStorageClass(pAttrs.storageClass, stc);
nextToken();
Lautodecl:
/* Look for auto initializers:
* storage_class identifier = initializer;
* storage_class identifier(...) = initializer;
*/
if (token.value == TOK.identifier && hasOptionalParensThen(peek(&token), TOK.assign))
{
a = parseAutoDeclarations(getStorageClass!AST(pAttrs), pAttrs.comment);
if (a && a.dim)
*pLastDecl = (*a)[a.dim - 1];
if (pAttrs.udas)
{
s = new AST.UserAttributeDeclaration(pAttrs.udas, a);
pAttrs.udas = null;
}
break;
}
/* Look for return type inference for template functions.
*/
Token* tk;
if (token.value == TOK.identifier && skipParens(peek(&token), &tk) && skipAttributes(tk, &tk) &&
(tk.value == TOK.leftParentheses || tk.value == TOK.leftCurly || tk.value == TOK.in_ ||
tk.value == TOK.out_ || tk.value == TOK.do_ ||
tk.value == TOK.identifier && tk.ident == Id._body))
{
version (none)
{
// This deprecation has been disabled for the time being, see PR10763
// @@@DEPRECATED@@@
// https://github.com/dlang/DIPs/blob/1f5959abe482b1f9094f6484a7d0a3ade77fc2fc/DIPs/accepted/DIP1003.md
// Deprecated in 2.091 - Can be removed from 2.101
if (tk.value == TOK.identifier && tk.ident == Id._body)
deprecation("Usage of the `body` keyword is deprecated. Use `do` instead.");
}
a = parseDeclarations(true, pAttrs, pAttrs.comment);
if (a && a.dim)
*pLastDecl = (*a)[a.dim - 1];
if (pAttrs.udas)
{
s = new AST.UserAttributeDeclaration(pAttrs.udas, a);
pAttrs.udas = null;
}
break;
}
a = parseBlock(pLastDecl, pAttrs);
auto stc2 = getStorageClass!AST(pAttrs);
if (stc2 != STC.undefined_)
{
s = new AST.StorageClassDeclaration(stc2, a);
}
if (pAttrs.udas)
{
if (s)
{
a = new AST.Dsymbols();
a.push(s);
}
s = new AST.UserAttributeDeclaration(pAttrs.udas, a);
pAttrs.udas = null;
}
break;
case TOK.deprecated_:
{
stc |= STC.deprecated_;
if (!parseDeprecatedAttribute(pAttrs.depmsg))
goto Lstc;
a = parseBlock(pLastDecl, pAttrs);
s = new AST.DeprecatedDeclaration(pAttrs.depmsg, a);
pAttrs.depmsg = null;
break;
}
case TOK.leftBracket:
{
if (peekNext() == TOK.rightBracket)
error("empty attribute list is not allowed");
error("use `@(attributes)` instead of `[attributes]`");
AST.Expressions* exps = parseArguments();
// no redundant/conflicting check for UDAs
pAttrs.udas = AST.UserAttributeDeclaration.concat(pAttrs.udas, exps);
a = parseBlock(pLastDecl, pAttrs);
if (pAttrs.udas)
{
s = new AST.UserAttributeDeclaration(pAttrs.udas, a);
pAttrs.udas = null;
}
break;
}
case TOK.extern_:
{
if (peekNext() != TOK.leftParentheses)
{
stc = STC.extern_;
goto Lstc;
}
const linkLoc = token.loc;
AST.Identifiers* idents = null;
AST.Expressions* identExps = null;
CPPMANGLE cppmangle;
bool cppMangleOnly = false;
const link = parseLinkage(&idents, &identExps, cppmangle, cppMangleOnly);
if (pAttrs.link != LINK.default_)
{
if (pAttrs.link != link)
{
error("conflicting linkage `extern (%s)` and `extern (%s)`", AST.linkageToChars(pAttrs.link), AST.linkageToChars(link));
}
else if (idents || identExps || cppmangle != CPPMANGLE.def)
{
// Allow:
// extern(C++, foo) extern(C++, bar) void foo();
// to be equivalent with:
// extern(C++, foo.bar) void foo();
// Allow also:
// extern(C++, "ns") extern(C++, class) struct test {}
// extern(C++, class) extern(C++, "ns") struct test {}
}
else
error("redundant linkage `extern (%s)`", AST.linkageToChars(pAttrs.link));
}
pAttrs.link = link;
this.linkage = link;
a = parseBlock(pLastDecl, pAttrs);
if (idents)
{
assert(link == LINK.cpp);
assert(idents.dim);
for (size_t i = idents.dim; i;)
{
Identifier id = (*idents)[--i];
if (s)
{
a = new AST.Dsymbols();
a.push(s);
}
if (cppMangleOnly)
s = new AST.CPPNamespaceDeclaration(id, a);
else
s = new AST.Nspace(linkLoc, id, null, a);
}
pAttrs.link = LINK.default_;
}
else if (identExps)
{
assert(link == LINK.cpp);
assert(identExps.dim);
for (size_t i = identExps.dim; i;)
{
AST.Expression exp = (*identExps)[--i];
if (s)
{
a = new AST.Dsymbols();
a.push(s);
}
if (cppMangleOnly)
s = new AST.CPPNamespaceDeclaration(exp, a);
else
s = new AST.Nspace(linkLoc, null, exp, a);
}
pAttrs.link = LINK.default_;
}
else if (cppmangle != CPPMANGLE.def)
{
assert(link == LINK.cpp);
s = new AST.CPPMangleDeclaration(cppmangle, a);
}
else if (pAttrs.link != LINK.default_)
{
s = new AST.LinkDeclaration(pAttrs.link, a);
pAttrs.link = LINK.default_;
}
break;
}
case TOK.private_:
prot = AST.Prot.Kind.private_;
goto Lprot;
case TOK.package_:
prot = AST.Prot.Kind.package_;
goto Lprot;
case TOK.protected_:
prot = AST.Prot.Kind.protected_;
goto Lprot;
case TOK.public_:
prot = AST.Prot.Kind.public_;
goto Lprot;
case TOK.export_:
prot = AST.Prot.Kind.export_;
goto Lprot;
Lprot:
{
if (pAttrs.protection.kind != AST.Prot.Kind.undefined)
{
if (pAttrs.protection.kind != prot)
error("conflicting protection attribute `%s` and `%s`", AST.protectionToChars(pAttrs.protection.kind), AST.protectionToChars(prot));
else
error("redundant protection attribute `%s`", AST.protectionToChars(prot));
}
pAttrs.protection.kind = prot;
nextToken();
// optional qualified package identifier to bind
// protection to
AST.Identifiers* pkg_prot_idents = null;
if (pAttrs.protection.kind == AST.Prot.Kind.package_ && token.value == TOK.leftParentheses)
{
pkg_prot_idents = parseQualifiedIdentifier("protection package");
if (pkg_prot_idents)
check(TOK.rightParentheses);
else
{
while (token.value != TOK.semicolon && token.value != TOK.endOfFile)
nextToken();
nextToken();
break;
}
}
const attrloc = token.loc;
a = parseBlock(pLastDecl, pAttrs);
if (pAttrs.protection.kind != AST.Prot.Kind.undefined)
{
if (pAttrs.protection.kind == AST.Prot.Kind.package_ && pkg_prot_idents)
s = new AST.ProtDeclaration(attrloc, pkg_prot_idents, a);
else
s = new AST.ProtDeclaration(attrloc, pAttrs.protection, a);
pAttrs.protection = AST.Prot(AST.Prot.Kind.undefined);
}
break;
}
case TOK.align_:
{
const attrLoc = token.loc;
nextToken();
AST.Expression e = null; // default
if (token.value == TOK.leftParentheses)
{
nextToken();
e = parseAssignExp();
check(TOK.rightParentheses);
}
if (pAttrs.setAlignment)
{
if (e)
error("redundant alignment attribute `align(%s)`", e.toChars());
else
error("redundant alignment attribute `align`");
}
pAttrs.setAlignment = true;
pAttrs.ealign = e;
a = parseBlock(pLastDecl, pAttrs);
if (pAttrs.setAlignment)
{
s = new AST.AlignDeclaration(attrLoc, pAttrs.ealign, a);
pAttrs.setAlignment = false;
pAttrs.ealign = null;
}
break;
}
case TOK.pragma_:
{
AST.Expressions* args = null;
const loc = token.loc;
nextToken();
check(TOK.leftParentheses);
if (token.value != TOK.identifier)
{
error("`pragma(identifier)` expected");
goto Lerror;
}
Identifier ident = token.ident;
nextToken();
if (token.value == TOK.comma && peekNext() != TOK.rightParentheses)
args = parseArguments(); // pragma(identifier, args...)
else
check(TOK.rightParentheses); // pragma(identifier)
AST.Dsymbols* a2 = null;
if (token.value == TOK.semicolon)
{
/* https://issues.dlang.org/show_bug.cgi?id=2354
* Accept single semicolon as an empty
* DeclarationBlock following attribute.
*
* Attribute DeclarationBlock
* Pragma DeclDef
* ;
*/
nextToken();
}
else
a2 = parseBlock(pLastDecl);
s = new AST.PragmaDeclaration(loc, ident, args, a2);
break;
}
case TOK.debug_:
nextToken();
if (token.value == TOK.assign)
{
nextToken();
if (token.value == TOK.identifier)
s = new AST.DebugSymbol(token.loc, token.ident);
else if (token.value == TOK.int32Literal || token.value == TOK.int64Literal)
s = new AST.DebugSymbol(token.loc, cast(uint)token.unsvalue);
else
{
error("identifier or integer expected, not `%s`", token.toChars());
s = null;
}
nextToken();
if (token.value != TOK.semicolon)
error("semicolon expected");
nextToken();
break;
}
condition = parseDebugCondition();
goto Lcondition;
case TOK.version_:
nextToken();
if (token.value == TOK.assign)
{
nextToken();
if (token.value == TOK.identifier)
s = new AST.VersionSymbol(token.loc, token.ident);
else if (token.value == TOK.int32Literal || token.value == TOK.int64Literal)
s = new AST.VersionSymbol(token.loc, cast(uint)token.unsvalue);
else
{
error("identifier or integer expected, not `%s`", token.toChars());
s = null;
}
nextToken();
if (token.value != TOK.semicolon)
error("semicolon expected");
nextToken();
break;
}
condition = parseVersionCondition();
goto Lcondition;
Lcondition:
{
AST.Dsymbols* athen;
if (token.value == TOK.colon)
athen = parseBlock(pLastDecl);
else
{
const lookingForElseSave = lookingForElse;
lookingForElse = token.loc;
athen = parseBlock(pLastDecl);
lookingForElse = lookingForElseSave;
}
AST.Dsymbols* aelse = null;
if (token.value == TOK.else_)
{
const elseloc = token.loc;
nextToken();
aelse = parseBlock(pLastDecl);
checkDanglingElse(elseloc);
}
s = new AST.ConditionalDeclaration(condition, athen, aelse);
break;
}
case TOK.semicolon:
// empty declaration
//error("empty declaration");
nextToken();
continue;
default:
error("declaration expected, not `%s`", token.toChars());
Lerror:
while (token.value != TOK.semicolon && token.value != TOK.endOfFile)
nextToken();
nextToken();
s = null;
continue;
}
if (s)
{
if (!s.isAttribDeclaration())
*pLastDecl = s;
decldefs.push(s);
addComment(s, pAttrs.comment);
}
else if (a && a.dim)
{
decldefs.append(a);
}
}
while (!once);
linkage = linksave;
return decldefs;
}
/*****************************************
* Parse auto declarations of the form:
* storageClass ident = init, ident = init, ... ;
* and return the array of them.
* Starts with token on the first ident.
* Ends with scanner past closing ';'
*/
private AST.Dsymbols* parseAutoDeclarations(StorageClass storageClass, const(char)* comment)
{
//printf("parseAutoDeclarations\n");
auto a = new AST.Dsymbols();
while (1)
{
const loc = token.loc;
Identifier ident = token.ident;
nextToken(); // skip over ident
AST.TemplateParameters* tpl = null;
if (token.value == TOK.leftParentheses)
tpl = parseTemplateParameterList();
check(TOK.assign); // skip over '='
AST.Initializer _init = parseInitializer();
auto v = new AST.VarDeclaration(loc, null, ident, _init, storageClass);
AST.Dsymbol s = v;
if (tpl)
{
auto a2 = new AST.Dsymbols();
a2.push(v);
auto tempdecl = new AST.TemplateDeclaration(loc, ident, tpl, null, a2, 0);
s = tempdecl;
}
a.push(s);
switch (token.value)
{
case TOK.semicolon:
nextToken();
addComment(s, comment);
break;
case TOK.comma:
nextToken();
if (!(token.value == TOK.identifier && hasOptionalParensThen(peek(&token), TOK.assign)))
{
error("identifier expected following comma");
break;
}
addComment(s, comment);
continue;
default:
error("semicolon expected following auto declaration, not `%s`", token.toChars());
break;
}
break;
}
return a;
}
/********************************************
* Parse declarations after an align, protection, or extern decl.
*/
private AST.Dsymbols* parseBlock(AST.Dsymbol* pLastDecl, PrefixAttributes!AST* pAttrs = null)
{
AST.Dsymbols* a = null;
//printf("parseBlock()\n");
switch (token.value)
{
case TOK.semicolon:
error("declaration expected following attribute, not `;`");
nextToken();
break;
case TOK.endOfFile:
error("declaration expected following attribute, not end of file");
break;
case TOK.leftCurly:
{
const lookingForElseSave = lookingForElse;
lookingForElse = Loc();
nextToken();
a = parseDeclDefs(0, pLastDecl);
if (token.value != TOK.rightCurly)
{
/* { */
error("matching `}` expected, not `%s`", token.toChars());
}
else
nextToken();
lookingForElse = lookingForElseSave;
break;
}
case TOK.colon:
nextToken();
a = parseDeclDefs(0, pLastDecl); // grab declarations up to closing curly bracket
break;
default:
a = parseDeclDefs(1, pLastDecl, pAttrs);
break;
}
return a;
}
/*********************************************
* Give error on redundant/conflicting storage class.
*/
private StorageClass appendStorageClass(StorageClass storageClass, StorageClass stc)
{
if ((storageClass & stc) || (storageClass & STC.in_ && stc & (STC.const_ | STC.scope_)) || (stc & STC.in_ && storageClass & (STC.const_ | STC.scope_)))
{
OutBuffer buf;
AST.stcToBuffer(&buf, stc);
error("redundant attribute `%s`", buf.peekChars());
return storageClass | stc;
}
storageClass |= stc;
if (stc & (STC.const_ | STC.immutable_ | STC.manifest))
{
StorageClass u = storageClass & (STC.const_ | STC.immutable_ | STC.manifest);
if (u & (u - 1))
error("conflicting attribute `%s`", Token.toChars(token.value));
}
if (stc & (STC.gshared | STC.shared_ | STC.tls))
{
StorageClass u = storageClass & (STC.gshared | STC.shared_ | STC.tls);
if (u & (u - 1))
error("conflicting attribute `%s`", Token.toChars(token.value));
}
if (stc & STC.safeGroup)
{
StorageClass u = storageClass & STC.safeGroup;
if (u & (u - 1))
error("conflicting attribute `@%s`", token.toChars());
}
return storageClass;
}
/***********************************************
* Parse attribute, lexer is on '@'.
* Input:
* pudas array of UDAs to append to
* Returns:
* storage class if a predefined attribute; also scanner remains on identifier.
* 0 if not a predefined attribute
* *pudas set if user defined attribute, scanner is past UDA
* *pudas NULL if not a user defined attribute
*/
private StorageClass parseAttribute(AST.Expressions** pudas)
{
nextToken();
AST.Expressions* udas = null;
StorageClass stc = 0;
if (token.value == TOK.identifier)
{
stc = isBuiltinAtAttribute(token.ident);
if (!stc)
{
// Allow identifier, template instantiation, or function call
AST.Expression exp = parsePrimaryExp();
if (token.value == TOK.leftParentheses)
{
const loc = token.loc;
exp = new AST.CallExp(loc, exp, parseArguments());
}
udas = new AST.Expressions();
udas.push(exp);
}
}
else if (token.value == TOK.leftParentheses)
{
// @( ArgumentList )
// Concatenate with existing
if (peekNext() == TOK.rightParentheses)
error("empty attribute list is not allowed");
udas = parseArguments();
}
else
{
error("@identifier or @(ArgumentList) expected, not `@%s`", token.toChars());
}
if (stc)
{
}
else if (udas)
{
*pudas = AST.UserAttributeDeclaration.concat(*pudas, udas);
}
else
error("valid attributes are `@property`, `@safe`, `@trusted`, `@system`, `@disable`, `@nogc`");
return stc;
}
/***********************************************
* Parse const/immutable/shared/inout/nothrow/pure postfix
*/
private StorageClass parsePostfix(StorageClass storageClass, AST.Expressions** pudas)
{
while (1)
{
StorageClass stc;
switch (token.value)
{
case TOK.const_:
stc = STC.const_;
break;
case TOK.immutable_:
stc = STC.immutable_;
break;
case TOK.shared_:
stc = STC.shared_;
break;
case TOK.inout_:
stc = STC.wild;
break;
case TOK.nothrow_:
stc = STC.nothrow_;
break;
case TOK.pure_:
stc = STC.pure_;
break;
case TOK.return_:
stc = STC.return_;
break;
case TOK.scope_:
stc = STC.scope_;
break;
case TOK.at:
{
AST.Expressions* udas = null;
stc = parseAttribute(&udas);
if (udas)
{
if (pudas)
*pudas = AST.UserAttributeDeclaration.concat(*pudas, udas);
else
{
// Disallow:
// void function() @uda fp;
// () @uda { return 1; }
error("user-defined attributes cannot appear as postfixes");
}
continue;
}
break;
}
default:
return storageClass;
}
storageClass = appendStorageClass(storageClass, stc);
nextToken();
}
}
private StorageClass parseTypeCtor()
{
StorageClass storageClass = STC.undefined_;
while (1)
{
if (peekNext() == TOK.leftParentheses)
return storageClass;
StorageClass stc;
switch (token.value)
{
case TOK.const_:
stc = STC.const_;
break;
case TOK.immutable_:
stc = STC.immutable_;
break;
case TOK.shared_:
stc = STC.shared_;
break;
case TOK.inout_:
stc = STC.wild;
break;
default:
return storageClass;
}
storageClass = appendStorageClass(storageClass, stc);
nextToken();
}
}
/**************************************
* Parse constraint.
* Constraint is of the form:
* if ( ConstraintExpression )
*/
private AST.Expression parseConstraint()
{
AST.Expression e = null;
if (token.value == TOK.if_)
{
nextToken(); // skip over 'if'
check(TOK.leftParentheses);
e = parseExpression();
check(TOK.rightParentheses);
}
return e;
}
/**************************************
* Parse a TemplateDeclaration.
*/
private AST.TemplateDeclaration parseTemplateDeclaration(bool ismixin = false)
{
AST.TemplateDeclaration tempdecl;
Identifier id;
AST.TemplateParameters* tpl;
AST.Dsymbols* decldefs;
AST.Expression constraint = null;
const loc = token.loc;
nextToken();
if (token.value != TOK.identifier)
{
error("identifier expected following `template`");
goto Lerr;
}
id = token.ident;
nextToken();
tpl = parseTemplateParameterList();
if (!tpl)
goto Lerr;
constraint = parseConstraint();
if (token.value != TOK.leftCurly)
{
error("members of template declaration expected");
goto Lerr;
}
decldefs = parseBlock(null);
tempdecl = new AST.TemplateDeclaration(loc, id, tpl, constraint, decldefs, ismixin);
return tempdecl;
Lerr:
return null;
}
/******************************************
* Parse template parameter list.
* Input:
* flag 0: parsing "( list )"
* 1: parsing non-empty "list $(RPAREN)"
*/
private AST.TemplateParameters* parseTemplateParameterList(int flag = 0)
{
auto tpl = new AST.TemplateParameters();
if (!flag && token.value != TOK.leftParentheses)
{
error("parenthesized template parameter list expected following template identifier");
goto Lerr;
}
nextToken();
// Get array of TemplateParameters
if (flag || token.value != TOK.rightParentheses)
{
int isvariadic = 0;
while (token.value != TOK.rightParentheses)
{
AST.TemplateParameter tp;
Loc loc;
Identifier tp_ident = null;
AST.Type tp_spectype = null;
AST.Type tp_valtype = null;
AST.Type tp_defaulttype = null;
AST.Expression tp_specvalue = null;
AST.Expression tp_defaultvalue = null;
// Get TemplateParameter
// First, look ahead to see if it is a TypeParameter or a ValueParameter
const tv = peekNext();
if (token.value == TOK.alias_)
{
// AliasParameter
nextToken();
loc = token.loc; // todo
AST.Type spectype = null;
if (isDeclaration(&token, NeedDeclaratorId.must, TOK.reserved, null))
{
spectype = parseType(&tp_ident);
}
else
{
if (token.value != TOK.identifier)
{
error("identifier expected for template alias parameter");
goto Lerr;
}
tp_ident = token.ident;
nextToken();
}
RootObject spec = null;
if (token.value == TOK.colon) // : Type
{
nextToken();
if (isDeclaration(&token, NeedDeclaratorId.no, TOK.reserved, null))
spec = parseType();
else
spec = parseCondExp();
}
RootObject def = null;
if (token.value == TOK.assign) // = Type
{
nextToken();
if (isDeclaration(&token, NeedDeclaratorId.no, TOK.reserved, null))
def = parseType();
else
def = parseCondExp();
}
tp = new AST.TemplateAliasParameter(loc, tp_ident, spectype, spec, def);
}
else if (tv == TOK.colon || tv == TOK.assign || tv == TOK.comma || tv == TOK.rightParentheses)
{
// TypeParameter
if (token.value != TOK.identifier)
{
error("identifier expected for template type parameter");
goto Lerr;
}
loc = token.loc;
tp_ident = token.ident;
nextToken();
if (token.value == TOK.colon) // : Type
{
nextToken();
tp_spectype = parseType();
}
if (token.value == TOK.assign) // = Type
{
nextToken();
tp_defaulttype = parseType();
}
tp = new AST.TemplateTypeParameter(loc, tp_ident, tp_spectype, tp_defaulttype);
}
else if (token.value == TOK.identifier && tv == TOK.dotDotDot)
{
// ident...
if (isvariadic)
error("variadic template parameter must be last");
isvariadic = 1;
loc = token.loc;
tp_ident = token.ident;
nextToken();
nextToken();
tp = new AST.TemplateTupleParameter(loc, tp_ident);
}
else if (token.value == TOK.this_)
{
// ThisParameter
nextToken();
if (token.value != TOK.identifier)
{
error("identifier expected for template this parameter");
goto Lerr;
}
loc = token.loc;
tp_ident = token.ident;
nextToken();
if (token.value == TOK.colon) // : Type
{
nextToken();
tp_spectype = parseType();
}
if (token.value == TOK.assign) // = Type
{
nextToken();
tp_defaulttype = parseType();
}
tp = new AST.TemplateThisParameter(loc, tp_ident, tp_spectype, tp_defaulttype);
}
else
{
// ValueParameter
loc = token.loc; // todo
tp_valtype = parseType(&tp_ident);
if (!tp_ident)
{
error("identifier expected for template value parameter");
tp_ident = Identifier.idPool("error");
}
if (token.value == TOK.colon) // : CondExpression
{
nextToken();
tp_specvalue = parseCondExp();
}
if (token.value == TOK.assign) // = CondExpression
{
nextToken();
tp_defaultvalue = parseDefaultInitExp();
}
tp = new AST.TemplateValueParameter(loc, tp_ident, tp_valtype, tp_specvalue, tp_defaultvalue);
}
tpl.push(tp);
if (token.value != TOK.comma)
break;
nextToken();
}
}
check(TOK.rightParentheses);
Lerr:
return tpl;
}
/******************************************
* Parse template mixin.
* mixin Foo;
* mixin Foo!(args);
* mixin a.b.c!(args).Foo!(args);
* mixin Foo!(args) identifier;
* mixin typeof(expr).identifier!(args);
*/
private AST.Dsymbol parseMixin()
{
AST.TemplateMixin tm;
Identifier id;
AST.Objects* tiargs;
//printf("parseMixin()\n");
const locMixin = token.loc;
nextToken(); // skip 'mixin'
auto loc = token.loc;
AST.TypeQualified tqual = null;
if (token.value == TOK.dot)
{
id = Id.empty;
}
else
{
if (token.value == TOK.typeof_)
{
tqual = parseTypeof();
check(TOK.dot);
}
if (token.value != TOK.identifier)
{
error("identifier expected, not `%s`", token.toChars());
id = Id.empty;
}
else
id = token.ident;
nextToken();
}
while (1)
{
tiargs = null;
if (token.value == TOK.not)
{
tiargs = parseTemplateArguments();
}
if (tiargs && token.value == TOK.dot)
{
auto tempinst = new AST.TemplateInstance(loc, id, tiargs);
if (!tqual)
tqual = new AST.TypeInstance(loc, tempinst);
else
tqual.addInst(tempinst);
tiargs = null;
}
else
{
if (!tqual)
tqual = new AST.TypeIdentifier(loc, id);
else
tqual.addIdent(id);
}
if (token.value != TOK.dot)
break;
nextToken();
if (token.value != TOK.identifier)
{
error("identifier expected following `.` instead of `%s`", token.toChars());
break;
}
loc = token.loc;
id = token.ident;
nextToken();
}
id = null;
if (token.value == TOK.identifier)
{
id = token.ident;
nextToken();
}
tm = new AST.TemplateMixin(locMixin, id, tqual, tiargs);
if (token.value != TOK.semicolon)
error("`;` expected after mixin");
nextToken();
return tm;
}
/******************************************
* Parse template arguments.
* Input:
* current token is opening '!'
* Output:
* current token is one after closing '$(RPAREN)'
*/
private AST.Objects* parseTemplateArguments()
{
AST.Objects* tiargs;
nextToken();
if (token.value == TOK.leftParentheses)
{
// ident!(template_arguments)
tiargs = parseTemplateArgumentList();
}
else
{
// ident!template_argument
tiargs = parseTemplateSingleArgument();
}
if (token.value == TOK.not)
{
TOK tok = peekNext();
if (tok != TOK.is_ && tok != TOK.in_)
{
error("multiple ! arguments are not allowed");
Lagain:
nextToken();
if (token.value == TOK.leftParentheses)
parseTemplateArgumentList();
else
parseTemplateSingleArgument();
if (token.value == TOK.not && (tok = peekNext()) != TOK.is_ && tok != TOK.in_)
goto Lagain;
}
}
return tiargs;
}
/******************************************
* Parse template argument list.
* Input:
* current token is opening '$(LPAREN)',
* or ',' for __traits
* Output:
* current token is one after closing '$(RPAREN)'
*/
private AST.Objects* parseTemplateArgumentList()
{
//printf("Parser::parseTemplateArgumentList()\n");
auto tiargs = new AST.Objects();
TOK endtok = TOK.rightParentheses;
assert(token.value == TOK.leftParentheses || token.value == TOK.comma);
nextToken();
// Get TemplateArgumentList
while (token.value != endtok)
{
tiargs.push(parseTypeOrAssignExp());
if (token.value != TOK.comma)
break;
nextToken();
}
check(endtok, "template argument list");
return tiargs;
}
/***************************************
* Parse a Type or an Expression
* Returns:
* RootObject representing the AST
*/
RootObject parseTypeOrAssignExp(TOK endtoken = TOK.reserved)
{
return isDeclaration(&token, NeedDeclaratorId.no, endtoken, null)
? parseType() // argument is a type
: parseAssignExp(); // argument is an expression
}
/*****************************
* Parse single template argument, to support the syntax:
* foo!arg
* Input:
* current token is the arg
*/
private AST.Objects* parseTemplateSingleArgument()
{
//printf("parseTemplateSingleArgument()\n");
auto tiargs = new AST.Objects();
AST.Type ta;
switch (token.value)
{
case TOK.identifier:
ta = new AST.TypeIdentifier(token.loc, token.ident);
goto LabelX;
case TOK.vector:
ta = parseVector();
goto LabelX;
case TOK.void_:
ta = AST.Type.tvoid;
goto LabelX;
case TOK.int8:
ta = AST.Type.tint8;
goto LabelX;
case TOK.uns8:
ta = AST.Type.tuns8;
goto LabelX;
case TOK.int16:
ta = AST.Type.tint16;
goto LabelX;
case TOK.uns16:
ta = AST.Type.tuns16;
goto LabelX;
case TOK.int32:
ta = AST.Type.tint32;
goto LabelX;
case TOK.uns32:
ta = AST.Type.tuns32;
goto LabelX;
case TOK.int64:
ta = AST.Type.tint64;
goto LabelX;
case TOK.uns64:
ta = AST.Type.tuns64;
goto LabelX;
case TOK.int128:
ta = AST.Type.tint128;
goto LabelX;
case TOK.uns128:
ta = AST.Type.tuns128;
goto LabelX;
case TOK.float32:
ta = AST.Type.tfloat32;
goto LabelX;
case TOK.float64:
ta = AST.Type.tfloat64;
goto LabelX;
case TOK.float80:
ta = AST.Type.tfloat80;
goto LabelX;
case TOK.imaginary32:
ta = AST.Type.timaginary32;
goto LabelX;
case TOK.imaginary64:
ta = AST.Type.timaginary64;
goto LabelX;
case TOK.imaginary80:
ta = AST.Type.timaginary80;
goto LabelX;
case TOK.complex32:
ta = AST.Type.tcomplex32;
goto LabelX;
case TOK.complex64:
ta = AST.Type.tcomplex64;
goto LabelX;
case TOK.complex80:
ta = AST.Type.tcomplex80;
goto LabelX;
case TOK.bool_:
ta = AST.Type.tbool;
goto LabelX;
case TOK.char_:
ta = AST.Type.tchar;
goto LabelX;
case TOK.wchar_:
ta = AST.Type.twchar;
goto LabelX;
case TOK.dchar_:
ta = AST.Type.tdchar;
goto LabelX;
LabelX:
tiargs.push(ta);
nextToken();
break;
case TOK.int32Literal:
case TOK.uns32Literal:
case TOK.int64Literal:
case TOK.uns64Literal:
case TOK.int128Literal:
case TOK.uns128Literal:
case TOK.float32Literal:
case TOK.float64Literal:
case TOK.float80Literal:
case TOK.imaginary32Literal:
case TOK.imaginary64Literal:
case TOK.imaginary80Literal:
case TOK.null_:
case TOK.true_:
case TOK.false_:
case TOK.charLiteral:
case TOK.wcharLiteral:
case TOK.dcharLiteral:
case TOK.string_:
case TOK.hexadecimalString:
case TOK.file:
case TOK.fileFullPath:
case TOK.line:
case TOK.moduleString:
case TOK.functionString:
case TOK.prettyFunction:
case TOK.this_:
{
// Template argument is an expression
AST.Expression ea = parsePrimaryExp();
tiargs.push(ea);
break;
}
default:
error("template argument expected following `!`");
break;
}
return tiargs;
}
/**********************************
* Parse a static assertion.
* Current token is 'static'.
*/
private AST.StaticAssert parseStaticAssert()
{
const loc = token.loc;
AST.Expression exp;
AST.Expression msg = null;
//printf("parseStaticAssert()\n");
nextToken();
nextToken();
check(TOK.leftParentheses);
exp = parseAssignExp();
if (token.value == TOK.comma)
{
nextToken();
if (token.value != TOK.rightParentheses)
{
msg = parseAssignExp();
if (token.value == TOK.comma)
nextToken();
}
}
check(TOK.rightParentheses);
check(TOK.semicolon);
return new AST.StaticAssert(loc, exp, msg);
}
/***********************************
* Parse typeof(expression).
* Current token is on the 'typeof'.
*/
private AST.TypeQualified parseTypeof()
{
AST.TypeQualified t;
const loc = token.loc;
nextToken();
check(TOK.leftParentheses);
if (token.value == TOK.return_) // typeof(return)
{
nextToken();
t = new AST.TypeReturn(loc);
}
else
{
AST.Expression exp = parseExpression(); // typeof(expression)
t = new AST.TypeTypeof(loc, exp);
}
check(TOK.rightParentheses);
return t;
}
/***********************************
* Parse __vector(type).
* Current token is on the '__vector'.
*/
private AST.Type parseVector()
{
nextToken();
check(TOK.leftParentheses);
AST.Type tb = parseType();
check(TOK.rightParentheses);
return new AST.TypeVector(tb);
}
/***********************************
* Parse:
* extern (linkage)
* extern (C++, namespaces)
* extern (C++, "namespace", "namespaces", ...)
* extern (C++, (StringExp))
* The parser is on the 'extern' token.
*/
private LINK parseLinkage(AST.Identifiers** pidents, AST.Expressions** pIdentExps, out CPPMANGLE cppmangle, out bool cppMangleOnly)
{
AST.Identifiers* idents = null;
AST.Expressions* identExps = null;
cppmangle = CPPMANGLE.def;
LINK link = LINK.d; // default
nextToken();
assert(token.value == TOK.leftParentheses);
nextToken();
if (token.value == TOK.identifier)
{
Identifier id = token.ident;
nextToken();
if (id == Id.Windows)
link = LINK.windows;
else if (id == Id.Pascal)
{
deprecation("`extern(Pascal)` is deprecated. You might want to use `extern(Windows)` instead.");
link = LINK.pascal;
}
else if (id == Id.D)
{ /* already set */}
else if (id == Id.C)
{
link = LINK.c;
if (token.value == TOK.plusPlus)
{
link = LINK.cpp;
nextToken();
if (token.value == TOK.comma) // , namespaces or class or struct
{
nextToken();
if (token.value == TOK.class_ || token.value == TOK.struct_)
{
cppmangle = token.value == TOK.class_ ? CPPMANGLE.asClass : CPPMANGLE.asStruct;
nextToken();
}
else if (token.value == TOK.identifier) // named scope namespace
{
idents = new AST.Identifiers();
while (1)
{
Identifier idn = token.ident;
idents.push(idn);
nextToken();
if (token.value == TOK.dot)
{
nextToken();
if (token.value == TOK.identifier)
continue;
error("identifier expected for C++ namespace");
idents = null; // error occurred, invalidate list of elements.
}
break;
}
}
else // non-scoped StringExp namespace
{
cppMangleOnly = true;
identExps = new AST.Expressions();
while (1)
{
identExps.push(parseCondExp());
if (token.value != TOK.comma)
break;
nextToken();
}
}
}
}
}
else if (id == Id.Objective) // Looking for tokens "Objective-C"
{
if (token.value == TOK.min)
{
nextToken();
if (token.ident == Id.C)
{
link = LINK.objc;
nextToken();
}
else
goto LinvalidLinkage;
}
else
goto LinvalidLinkage;
}
else if (id == Id.System)
{
link = LINK.system;
}
else
{
LinvalidLinkage:
error("valid linkage identifiers are `D`, `C`, `C++`, `Objective-C`, `Pascal`, `Windows`, `System`");
link = LINK.d;
}
}
check(TOK.rightParentheses);
*pidents = idents;
*pIdentExps = identExps;
return link;
}
/***********************************
* Parse ident1.ident2.ident3
*
* Params:
* entity = what qualified identifier is expected to resolve into.
* Used only for better error message
*
* Returns:
* array of identifiers with actual qualified one stored last
*/
private AST.Identifiers* parseQualifiedIdentifier(const(char)* entity)
{
AST.Identifiers* qualified = null;
do
{
nextToken();
if (token.value != TOK.identifier)
{
error("`%s` expected as dot-separated identifiers, got `%s`", entity, token.toChars());
return null;
}
Identifier id = token.ident;
if (!qualified)
qualified = new AST.Identifiers();
qualified.push(id);
nextToken();
}
while (token.value == TOK.dot);
return qualified;
}
/**************************************
* Parse a debug conditional
*/
private AST.Condition parseDebugCondition()
{
uint level = 1;
Identifier id = null;
if (token.value == TOK.leftParentheses)
{
nextToken();
if (token.value == TOK.identifier)
id = token.ident;
else if (token.value == TOK.int32Literal || token.value == TOK.int64Literal)
level = cast(uint)token.unsvalue;
else
error("identifier or integer expected inside debug(...), not `%s`", token.toChars());
nextToken();
check(TOK.rightParentheses);
}
return new AST.DebugCondition(mod, level, id);
}
/**************************************
* Parse a version conditional
*/
private AST.Condition parseVersionCondition()
{
uint level = 1;
Identifier id = null;
if (token.value == TOK.leftParentheses)
{
nextToken();
/* Allow:
* version (unittest)
* version (assert)
* even though they are keywords
*/
if (token.value == TOK.identifier)
id = token.ident;
else if (token.value == TOK.int32Literal || token.value == TOK.int64Literal)
level = cast(uint)token.unsvalue;
else if (token.value == TOK.unittest_)
id = Identifier.idPool(Token.toString(TOK.unittest_));
else if (token.value == TOK.assert_)
id = Identifier.idPool(Token.toString(TOK.assert_));
else
error("identifier or integer expected inside version(...), not `%s`", token.toChars());
nextToken();
check(TOK.rightParentheses);
}
else
error("(condition) expected following `version`");
return new AST.VersionCondition(mod, level, id);
}
/***********************************************
* static if (expression)
* body
* else
* body
* Current token is 'static'.
*/
private AST.Condition parseStaticIfCondition()
{
AST.Expression exp;
AST.Condition condition;
const loc = token.loc;
nextToken();
nextToken();
if (token.value == TOK.leftParentheses)
{
nextToken();
exp = parseAssignExp();
check(TOK.rightParentheses);
}
else
{
error("(expression) expected following `static if`");
exp = null;
}
condition = new AST.StaticIfCondition(loc, exp);
return condition;
}
/*****************************************
* Parse a constructor definition:
* this(parameters) { body }
* or postblit:
* this(this) { body }
* or constructor template:
* this(templateparameters)(parameters) { body }
* Current token is 'this'.
*/
private AST.Dsymbol parseCtor(PrefixAttributes!AST* pAttrs)
{
AST.Expressions* udas = null;
const loc = token.loc;
StorageClass stc = getStorageClass!AST(pAttrs);
nextToken();
if (token.value == TOK.leftParentheses && peekNext() == TOK.this_ && peekNext2() == TOK.rightParentheses)
{
// this(this) { ... }
nextToken();
nextToken();
check(TOK.rightParentheses);
stc = parsePostfix(stc, &udas);
if (stc & STC.immutable_)
deprecation("`immutable` postblit is deprecated. Please use an unqualified postblit.");
if (stc & STC.shared_)
deprecation("`shared` postblit is deprecated. Please use an unqualified postblit.");
if (stc & STC.const_)
deprecation("`const` postblit is deprecated. Please use an unqualified postblit.");
if (stc & STC.static_)
error(loc, "postblit cannot be `static`");
auto f = new AST.PostBlitDeclaration(loc, Loc.initial, stc, Id.postblit);
AST.Dsymbol s = parseContracts(f);
if (udas)
{
auto a = new AST.Dsymbols();
a.push(f);
s = new AST.UserAttributeDeclaration(udas, a);
}
return s;
}
/* Look ahead to see if:
* this(...)(...)
* which is a constructor template
*/
AST.TemplateParameters* tpl = null;
if (token.value == TOK.leftParentheses && peekPastParen(&token).value == TOK.leftParentheses)
{
tpl = parseTemplateParameterList();
}
/* Just a regular constructor
*/
AST.VarArg varargs;
AST.Parameters* parameters = parseParameters(&varargs);
stc = parsePostfix(stc, &udas);
if (varargs != AST.VarArg.none || AST.Parameter.dim(parameters) != 0)
{
if (stc & STC.static_)
error(loc, "constructor cannot be static");
}
else if (StorageClass ss = stc & (STC.shared_ | STC.static_)) // this()
{
if (ss == STC.static_)
error(loc, "use `static this()` to declare a static constructor");
else if (ss == (STC.shared_ | STC.static_))
error(loc, "use `shared static this()` to declare a shared static constructor");
}
AST.Expression constraint = tpl ? parseConstraint() : null;
AST.Type tf = new AST.TypeFunction(AST.ParameterList(parameters, varargs), null, linkage, stc); // RetrunType -> auto
tf = tf.addSTC(stc);
auto f = new AST.CtorDeclaration(loc, Loc.initial, stc, tf);
AST.Dsymbol s = parseContracts(f);
if (udas)
{
auto a = new AST.Dsymbols();
a.push(f);
s = new AST.UserAttributeDeclaration(udas, a);
}
if (tpl)
{
// Wrap a template around it
auto decldefs = new AST.Dsymbols();
decldefs.push(s);
s = new AST.TemplateDeclaration(loc, f.ident, tpl, constraint, decldefs);
}
return s;
}
/*****************************************
* Parse a destructor definition:
* ~this() { body }
* Current token is '~'.
*/
private AST.Dsymbol parseDtor(PrefixAttributes!AST* pAttrs)
{
AST.Expressions* udas = null;
const loc = token.loc;
StorageClass stc = getStorageClass!AST(pAttrs);
nextToken();
check(TOK.this_);
check(TOK.leftParentheses);
check(TOK.rightParentheses);
stc = parsePostfix(stc, &udas);
if (StorageClass ss = stc & (STC.shared_ | STC.static_))
{
if (ss == STC.static_)
error(loc, "use `static ~this()` to declare a static destructor");
else if (ss == (STC.shared_ | STC.static_))
error(loc, "use `shared static ~this()` to declare a shared static destructor");
}
auto f = new AST.DtorDeclaration(loc, Loc.initial, stc, Id.dtor);
AST.Dsymbol s = parseContracts(f);
if (udas)
{
auto a = new AST.Dsymbols();
a.push(f);
s = new AST.UserAttributeDeclaration(udas, a);
}
return s;
}
/*****************************************
* Parse a static constructor definition:
* static this() { body }
* Current token is 'static'.
*/
private AST.Dsymbol parseStaticCtor(PrefixAttributes!AST* pAttrs)
{
//Expressions *udas = NULL;
const loc = token.loc;
StorageClass stc = getStorageClass!AST(pAttrs);
nextToken();
nextToken();
check(TOK.leftParentheses);
check(TOK.rightParentheses);
stc = parsePostfix(stc & ~STC.TYPECTOR, null) | stc;
if (stc & STC.shared_)
error(loc, "use `shared static this()` to declare a shared static constructor");
else if (stc & STC.static_)
appendStorageClass(stc, STC.static_); // complaint for the redundancy
else if (StorageClass modStc = stc & STC.TYPECTOR)
{
OutBuffer buf;
AST.stcToBuffer(&buf, modStc);
error(loc, "static constructor cannot be `%s`", buf.peekChars());
}
stc &= ~(STC.static_ | STC.TYPECTOR);
auto f = new AST.StaticCtorDeclaration(loc, Loc.initial, stc);
AST.Dsymbol s = parseContracts(f);
return s;
}
/*****************************************
* Parse a static destructor definition:
* static ~this() { body }
* Current token is 'static'.
*/
private AST.Dsymbol parseStaticDtor(PrefixAttributes!AST* pAttrs)
{
AST.Expressions* udas = null;
const loc = token.loc;
StorageClass stc = getStorageClass!AST(pAttrs);
nextToken();
nextToken();
check(TOK.this_);
check(TOK.leftParentheses);
check(TOK.rightParentheses);
stc = parsePostfix(stc & ~STC.TYPECTOR, &udas) | stc;
if (stc & STC.shared_)
error(loc, "use `shared static ~this()` to declare a shared static destructor");
else if (stc & STC.static_)
appendStorageClass(stc, STC.static_); // complaint for the redundancy
else if (StorageClass modStc = stc & STC.TYPECTOR)
{
OutBuffer buf;
AST.stcToBuffer(&buf, modStc);
error(loc, "static destructor cannot be `%s`", buf.peekChars());
}
stc &= ~(STC.static_ | STC.TYPECTOR);
auto f = new AST.StaticDtorDeclaration(loc, Loc.initial, stc);
AST.Dsymbol s = parseContracts(f);
if (udas)
{
auto a = new AST.Dsymbols();
a.push(f);
s = new AST.UserAttributeDeclaration(udas, a);
}
return s;
}
/*****************************************
* Parse a shared static constructor definition:
* shared static this() { body }
* Current token is 'shared'.
*/
private AST.Dsymbol parseSharedStaticCtor(PrefixAttributes!AST* pAttrs)
{
//Expressions *udas = NULL;
const loc = token.loc;
StorageClass stc = getStorageClass!AST(pAttrs);
nextToken();
nextToken();
nextToken();
check(TOK.leftParentheses);
check(TOK.rightParentheses);
stc = parsePostfix(stc & ~STC.TYPECTOR, null) | stc;
if (StorageClass ss = stc & (STC.shared_ | STC.static_))
appendStorageClass(stc, ss); // complaint for the redundancy
else if (StorageClass modStc = stc & STC.TYPECTOR)
{
OutBuffer buf;
AST.stcToBuffer(&buf, modStc);
error(loc, "shared static constructor cannot be `%s`", buf.peekChars());
}
stc &= ~(STC.static_ | STC.TYPECTOR);
auto f = new AST.SharedStaticCtorDeclaration(loc, Loc.initial, stc);
AST.Dsymbol s = parseContracts(f);
return s;
}
/*****************************************
* Parse a shared static destructor definition:
* shared static ~this() { body }
* Current token is 'shared'.
*/
private AST.Dsymbol parseSharedStaticDtor(PrefixAttributes!AST* pAttrs)
{
AST.Expressions* udas = null;
const loc = token.loc;
StorageClass stc = getStorageClass!AST(pAttrs);
nextToken();
nextToken();
nextToken();
check(TOK.this_);
check(TOK.leftParentheses);
check(TOK.rightParentheses);
stc = parsePostfix(stc & ~STC.TYPECTOR, &udas) | stc;
if (StorageClass ss = stc & (STC.shared_ | STC.static_))
appendStorageClass(stc, ss); // complaint for the redundancy
else if (StorageClass modStc = stc & STC.TYPECTOR)
{
OutBuffer buf;
AST.stcToBuffer(&buf, modStc);
error(loc, "shared static destructor cannot be `%s`", buf.peekChars());
}
stc &= ~(STC.static_ | STC.TYPECTOR);
auto f = new AST.SharedStaticDtorDeclaration(loc, Loc.initial, stc);
AST.Dsymbol s = parseContracts(f);
if (udas)
{
auto a = new AST.Dsymbols();
a.push(f);
s = new AST.UserAttributeDeclaration(udas, a);
}
return s;
}
/*****************************************
* Parse an invariant definition:
* invariant { statements... }
* invariant() { statements... }
* invariant (expression);
* Current token is 'invariant'.
*/
private AST.Dsymbol parseInvariant(PrefixAttributes!AST* pAttrs)
{
const loc = token.loc;
StorageClass stc = getStorageClass!AST(pAttrs);
nextToken();
if (token.value == TOK.leftParentheses) // optional () or invariant (expression);
{
nextToken();
if (token.value != TOK.rightParentheses) // invariant (expression);
{
AST.Expression e = parseAssignExp(), msg = null;
if (token.value == TOK.comma)
{
nextToken();
if (token.value != TOK.rightParentheses)
{
msg = parseAssignExp();
if (token.value == TOK.comma)
nextToken();
}
}
check(TOK.rightParentheses);
check(TOK.semicolon);
e = new AST.AssertExp(loc, e, msg);
auto fbody = new AST.ExpStatement(loc, e);
auto f = new AST.InvariantDeclaration(loc, token.loc, stc, null, fbody);
return f;
}
nextToken();
}
auto fbody = parseStatement(ParseStatementFlags.curly);
auto f = new AST.InvariantDeclaration(loc, token.loc, stc, null, fbody);
return f;
}
/*****************************************
* Parse a unittest definition:
* unittest { body }
* Current token is 'unittest'.
*/
private AST.Dsymbol parseUnitTest(PrefixAttributes!AST* pAttrs)
{
const loc = token.loc;
StorageClass stc = getStorageClass!AST(pAttrs);
nextToken();
const(char)* begPtr = token.ptr + 1; // skip '{'
const(char)* endPtr = null;
AST.Statement sbody = parseStatement(ParseStatementFlags.curly, &endPtr);
/** Extract unittest body as a string. Must be done eagerly since memory
will be released by the lexer before doc gen. */
char* docline = null;
if (global.params.doDocComments && endPtr > begPtr)
{
/* Remove trailing whitespaces */
for (const(char)* p = endPtr - 1; begPtr <= p && (*p == ' ' || *p == '\r' || *p == '\n' || *p == '\t'); --p)
{
endPtr = p;
}
size_t len = endPtr - begPtr;
if (len > 0)
{
docline = cast(char*)mem.xmalloc_noscan(len + 2);
memcpy(docline, begPtr, len);
docline[len] = '\n'; // Terminate all lines by LF
docline[len + 1] = '\0';
}
}
auto f = new AST.UnitTestDeclaration(loc, token.loc, stc, docline);
f.fbody = sbody;
return f;
}
/*****************************************
* Parse a new definition:
* new(parameters) { body }
* Current token is 'new'.
*/
private AST.Dsymbol parseNew(PrefixAttributes!AST* pAttrs)
{
const loc = token.loc;
StorageClass stc = getStorageClass!AST(pAttrs);
nextToken();
AST.VarArg varargs;
AST.Parameters* parameters = parseParameters(&varargs);
auto f = new AST.NewDeclaration(loc, Loc.initial, stc, parameters, varargs);
AST.Dsymbol s = parseContracts(f);
return s;
}
/**********************************************
* Parse parameter list.
*/
private AST.Parameters* parseParameters(AST.VarArg* pvarargs, AST.TemplateParameters** tpl = null)
{
auto parameters = new AST.Parameters();
AST.VarArg varargs = AST.VarArg.none;
int hasdefault = 0;
check(TOK.leftParentheses);
while (1)
{
Identifier ai = null;
AST.Type at;
StorageClass storageClass = 0;
StorageClass stc;
AST.Expression ae;
AST.Expressions* udas = null;
for (; 1; nextToken())
{
L3:
switch (token.value)
{
case TOK.rightParentheses:
if (storageClass != 0 || udas !is null)
error("basic type expected, not `)`");
break;
case TOK.dotDotDot:
varargs = AST.VarArg.variadic;
nextToken();
break;
case TOK.const_:
if (peekNext() == TOK.leftParentheses)
goto default;
stc = STC.const_;
goto L2;
case TOK.immutable_:
if (peekNext() == TOK.leftParentheses)
goto default;
stc = STC.immutable_;
goto L2;
case TOK.shared_:
if (peekNext() == TOK.leftParentheses)
goto default;
stc = STC.shared_;
goto L2;
case TOK.inout_:
if (peekNext() == TOK.leftParentheses)
goto default;
stc = STC.wild;
goto L2;
case TOK.at:
{
AST.Expressions* exps = null;
StorageClass stc2 = parseAttribute(&exps);
if (stc2 & atAttrGroup)
{
error("`@%s` attribute for function parameter is not supported", token.toChars());
}
else
{
udas = AST.UserAttributeDeclaration.concat(udas, exps);
}
if (token.value == TOK.dotDotDot)
error("variadic parameter cannot have user-defined attributes");
if (stc2)
nextToken();
goto L3;
// Don't call nextToken again.
}
case TOK.in_:
stc = STC.in_;
goto L2;
case TOK.out_:
stc = STC.out_;
goto L2;
case TOK.ref_:
stc = STC.ref_;
goto L2;
case TOK.lazy_:
stc = STC.lazy_;
goto L2;
case TOK.scope_:
stc = STC.scope_;
goto L2;
case TOK.final_:
stc = STC.final_;
goto L2;
case TOK.auto_:
stc = STC.auto_;
goto L2;
case TOK.return_:
stc = STC.return_;
goto L2;
L2:
storageClass = appendStorageClass(storageClass, stc);
continue;
version (none)
{
case TOK.static_:
stc = STC.static_;
goto L2;
case TOK.auto_:
storageClass = STC.auto_;
goto L4;
case TOK.alias_:
storageClass = STC.alias_;
goto L4;
L4:
nextToken();
ai = null;
if (token.value == TOK.identifier)
{
ai = token.ident;
nextToken();
}
at = null; // no type
ae = null; // no default argument
if (token.value == TOK.assign) // = defaultArg
{
nextToken();
ae = parseDefaultInitExp();
hasdefault = 1;
}
else
{
if (hasdefault)
error("default argument expected for `alias %s`", ai ? ai.toChars() : "");
}
goto L3;
}
default:
{
stc = storageClass & (STC.in_ | STC.out_ | STC.ref_ | STC.lazy_);
// if stc is not a power of 2
if (stc & (stc - 1) && !(stc == (STC.in_ | STC.ref_)))
error("incompatible parameter storage classes");
//if ((storageClass & STC.scope_) && (storageClass & (STC.ref_ | STC.out_)))
//error("scope cannot be ref or out");
if (tpl && token.value == TOK.identifier)
{
const tv = peekNext();
if (tv == TOK.comma || tv == TOK.rightParentheses || tv == TOK.dotDotDot)
{
Identifier id = Identifier.generateId("__T");
const loc = token.loc;
at = new AST.TypeIdentifier(loc, id);
if (!*tpl)
*tpl = new AST.TemplateParameters();
AST.TemplateParameter tp = new AST.TemplateTypeParameter(loc, id, null, null);
(*tpl).push(tp);
ai = token.ident;
nextToken();
}
else goto _else;
}
else
{
_else:
at = parseType(&ai);
}
ae = null;
if (token.value == TOK.assign) // = defaultArg
{
nextToken();
ae = parseDefaultInitExp();
hasdefault = 1;
}
else
{
if (hasdefault)
error("default argument expected for `%s`", ai ? ai.toChars() : at.toChars());
}
auto param = new AST.Parameter(storageClass, at, ai, ae, null);
if (udas)
{
auto a = new AST.Dsymbols();
auto udad = new AST.UserAttributeDeclaration(udas, a);
param.userAttribDecl = udad;
}
if (token.value == TOK.at)
{
AST.Expressions* exps = null;
StorageClass stc2 = parseAttribute(&exps);
if (stc2 & atAttrGroup)
{
error("`@%s` attribute for function parameter is not supported", token.toChars());
}
else
{
error("user-defined attributes cannot appear as postfixes", token.toChars());
}
if (stc2)
nextToken();
}
if (token.value == TOK.dotDotDot)
{
/* This is:
* at ai ...
*/
if (storageClass & (STC.out_ | STC.ref_))
error("variadic argument cannot be `out` or `ref`");
varargs = AST.VarArg.typesafe;
parameters.push(param);
nextToken();
break;
}
parameters.push(param);
if (token.value == TOK.comma)
{
nextToken();
goto L1;
}
break;
}
}
break;
}
break;
L1:
}
check(TOK.rightParentheses);
*pvarargs = varargs;
return parameters;
}
/*************************************
*/
private AST.EnumDeclaration parseEnum()
{
AST.EnumDeclaration e;
Identifier id;
AST.Type memtype;
auto loc = token.loc;
// printf("Parser::parseEnum()\n");
nextToken();
id = null;
if (token.value == TOK.identifier)
{
id = token.ident;
nextToken();
}
memtype = null;
if (token.value == TOK.colon)
{
nextToken();
int alt = 0;
const typeLoc = token.loc;
memtype = parseBasicType();
memtype = parseDeclarator(memtype, &alt, null);
checkCstyleTypeSyntax(typeLoc, memtype, alt, null);
}
e = new AST.EnumDeclaration(loc, id, memtype);
if (token.value == TOK.semicolon && id)
nextToken();
else if (token.value == TOK.leftCurly)
{
bool isAnonymousEnum = !id;
TOK prevTOK;
//printf("enum definition\n");
e.members = new AST.Dsymbols();
nextToken();
const(char)[] comment = token.blockComment;
while (token.value != TOK.rightCurly)
{
/* Can take the following forms...
* 1. ident
* 2. ident = value
* 3. type ident = value
* ... prefixed by valid attributes
*/
loc = token.loc;
AST.Type type = null;
Identifier ident = null;
AST.Expressions* udas;
StorageClass stc;
AST.Expression deprecationMessage;
enum attributeErrorMessage = "`%s` is not a valid attribute for enum members";
while(token.value != TOK.rightCurly
&& token.value != TOK.comma
&& token.value != TOK.assign)
{
switch(token.value)
{
case TOK.at:
if (StorageClass _stc = parseAttribute(&udas))
{
if (_stc == STC.disable)
stc |= _stc;
else
{
OutBuffer buf;
AST.stcToBuffer(&buf, _stc);
error(attributeErrorMessage, buf.peekChars());
}
prevTOK = token.value;
nextToken();
}
break;
case TOK.deprecated_:
stc |= STC.deprecated_;
if (!parseDeprecatedAttribute(deprecationMessage))
{
prevTOK = token.value;
nextToken();
}
break;
case TOK.identifier:
const tv = peekNext();
if (tv == TOK.assign || tv == TOK.comma || tv == TOK.rightCurly)
{
ident = token.ident;
type = null;
prevTOK = token.value;
nextToken();
}
else
{
goto default;
}
break;
default:
if (isAnonymousEnum)
{
type = parseType(&ident, null);
if (type == AST.Type.terror)
{
type = null;
prevTOK = token.value;
nextToken();
}
else
{
prevTOK = TOK.identifier;
}
}
else
{
error(attributeErrorMessage, token.toChars());
prevTOK = token.value;
nextToken();
}
break;
}
if (token.value == TOK.comma)
{
prevTOK = token.value;
}
}
if (type && type != AST.Type.terror)
{
if (!ident)
error("no identifier for declarator `%s`", type.toChars());
if (!isAnonymousEnum)
error("type only allowed if anonymous enum and no enum type");
}
AST.Expression value;
if (token.value == TOK.assign)
{
if (prevTOK == TOK.identifier)
{
nextToken();
value = parseAssignExp();
}
else
{
error("assignment must be preceded by an identifier");
nextToken();
}
}
else
{
value = null;
if (type && type != AST.Type.terror && isAnonymousEnum)
error("if type, there must be an initializer");
}
AST.UserAttributeDeclaration uad;
if (udas)
uad = new AST.UserAttributeDeclaration(udas, null);
AST.DeprecatedDeclaration dd;
if (deprecationMessage)
{
dd = new AST.DeprecatedDeclaration(deprecationMessage, null);
stc |= STC.deprecated_;
}
auto em = new AST.EnumMember(loc, ident, value, type, stc, uad, dd);
e.members.push(em);
if (token.value == TOK.rightCurly)
{
}
else
{
addComment(em, comment);
comment = null;
check(TOK.comma);
}
addComment(em, comment);
comment = token.blockComment;
if (token.value == TOK.endOfFile)
{
error("premature end of file");
break;
}
}
nextToken();
}
else
error("enum declaration is invalid");
//printf("-parseEnum() %s\n", e.toChars());
return e;
}
/********************************
* Parse struct, union, interface, class.
*/
private AST.Dsymbol parseAggregate()
{
AST.TemplateParameters* tpl = null;
AST.Expression constraint;
const loc = token.loc;
TOK tok = token.value;
//printf("Parser::parseAggregate()\n");
nextToken();
Identifier id;
if (token.value != TOK.identifier)
{
id = null;
}
else
{
id = token.ident;
nextToken();
if (token.value == TOK.leftParentheses)
{
// struct/class template declaration.
tpl = parseTemplateParameterList();
constraint = parseConstraint();
}
}
// Collect base class(es)
AST.BaseClasses* baseclasses = null;
if (token.value == TOK.colon)
{
if (tok != TOK.interface_ && tok != TOK.class_)
error("base classes are not allowed for `%s`, did you mean `;`?", Token.toChars(tok));
nextToken();
baseclasses = parseBaseClasses();
}
if (token.value == TOK.if_)
{
if (constraint)
error("template constraints appear both before and after BaseClassList, put them before");
constraint = parseConstraint();
}
if (constraint)
{
if (!id)
error("template constraints not allowed for anonymous `%s`", Token.toChars(tok));
if (!tpl)
error("template constraints only allowed for templates");
}
AST.Dsymbols* members = null;
if (token.value == TOK.leftCurly)
{
//printf("aggregate definition\n");
const lookingForElseSave = lookingForElse;
lookingForElse = Loc();
nextToken();
members = parseDeclDefs(0);
lookingForElse = lookingForElseSave;
if (token.value != TOK.rightCurly)
{
/* { */
error("`}` expected following members in `%s` declaration at %s",
Token.toChars(tok), loc.toChars());
}
nextToken();
}
else if (token.value == TOK.semicolon && id)
{
if (baseclasses || constraint)
error("members expected");
nextToken();
}
else
{
error("{ } expected following `%s` declaration", Token.toChars(tok));
}
AST.AggregateDeclaration a;
switch (tok)
{
case TOK.interface_:
if (!id)
error(loc, "anonymous interfaces not allowed");
a = new AST.InterfaceDeclaration(loc, id, baseclasses);
a.members = members;
break;
case TOK.class_:
if (!id)
error(loc, "anonymous classes not allowed");
bool inObject = md && !md.packages && md.id == Id.object;
a = new AST.ClassDeclaration(loc, id, baseclasses, members, inObject);
break;
case TOK.struct_:
if (id)
{
bool inObject = md && !md.packages && md.id == Id.object;
a = new AST.StructDeclaration(loc, id, inObject);
a.members = members;
}
else
{
/* Anonymous structs/unions are more like attributes.
*/
assert(!tpl);
return new AST.AnonDeclaration(loc, false, members);
}
break;
case TOK.union_:
if (id)
{
a = new AST.UnionDeclaration(loc, id);
a.members = members;
}
else
{
/* Anonymous structs/unions are more like attributes.
*/
assert(!tpl);
return new AST.AnonDeclaration(loc, true, members);
}
break;
default:
assert(0);
}
if (tpl)
{
// Wrap a template around the aggregate declaration
auto decldefs = new AST.Dsymbols();
decldefs.push(a);
auto tempdecl = new AST.TemplateDeclaration(loc, id, tpl, constraint, decldefs);
return tempdecl;
}
return a;
}
/*******************************************
*/
private AST.BaseClasses* parseBaseClasses()
{
auto baseclasses = new AST.BaseClasses();
for (; 1; nextToken())
{
auto b = new AST.BaseClass(parseBasicType());
baseclasses.push(b);
if (token.value != TOK.comma)
break;
}
return baseclasses;
}
private AST.Dsymbols* parseImport()
{
auto decldefs = new AST.Dsymbols();
Identifier aliasid = null;
int isstatic = token.value == TOK.static_;
if (isstatic)
nextToken();
//printf("Parser::parseImport()\n");
do
{
L1:
nextToken();
if (token.value != TOK.identifier)
{
error("identifier expected following `import`");
break;
}
const loc = token.loc;
Identifier id = token.ident;
AST.Identifiers* a = null;
nextToken();
if (!aliasid && token.value == TOK.assign)
{
aliasid = id;
goto L1;
}
while (token.value == TOK.dot)
{
if (!a)
a = new AST.Identifiers();
a.push(id);
nextToken();
if (token.value != TOK.identifier)
{
error("identifier expected following `package`");
break;
}
id = token.ident;
nextToken();
}
auto s = new AST.Import(loc, a, id, aliasid, isstatic);
decldefs.push(s);
/* Look for
* : alias=name, alias=name;
* syntax.
*/
if (token.value == TOK.colon)
{
do
{
nextToken();
if (token.value != TOK.identifier)
{
error("identifier expected following `:`");
break;
}
Identifier _alias = token.ident;
Identifier name;
nextToken();
if (token.value == TOK.assign)
{
nextToken();
if (token.value != TOK.identifier)
{
error("identifier expected following `%s=`", _alias.toChars());
break;
}
name = token.ident;
nextToken();
}
else
{
name = _alias;
_alias = null;
}
s.addAlias(name, _alias);
}
while (token.value == TOK.comma);
break; // no comma-separated imports of this form
}
aliasid = null;
}
while (token.value == TOK.comma);
if (token.value == TOK.semicolon)
nextToken();
else
{
error("`;` expected");
nextToken();
}
return decldefs;
}
AST.Type parseType(Identifier* pident = null, AST.TemplateParameters** ptpl = null)
{
/* Take care of the storage class prefixes that
* serve as type attributes:
* const type
* immutable type
* shared type
* inout type
* inout const type
* shared const type
* shared inout type
* shared inout const type
*/
StorageClass stc = 0;
while (1)
{
switch (token.value)
{
case TOK.const_:
if (peekNext() == TOK.leftParentheses)
break; // const as type constructor
stc |= STC.const_; // const as storage class
nextToken();
continue;
case TOK.immutable_:
if (peekNext() == TOK.leftParentheses)
break;
stc |= STC.immutable_;
nextToken();
continue;
case TOK.shared_:
if (peekNext() == TOK.leftParentheses)
break;
stc |= STC.shared_;
nextToken();
continue;
case TOK.inout_:
if (peekNext() == TOK.leftParentheses)
break;
stc |= STC.wild;
nextToken();
continue;
default:
break;
}
break;
}
const typeLoc = token.loc;
AST.Type t;
t = parseBasicType();
int alt = 0;
t = parseDeclarator(t, &alt, pident, ptpl);
checkCstyleTypeSyntax(typeLoc, t, alt, pident ? *pident : null);
t = t.addSTC(stc);
return t;
}
private AST.Type parseBasicType(bool dontLookDotIdents = false)
{
AST.Type t;
Loc loc;
Identifier id;
//printf("parseBasicType()\n");
switch (token.value)
{
case TOK.void_:
t = AST.Type.tvoid;
goto LabelX;
case TOK.int8:
t = AST.Type.tint8;
goto LabelX;
case TOK.uns8:
t = AST.Type.tuns8;
goto LabelX;
case TOK.int16:
t = AST.Type.tint16;
goto LabelX;
case TOK.uns16:
t = AST.Type.tuns16;
goto LabelX;
case TOK.int32:
t = AST.Type.tint32;
goto LabelX;
case TOK.uns32:
t = AST.Type.tuns32;
goto LabelX;
case TOK.int64:
t = AST.Type.tint64;
nextToken();
if (token.value == TOK.int64) // if `long long`
{
error("use `long` for a 64 bit integer instead of `long long`");
nextToken();
}
else if (token.value == TOK.float64) // if `long double`
{
error("use `real` instead of `long double`");
t = AST.Type.tfloat80;
nextToken();
}
break;
case TOK.uns64:
t = AST.Type.tuns64;
goto LabelX;
case TOK.int128:
t = AST.Type.tint128;
goto LabelX;
case TOK.uns128:
t = AST.Type.tuns128;
goto LabelX;
case TOK.float32:
t = AST.Type.tfloat32;
goto LabelX;
case TOK.float64:
t = AST.Type.tfloat64;
goto LabelX;
case TOK.float80:
t = AST.Type.tfloat80;
goto LabelX;
case TOK.imaginary32:
t = AST.Type.timaginary32;
goto LabelX;
case TOK.imaginary64:
t = AST.Type.timaginary64;
goto LabelX;
case TOK.imaginary80:
t = AST.Type.timaginary80;
goto LabelX;
case TOK.complex32:
t = AST.Type.tcomplex32;
goto LabelX;
case TOK.complex64:
t = AST.Type.tcomplex64;
goto LabelX;
case TOK.complex80:
t = AST.Type.tcomplex80;
goto LabelX;
case TOK.bool_:
t = AST.Type.tbool;
goto LabelX;
case TOK.char_:
t = AST.Type.tchar;
goto LabelX;
case TOK.wchar_:
t = AST.Type.twchar;
goto LabelX;
case TOK.dchar_:
t = AST.Type.tdchar;
goto LabelX;
LabelX:
nextToken();
break;
case TOK.this_:
case TOK.super_:
case TOK.identifier:
loc = token.loc;
id = token.ident;
nextToken();
if (token.value == TOK.not)
{
// ident!(template_arguments)
auto tempinst = new AST.TemplateInstance(loc, id, parseTemplateArguments());
t = parseBasicTypeStartingAt(new AST.TypeInstance(loc, tempinst), dontLookDotIdents);
}
else
{
t = parseBasicTypeStartingAt(new AST.TypeIdentifier(loc, id), dontLookDotIdents);
}
break;
case TOK.mixin_:
// https://dlang.org/spec/expression.html#mixin_types
nextToken();
loc = token.loc;
if (token.value != TOK.leftParentheses)
error("found `%s` when expecting `%s` following %s", token.toChars(), Token.toChars(TOK.leftParentheses), "`mixin`".ptr);
auto exps = parseArguments();
t = new AST.TypeMixin(loc, exps);
break;
case TOK.dot:
// Leading . as in .foo
t = parseBasicTypeStartingAt(new AST.TypeIdentifier(token.loc, Id.empty), dontLookDotIdents);
break;
case TOK.typeof_:
// typeof(expression)
t = parseBasicTypeStartingAt(parseTypeof(), dontLookDotIdents);
break;
case TOK.vector:
t = parseVector();
break;
case TOK.traits:
if (AST.TraitsExp te = cast(AST.TraitsExp) parsePrimaryExp())
if (te.ident && te.args)
{
t = new AST.TypeTraits(token.loc, te);
break;
}
t = new AST.TypeError;
break;
case TOK.const_:
// const(type)
nextToken();
check(TOK.leftParentheses);
t = parseType().addSTC(STC.const_);
check(TOK.rightParentheses);
break;
case TOK.immutable_:
// immutable(type)
nextToken();
check(TOK.leftParentheses);
t = parseType().addSTC(STC.immutable_);
check(TOK.rightParentheses);
break;
case TOK.shared_:
// shared(type)
nextToken();
check(TOK.leftParentheses);
t = parseType().addSTC(STC.shared_);
check(TOK.rightParentheses);
break;
case TOK.inout_:
// wild(type)
nextToken();
check(TOK.leftParentheses);
t = parseType().addSTC(STC.wild);
check(TOK.rightParentheses);
break;
default:
error("basic type expected, not `%s`", token.toChars());
if (token.value == TOK.else_)
errorSupplemental(token.loc, "There's no `static else`, use `else` instead.");
t = AST.Type.terror;
break;
}
return t;
}
private AST.Type parseBasicTypeStartingAt(AST.TypeQualified tid, bool dontLookDotIdents)
{
AST.Type maybeArray = null;
// See https://issues.dlang.org/show_bug.cgi?id=1215
// A basic type can look like MyType (typical case), but also:
// MyType.T -> A type
// MyType[expr] -> Either a static array of MyType or a type (iif MyType is a Ttuple)
// MyType[expr].T -> A type.
// MyType[expr].T[expr] -> Either a static array of MyType[expr].T or a type
// (iif MyType[expr].T is a Ttuple)
while (1)
{
switch (token.value)
{
case TOK.dot:
{
nextToken();
if (token.value != TOK.identifier)
{
error("identifier expected following `.` instead of `%s`", token.toChars());
break;
}
if (maybeArray)
{
// This is actually a TypeTuple index, not an {a/s}array.
// We need to have a while loop to unwind all index taking:
// T[e1][e2].U -> T, addIndex(e1), addIndex(e2)
AST.Objects dimStack;
AST.Type t = maybeArray;
while (true)
{
if (t.ty == AST.Tsarray)
{
// The index expression is an Expression.
AST.TypeSArray a = cast(AST.TypeSArray)t;
dimStack.push(a.dim.syntaxCopy());
t = a.next.syntaxCopy();
}
else if (t.ty == AST.Taarray)
{
// The index expression is a Type. It will be interpreted as an expression at semantic time.
AST.TypeAArray a = cast(AST.TypeAArray)t;
dimStack.push(a.index.syntaxCopy());
t = a.next.syntaxCopy();
}
else
{
break;
}
}
assert(dimStack.dim > 0);
// We're good. Replay indices in the reverse order.
tid = cast(AST.TypeQualified)t;
while (dimStack.dim)
{
tid.addIndex(dimStack.pop());
}
maybeArray = null;
}
const loc = token.loc;
Identifier id = token.ident;
nextToken();
if (token.value == TOK.not)
{
auto tempinst = new AST.TemplateInstance(loc, id, parseTemplateArguments());
tid.addInst(tempinst);
}
else
tid.addIdent(id);
continue;
}
case TOK.leftBracket:
{
if (dontLookDotIdents) // workaround for https://issues.dlang.org/show_bug.cgi?id=14911
goto Lend;
nextToken();
AST.Type t = maybeArray ? maybeArray : cast(AST.Type)tid;
if (token.value == TOK.rightBracket)
{
// It's a dynamic array, and we're done:
// T[].U does not make sense.
t = new AST.TypeDArray(t);
nextToken();
return t;
}
else if (isDeclaration(&token, NeedDeclaratorId.no, TOK.rightBracket, null))
{
// This can be one of two things:
// 1 - an associative array declaration, T[type]
// 2 - an associative array declaration, T[expr]
// These can only be disambiguated later.
AST.Type index = parseType(); // [ type ]
maybeArray = new AST.TypeAArray(t, index);
check(TOK.rightBracket);
}
else
{
// This can be one of three things:
// 1 - an static array declaration, T[expr]
// 2 - a slice, T[expr .. expr]
// 3 - a template parameter pack index expression, T[expr].U
// 1 and 3 can only be disambiguated later.
//printf("it's type[expression]\n");
inBrackets++;
AST.Expression e = parseAssignExp(); // [ expression ]
if (token.value == TOK.slice)
{
// It's a slice, and we're done.
nextToken();
AST.Expression e2 = parseAssignExp(); // [ exp .. exp ]
t = new AST.TypeSlice(t, e, e2);
inBrackets--;
check(TOK.rightBracket);
return t;
}
else
{
maybeArray = new AST.TypeSArray(t, e);
inBrackets--;
check(TOK.rightBracket);
continue;
}
}
break;
}
default:
goto Lend;
}
}
Lend:
return maybeArray ? maybeArray : cast(AST.Type)tid;
}
/******************************************
* Parse things that follow the initial type t.
* t *
* t []
* t [type]
* t [expression]
* t [expression .. expression]
* t function
* t delegate
*/
private AST.Type parseBasicType2(AST.Type t)
{
//printf("parseBasicType2()\n");
while (1)
{
switch (token.value)
{
case TOK.mul:
t = new AST.TypePointer(t);
nextToken();
continue;
case TOK.leftBracket:
// Handle []. Make sure things like
// int[3][1] a;
// is (array[1] of array[3] of int)
nextToken();
if (token.value == TOK.rightBracket)
{
t = new AST.TypeDArray(t); // []
nextToken();
}
else if (isDeclaration(&token, NeedDeclaratorId.no, TOK.rightBracket, null))
{
// It's an associative array declaration
//printf("it's an associative array\n");
AST.Type index = parseType(); // [ type ]
t = new AST.TypeAArray(t, index);
check(TOK.rightBracket);
}
else
{
//printf("it's type[expression]\n");
inBrackets++;
AST.Expression e = parseAssignExp(); // [ expression ]
if (token.value == TOK.slice)
{
nextToken();
AST.Expression e2 = parseAssignExp(); // [ exp .. exp ]
t = new AST.TypeSlice(t, e, e2);
}
else
{
t = new AST.TypeSArray(t, e);
}
inBrackets--;
check(TOK.rightBracket);
}
continue;
case TOK.delegate_:
case TOK.function_:
{
// Handle delegate declaration:
// t delegate(parameter list) nothrow pure
// t function(parameter list) nothrow pure
TOK save = token.value;
nextToken();
AST.VarArg varargs;
AST.Parameters* parameters = parseParameters(&varargs);
StorageClass stc = parsePostfix(STC.undefined_, null);
auto tf = new AST.TypeFunction(AST.ParameterList(parameters, varargs), t, linkage, stc);
if (stc & (STC.const_ | STC.immutable_ | STC.shared_ | STC.wild | STC.return_))
{
if (save == TOK.function_)
error("`const`/`immutable`/`shared`/`inout`/`return` attributes are only valid for non-static member functions");
else
tf = cast(AST.TypeFunction)tf.addSTC(stc);
}
t = save == TOK.delegate_ ? new AST.TypeDelegate(tf) : new AST.TypePointer(tf); // pointer to function
continue;
}
default:
return t;
}
assert(0);
}
assert(0);
}
private AST.Type parseDeclarator(AST.Type t, int* palt, Identifier* pident, AST.TemplateParameters** tpl = null, StorageClass storageClass = 0, int* pdisable = null, AST.Expressions** pudas = null)
{
//printf("parseDeclarator(tpl = %p)\n", tpl);
t = parseBasicType2(t);
AST.Type ts;
switch (token.value)
{
case TOK.identifier:
if (pident)
*pident = token.ident;
else
error("unexpected identifier `%s` in declarator", token.ident.toChars());
ts = t;
nextToken();
break;
case TOK.leftParentheses:
{
// like: T (*fp)();
// like: T ((*fp))();
if (peekNext() == TOK.mul || peekNext() == TOK.leftParentheses)
{
/* Parse things with parentheses around the identifier, like:
* int (*ident[3])[]
* although the D style would be:
* int[]*[3] ident
*/
*palt |= 1;
nextToken();
ts = parseDeclarator(t, palt, pident);
check(TOK.rightParentheses);
break;
}
ts = t;
Token* peekt = &token;
/* Completely disallow C-style things like:
* T (a);
* Improve error messages for the common bug of a missing return type
* by looking to see if (a) looks like a parameter list.
*/
if (isParameters(&peekt))
{
error("function declaration without return type. (Note that constructors are always named `this`)");
}
else
error("unexpected `(` in declarator");
break;
}
default:
ts = t;
break;
}
// parse DeclaratorSuffixes
while (1)
{
switch (token.value)
{
static if (CARRAYDECL)
{
/* Support C style array syntax:
* int ident[]
* as opposed to D-style:
* int[] ident
*/
case TOK.leftBracket:
{
// This is the old C-style post [] syntax.
AST.TypeNext ta;
nextToken();
if (token.value == TOK.rightBracket)
{
// It's a dynamic array
ta = new AST.TypeDArray(t); // []
nextToken();
*palt |= 2;
}
else if (isDeclaration(&token, NeedDeclaratorId.no, TOK.rightBracket, null))
{
// It's an associative array
//printf("it's an associative array\n");
AST.Type index = parseType(); // [ type ]
check(TOK.rightBracket);
ta = new AST.TypeAArray(t, index);
*palt |= 2;
}
else
{
//printf("It's a static array\n");
AST.Expression e = parseAssignExp(); // [ expression ]
ta = new AST.TypeSArray(t, e);
check(TOK.rightBracket);
*palt |= 2;
}
/* Insert ta into
* ts -> ... -> t
* so that
* ts -> ... -> ta -> t
*/
AST.Type* pt;
for (pt = &ts; *pt != t; pt = &(cast(AST.TypeNext)*pt).next)
{
}
*pt = ta;
continue;
}
}
case TOK.leftParentheses:
{
if (tpl)
{
Token* tk = peekPastParen(&token);
if (tk.value == TOK.leftParentheses)
{
/* Look ahead to see if this is (...)(...),
* i.e. a function template declaration
*/
//printf("function template declaration\n");
// Gather template parameter list
*tpl = parseTemplateParameterList();
}
else if (tk.value == TOK.assign)
{
/* or (...) =,
* i.e. a variable template declaration
*/
//printf("variable template declaration\n");
*tpl = parseTemplateParameterList();
break;
}
}
AST.VarArg varargs;
AST.Parameters* parameters = parseParameters(&varargs);
/* Parse const/immutable/shared/inout/nothrow/pure/return postfix
*/
// merge prefix storage classes
StorageClass stc = parsePostfix(storageClass, pudas);
AST.Type tf = new AST.TypeFunction(AST.ParameterList(parameters, varargs), t, linkage, stc);
tf = tf.addSTC(stc);
if (pdisable)
*pdisable = stc & STC.disable ? 1 : 0;
/* Insert tf into
* ts -> ... -> t
* so that
* ts -> ... -> tf -> t
*/
AST.Type* pt;
for (pt = &ts; *pt != t; pt = &(cast(AST.TypeNext)*pt).next)
{
}
*pt = tf;
break;
}
default:
break;
}
break;
}
return ts;
}
private void parseStorageClasses(ref StorageClass storage_class, ref LINK link,
ref bool setAlignment, ref AST.Expression ealign, ref AST.Expressions* udas)
{
StorageClass stc;
bool sawLinkage = false; // seen a linkage declaration
while (1)
{
switch (token.value)
{
case TOK.const_:
if (peekNext() == TOK.leftParentheses)
break; // const as type constructor
stc = STC.const_; // const as storage class
goto L1;
case TOK.immutable_:
if (peekNext() == TOK.leftParentheses)
break;
stc = STC.immutable_;
goto L1;
case TOK.shared_:
if (peekNext() == TOK.leftParentheses)
break;
stc = STC.shared_;
goto L1;
case TOK.inout_:
if (peekNext() == TOK.leftParentheses)
break;
stc = STC.wild;
goto L1;
case TOK.static_:
stc = STC.static_;
goto L1;
case TOK.final_:
stc = STC.final_;
goto L1;
case TOK.auto_:
stc = STC.auto_;
goto L1;
case TOK.scope_:
stc = STC.scope_;
goto L1;
case TOK.override_:
stc = STC.override_;
goto L1;
case TOK.abstract_:
stc = STC.abstract_;
goto L1;
case TOK.synchronized_:
stc = STC.synchronized_;
goto L1;
case TOK.deprecated_:
stc = STC.deprecated_;
goto L1;
case TOK.nothrow_:
stc = STC.nothrow_;
goto L1;
case TOK.pure_:
stc = STC.pure_;
goto L1;
case TOK.ref_:
stc = STC.ref_;
goto L1;
case TOK.gshared:
stc = STC.gshared;
goto L1;
case TOK.enum_:
{
const tv = peekNext();
if (tv == TOK.leftCurly || tv == TOK.colon)
break;
if (tv == TOK.identifier)
{
const nextv = peekNext2();
if (nextv == TOK.leftCurly || nextv == TOK.colon || nextv == TOK.semicolon)
break;
}
stc = STC.manifest;
goto L1;
}
case TOK.at:
{
stc = parseAttribute(&udas);
if (stc)
goto L1;
continue;
}
L1:
storage_class = appendStorageClass(storage_class, stc);
nextToken();
continue;
case TOK.extern_:
{
if (peekNext() != TOK.leftParentheses)
{
stc = STC.extern_;
goto L1;
}
if (sawLinkage)
error("redundant linkage declaration");
sawLinkage = true;
AST.Identifiers* idents = null;
AST.Expressions* identExps = null;
CPPMANGLE cppmangle;
bool cppMangleOnly = false;
link = parseLinkage(&idents, &identExps, cppmangle, cppMangleOnly);
if (idents || identExps)
{
error("C++ name spaces not allowed here");
}
if (cppmangle != CPPMANGLE.def)
{
error("C++ mangle declaration not allowed here");
}
continue;
}
case TOK.align_:
{
nextToken();
setAlignment = true;
if (token.value == TOK.leftParentheses)
{
nextToken();
ealign = parseExpression();
check(TOK.rightParentheses);
}
continue;
}
default:
break;
}
break;
}
}
/**********************************
* Parse Declarations.
* These can be:
* 1. declarations at global/class level
* 2. declarations at statement level
* Return array of Declaration *'s.
*/
private AST.Dsymbols* parseDeclarations(bool autodecl, PrefixAttributes!AST* pAttrs, const(char)* comment)
{
StorageClass storage_class = STC.undefined_;
TOK tok = TOK.reserved;
LINK link = linkage;
bool setAlignment = false;
AST.Expression ealign;
AST.Expressions* udas = null;
//printf("parseDeclarations() %s\n", token.toChars());
if (!comment)
comment = token.blockComment.ptr;
if (token.value == TOK.alias_)
{
const loc = token.loc;
tok = token.value;
nextToken();
/* Look for:
* alias identifier this;
*/
if (token.value == TOK.identifier && peekNext() == TOK.this_)
{
auto s = new AST.AliasThis(loc, token.ident);
nextToken();
check(TOK.this_);
check(TOK.semicolon);
auto a = new AST.Dsymbols();
a.push(s);
addComment(s, comment);
return a;
}
version (none)
{
/* Look for:
* alias this = identifier;
*/
if (token.value == TOK.this_ && peekNext() == TOK.assign && peekNext2() == TOK.identifier)
{
check(TOK.this_);
check(TOK.assign);
auto s = new AliasThis(loc, token.ident);
nextToken();
check(TOK.semicolon);
auto a = new Dsymbols();
a.push(s);
addComment(s, comment);
return a;
}
}
/* Look for:
* alias identifier = type;
* alias identifier(...) = type;
*/
if (token.value == TOK.identifier && hasOptionalParensThen(peek(&token), TOK.assign))
{
auto a = new AST.Dsymbols();
while (1)
{
auto ident = token.ident;
nextToken();
AST.TemplateParameters* tpl = null;
if (token.value == TOK.leftParentheses)
tpl = parseTemplateParameterList();
check(TOK.assign);
bool hasParsedAttributes;
void parseAttributes()
{
if (hasParsedAttributes) // only parse once
return;
hasParsedAttributes = true;
udas = null;
storage_class = STC.undefined_;
link = linkage;
setAlignment = false;
ealign = null;
parseStorageClasses(storage_class, link, setAlignment, ealign, udas);
}
if (token.value == TOK.at)
parseAttributes;
AST.Declaration v;
AST.Dsymbol s;
// try to parse function type:
// TypeCtors? BasicType ( Parameters ) MemberFunctionAttributes
bool attributesAppended;
const StorageClass funcStc = parseTypeCtor();
Token* tlu = &token;
Token* tk;
if (token.value != TOK.function_ &&
token.value != TOK.delegate_ &&
isBasicType(&tlu) && tlu &&
tlu.value == TOK.leftParentheses)
{
AST.VarArg vargs;
AST.Type tret = parseBasicType();
AST.Parameters* prms = parseParameters(&vargs);
AST.ParameterList pl = AST.ParameterList(prms, vargs);
parseAttributes();
if (udas)
error("user-defined attributes not allowed for `alias` declarations");
attributesAppended = true;
storage_class = appendStorageClass(storage_class, funcStc);
AST.Type tf = new AST.TypeFunction(pl, tret, link, storage_class);
v = new AST.AliasDeclaration(loc, ident, tf);
}
else if (token.value == TOK.function_ ||
token.value == TOK.delegate_ ||
token.value == TOK.leftParentheses &&
skipAttributes(peekPastParen(&token), &tk) &&
(tk.value == TOK.goesTo || tk.value == TOK.leftCurly) ||
token.value == TOK.leftCurly ||
token.value == TOK.identifier && peekNext() == TOK.goesTo ||
token.value == TOK.ref_ && peekNext() == TOK.leftParentheses &&
skipAttributes(peekPastParen(peek(&token)), &tk) &&
(tk.value == TOK.goesTo || tk.value == TOK.leftCurly)
)
{
// function (parameters) { statements... }
// delegate (parameters) { statements... }
// (parameters) { statements... }
// (parameters) => expression
// { statements... }
// identifier => expression
// ref (parameters) { statements... }
// ref (parameters) => expression
s = parseFunctionLiteral();
if (udas !is null)
{
if (storage_class != 0)
error("Cannot put a storage-class in an alias declaration.");
// parseAttributes shouldn't have set these variables
assert(link == linkage && !setAlignment && ealign is null);
auto tpl_ = cast(AST.TemplateDeclaration) s;
assert(tpl_ !is null && tpl_.members.dim == 1);
auto fd = cast(AST.FuncLiteralDeclaration) (*tpl_.members)[0];
auto tf = cast(AST.TypeFunction) fd.type;
assert(tf.parameterList.parameters.dim > 0);
auto as = new AST.Dsymbols();
(*tf.parameterList.parameters)[0].userAttribDecl = new AST.UserAttributeDeclaration(udas, as);
}
v = new AST.AliasDeclaration(loc, ident, s);
}
else
{
parseAttributes();
// StorageClasses type
if (udas)
error("user-defined attributes not allowed for `%s` declarations", Token.toChars(tok));
auto t = parseType();
v = new AST.AliasDeclaration(loc, ident, t);
}
if (!attributesAppended)
storage_class = appendStorageClass(storage_class, funcStc);
v.storage_class = storage_class;
s = v;
if (tpl)
{
auto a2 = new AST.Dsymbols();
a2.push(s);
auto tempdecl = new AST.TemplateDeclaration(loc, ident, tpl, null, a2);
s = tempdecl;
}
if (link != linkage)
{
auto a2 = new AST.Dsymbols();
a2.push(s);
s = new AST.LinkDeclaration(link, a2);
}
a.push(s);
switch (token.value)
{
case TOK.semicolon:
nextToken();
addComment(s, comment);
break;
case TOK.comma:
nextToken();
addComment(s, comment);
if (token.value != TOK.identifier)
{
error("identifier expected following comma, not `%s`", token.toChars());
break;
}
if (peekNext() != TOK.assign && peekNext() != TOK.leftParentheses)
{
error("`=` expected following identifier");
nextToken();
break;
}
continue;
default:
error("semicolon expected to close `%s` declaration", Token.toChars(tok));
break;
}
break;
}
return a;
}
// alias StorageClasses type ident;
}
AST.Type ts;
if (!autodecl)
{
parseStorageClasses(storage_class, link, setAlignment, ealign, udas);
if (token.value == TOK.enum_)
{
AST.Dsymbol d = parseEnum();
auto a = new AST.Dsymbols();
a.push(d);
if (udas)
{
d = new AST.UserAttributeDeclaration(udas, a);
a = new AST.Dsymbols();
a.push(d);
}
addComment(d, comment);
return a;
}
if (token.value == TOK.struct_ ||
token.value == TOK.union_ ||
token.value == TOK.class_ ||
token.value == TOK.interface_)
{
AST.Dsymbol s = parseAggregate();
auto a = new AST.Dsymbols();
a.push(s);
if (storage_class)
{
s = new AST.StorageClassDeclaration(storage_class, a);
a = new AST.Dsymbols();
a.push(s);
}
if (setAlignment)
{
s = new AST.AlignDeclaration(s.loc, ealign, a);
a = new AST.Dsymbols();
a.push(s);
}
if (link != linkage)
{
s = new AST.LinkDeclaration(link, a);
a = new AST.Dsymbols();
a.push(s);
}
if (udas)
{
s = new AST.UserAttributeDeclaration(udas, a);
a = new AST.Dsymbols();
a.push(s);
}
addComment(s, comment);
return a;
}
/* Look for auto initializers:
* storage_class identifier = initializer;
* storage_class identifier(...) = initializer;
*/
if ((storage_class || udas) && token.value == TOK.identifier && hasOptionalParensThen(peek(&token), TOK.assign))
{
AST.Dsymbols* a = parseAutoDeclarations(storage_class, comment);
if (udas)
{
AST.Dsymbol s = new AST.UserAttributeDeclaration(udas, a);
a = new AST.Dsymbols();
a.push(s);
}
return a;
}
/* Look for return type inference for template functions.
*/
{
Token* tk;
if ((storage_class || udas) && token.value == TOK.identifier && skipParens(peek(&token), &tk) &&
skipAttributes(tk, &tk) &&
(tk.value == TOK.leftParentheses || tk.value == TOK.leftCurly || tk.value == TOK.in_ || tk.value == TOK.out_ ||
tk.value == TOK.do_ || tk.value == TOK.identifier && tk.ident == Id._body))
{
version (none)
{
// This deprecation has been disabled for the time being, see PR10763
// @@@DEPRECATED@@@
// https://github.com/dlang/DIPs/blob/1f5959abe482b1f9094f6484a7d0a3ade77fc2fc/DIPs/accepted/DIP1003.md
// Deprecated in 2.091 - Can be removed from 2.101
if (tk.value == TOK.identifier && tk.ident == Id._body)
deprecation("Usage of the `body` keyword is deprecated. Use `do` instead.");
}
ts = null;
}
else
{
ts = parseBasicType();
ts = parseBasicType2(ts);
}
}
}
if (pAttrs)
{
storage_class |= pAttrs.storageClass;
//pAttrs.storageClass = STC.undefined_;
}
AST.Type tfirst = null;
auto a = new AST.Dsymbols();
while (1)
{
AST.TemplateParameters* tpl = null;
int disable;
int alt = 0;
const loc = token.loc;
Identifier ident = null;
auto t = parseDeclarator(ts, &alt, &ident, &tpl, storage_class, &disable, &udas);
assert(t);
if (!tfirst)
tfirst = t;
else if (t != tfirst)
error("multiple declarations must have the same type, not `%s` and `%s`", tfirst.toChars(), t.toChars());
bool isThis = (t.ty == AST.Tident && (cast(AST.TypeIdentifier)t).ident == Id.This && token.value == TOK.assign);
if (ident)
checkCstyleTypeSyntax(loc, t, alt, ident);
else if (!isThis && (t != AST.Type.terror))
error("no identifier for declarator `%s`", t.toChars());
if (tok == TOK.alias_)
{
AST.Declaration v;
AST.Initializer _init = null;
/* Aliases can no longer have multiple declarators, storage classes,
* linkages, or auto declarations.
* These never made any sense, anyway.
* The code below needs to be fixed to reject them.
* The grammar has already been fixed to preclude them.
*/
if (udas)
error("user-defined attributes not allowed for `%s` declarations", Token.toChars(tok));
if (token.value == TOK.assign)
{
nextToken();
_init = parseInitializer();
}
if (_init)
{
if (isThis)
error("cannot use syntax `alias this = %s`, use `alias %s this` instead", _init.toChars(), _init.toChars());
else
error("alias cannot have initializer");
}
v = new AST.AliasDeclaration(loc, ident, t);
v.storage_class = storage_class;
if (pAttrs)
{
/* AliasDeclaration distinguish @safe, @system, @trusted attributes
* on prefix and postfix.
* @safe alias void function() FP1;
* alias @safe void function() FP2; // FP2 is not @safe
* alias void function() @safe FP3;
*/
pAttrs.storageClass &= STC.safeGroup;
}
AST.Dsymbol s = v;
if (link != linkage)
{
auto ax = new AST.Dsymbols();
ax.push(v);
s = new AST.LinkDeclaration(link, ax);
}
a.push(s);
switch (token.value)
{
case TOK.semicolon:
nextToken();
addComment(s, comment);
break;
case TOK.comma:
nextToken();
addComment(s, comment);
continue;
default:
error("semicolon expected to close `%s` declaration", Token.toChars(tok));
break;
}
}
else if (t.ty == AST.Tfunction)
{
AST.Expression constraint = null;
//printf("%s funcdecl t = %s, storage_class = x%lx\n", loc.toChars(), t.toChars(), storage_class);
auto f = new AST.FuncDeclaration(loc, Loc.initial, ident, storage_class | (disable ? STC.disable : 0), t);
if (pAttrs)
pAttrs.storageClass = STC.undefined_;
if (tpl)
constraint = parseConstraint();
AST.Dsymbol s = parseContracts(f);
auto tplIdent = s.ident;
if (link != linkage)
{
auto ax = new AST.Dsymbols();
ax.push(s);
s = new AST.LinkDeclaration(link, ax);
}
if (udas)
{
auto ax = new AST.Dsymbols();
ax.push(s);
s = new AST.UserAttributeDeclaration(udas, ax);
}
/* A template parameter list means it's a function template
*/
if (tpl)
{
// Wrap a template around the function declaration
auto decldefs = new AST.Dsymbols();
decldefs.push(s);
auto tempdecl = new AST.TemplateDeclaration(loc, tplIdent, tpl, constraint, decldefs);
s = tempdecl;
if (storage_class & STC.static_)
{
assert(f.storage_class & STC.static_);
f.storage_class &= ~STC.static_;
auto ax = new AST.Dsymbols();
ax.push(s);
s = new AST.StorageClassDeclaration(STC.static_, ax);
}
}
a.push(s);
addComment(s, comment);
}
else if (ident)
{
AST.Initializer _init = null;
if (token.value == TOK.assign)
{
nextToken();
_init = parseInitializer();
}
auto v = new AST.VarDeclaration(loc, t, ident, _init);
v.storage_class = storage_class;
if (pAttrs)
pAttrs.storageClass = STC.undefined_;
AST.Dsymbol s = v;
if (tpl && _init)
{
auto a2 = new AST.Dsymbols();
a2.push(s);
auto tempdecl = new AST.TemplateDeclaration(loc, ident, tpl, null, a2, 0);
s = tempdecl;
}
if (setAlignment)
{
auto ax = new AST.Dsymbols();
ax.push(s);
s = new AST.AlignDeclaration(v.loc, ealign, ax);
}
if (link != linkage)
{
auto ax = new AST.Dsymbols();
ax.push(s);
s = new AST.LinkDeclaration(link, ax);
}
if (udas)
{
auto ax = new AST.Dsymbols();
ax.push(s);
s = new AST.UserAttributeDeclaration(udas, ax);
}
a.push(s);
switch (token.value)
{
case TOK.semicolon:
nextToken();
addComment(s, comment);
break;
case TOK.comma:
nextToken();
addComment(s, comment);
continue;
default:
error("semicolon expected, not `%s`", token.toChars());
break;
}
}
break;
}
return a;
}
private AST.Dsymbol parseFunctionLiteral()
{
const loc = token.loc;
AST.TemplateParameters* tpl = null;
AST.Parameters* parameters = null;
AST.VarArg varargs = AST.VarArg.none;
AST.Type tret = null;
StorageClass stc = 0;
TOK save = TOK.reserved;
switch (token.value)
{
case TOK.function_:
case TOK.delegate_:
save = token.value;
nextToken();
if (token.value == TOK.ref_)
{
// function ref (parameters) { statements... }
// delegate ref (parameters) { statements... }
stc = STC.ref_;
nextToken();
}
if (token.value != TOK.leftParentheses && token.value != TOK.leftCurly)
{
// function type (parameters) { statements... }
// delegate type (parameters) { statements... }
tret = parseBasicType();
tret = parseBasicType2(tret); // function return type
}
if (token.value == TOK.leftParentheses)
{
// function (parameters) { statements... }
// delegate (parameters) { statements... }
}
else
{
// function { statements... }
// delegate { statements... }
break;
}
goto case TOK.leftParentheses;
case TOK.ref_:
{
// ref (parameters) => expression
// ref (parameters) { statements... }
stc = STC.ref_;
nextToken();
goto case TOK.leftParentheses;
}
case TOK.leftParentheses:
{
// (parameters) => expression
// (parameters) { statements... }
parameters = parseParameters(&varargs, &tpl);
stc = parsePostfix(stc, null);
if (StorageClass modStc = stc & STC.TYPECTOR)
{
if (save == TOK.function_)
{
OutBuffer buf;
AST.stcToBuffer(&buf, modStc);
error("function literal cannot be `%s`", buf.peekChars());
}
else
save = TOK.delegate_;
}
break;
}
case TOK.leftCurly:
// { statements... }
break;
case TOK.identifier:
{
// identifier => expression
parameters = new AST.Parameters();
Identifier id = Identifier.generateId("__T");
AST.Type t = new AST.TypeIdentifier(loc, id);
parameters.push(new AST.Parameter(0, t, token.ident, null, null));
tpl = new AST.TemplateParameters();
AST.TemplateParameter tp = new AST.TemplateTypeParameter(loc, id, null, null);
tpl.push(tp);
nextToken();
break;
}
default:
assert(0);
}
auto tf = new AST.TypeFunction(AST.ParameterList(parameters, varargs), tret, linkage, stc);
tf = cast(AST.TypeFunction)tf.addSTC(stc);
auto fd = new AST.FuncLiteralDeclaration(loc, Loc.initial, tf, save, null);
if (token.value == TOK.goesTo)
{
check(TOK.goesTo);
const returnloc = token.loc;
AST.Expression ae = parseAssignExp();
fd.fbody = new AST.ReturnStatement(returnloc, ae);
fd.endloc = token.loc;
}
else
{
parseContracts(fd);
}
if (tpl)
{
// Wrap a template around function fd
auto decldefs = new AST.Dsymbols();
decldefs.push(fd);
return new AST.TemplateDeclaration(fd.loc, fd.ident, tpl, null, decldefs, false, true);
}
return fd;
}
/*****************************************
* Parse contracts following function declaration.
*/
private AST.FuncDeclaration parseContracts(AST.FuncDeclaration f)
{
LINK linksave = linkage;
bool literal = f.isFuncLiteralDeclaration() !is null;
// The following is irrelevant, as it is overridden by sc.linkage in
// TypeFunction::semantic
linkage = LINK.d; // nested functions have D linkage
bool requireDo = false;
L1:
switch (token.value)
{
case TOK.leftCurly:
if (requireDo)
error("missing `do { ... }` after `in` or `out`");
f.fbody = parseStatement(ParseStatementFlags.semi);
f.endloc = endloc;
break;
case TOK.identifier:
if (token.ident == Id._body)
{
version (none)
{
// This deprecation has been disabled for the time being, see PR10763
// @@@DEPRECATED@@@
// https://github.com/dlang/DIPs/blob/1f5959abe482b1f9094f6484a7d0a3ade77fc2fc/DIPs/accepted/DIP1003.md
// Deprecated in 2.091 - Can be removed from 2.101
deprecation("Usage of the `body` keyword is deprecated. Use `do` instead.");
}
goto case TOK.do_;
}
goto default;
case TOK.do_:
nextToken();
f.fbody = parseStatement(ParseStatementFlags.curly);
f.endloc = endloc;
break;
version (none)
{
// Do we want this for function declarations, so we can do:
// int x, y, foo(), z;
case TOK.comma:
nextToken();
continue;
}
case TOK.in_:
// in { statements... }
// in (expression)
auto loc = token.loc;
nextToken();
if (!f.frequires)
{
f.frequires = new AST.Statements;
}
if (token.value == TOK.leftParentheses)
{
nextToken();
AST.Expression e = parseAssignExp(), msg = null;
if (token.value == TOK.comma)
{
nextToken();
if (token.value != TOK.rightParentheses)
{
msg = parseAssignExp();
if (token.value == TOK.comma)
nextToken();
}
}
check(TOK.rightParentheses);
e = new AST.AssertExp(loc, e, msg);
f.frequires.push(new AST.ExpStatement(loc, e));
requireDo = false;
}
else
{
f.frequires.push(parseStatement(ParseStatementFlags.curly | ParseStatementFlags.scope_));
requireDo = true;
}
goto L1;
case TOK.out_:
// out { statements... }
// out (; expression)
// out (identifier) { statements... }
// out (identifier; expression)
auto loc = token.loc;
nextToken();
if (!f.fensures)
{
f.fensures = new AST.Ensures;
}
Identifier id = null;
if (token.value != TOK.leftCurly)
{
check(TOK.leftParentheses);
if (token.value != TOK.identifier && token.value != TOK.semicolon)
error("`(identifier) { ... }` or `(identifier; expression)` following `out` expected, not `%s`", token.toChars());
if (token.value != TOK.semicolon)
{
id = token.ident;
nextToken();
}
if (token.value == TOK.semicolon)
{
nextToken();
AST.Expression e = parseAssignExp(), msg = null;
if (token.value == TOK.comma)
{
nextToken();
if (token.value != TOK.rightParentheses)
{
msg = parseAssignExp();
if (token.value == TOK.comma)
nextToken();
}
}
check(TOK.rightParentheses);
e = new AST.AssertExp(loc, e, msg);
f.fensures.push(AST.Ensure(id, new AST.ExpStatement(loc, e)));
requireDo = false;
goto L1;
}
check(TOK.rightParentheses);
}
f.fensures.push(AST.Ensure(id, parseStatement(ParseStatementFlags.curly | ParseStatementFlags.scope_)));
requireDo = true;
goto L1;
case TOK.semicolon:
if (!literal)
{
// https://issues.dlang.org/show_bug.cgi?id=15799
// Semicolon becomes a part of function declaration
// only when 'do' is not required
if (!requireDo)
nextToken();
break;
}
goto default;
default:
if (literal)
{
const(char)* sbody = requireDo ? "do " : "";
error("missing `%s{ ... }` for function literal", sbody);
}
else if (!requireDo) // allow contracts even with no body
{
TOK t = token.value;
if (t == TOK.const_ || t == TOK.immutable_ || t == TOK.inout_ || t == TOK.return_ ||
t == TOK.shared_ || t == TOK.nothrow_ || t == TOK.pure_)
error("'%s' cannot be placed after a template constraint", token.toChars);
else if (t == TOK.at)
error("attributes cannot be placed after a template constraint");
else if (t == TOK.if_)
error("cannot use function constraints for non-template functions. Use `static if` instead");
else
error("semicolon expected following function declaration");
}
break;
}
if (literal && !f.fbody)
{
// Set empty function body for error recovery
f.fbody = new AST.CompoundStatement(Loc.initial, cast(AST.Statement)null);
}
linkage = linksave;
return f;
}
/*****************************************
*/
private void checkDanglingElse(Loc elseloc)
{
if (token.value != TOK.else_ && token.value != TOK.catch_ && token.value != TOK.finally_ && lookingForElse.linnum != 0)
{
warning(elseloc, "else is dangling, add { } after condition at %s", lookingForElse.toChars());
}
}
private void checkCstyleTypeSyntax(Loc loc, AST.Type t, int alt, Identifier ident)
{
if (!alt)
return;
const(char)* sp = !ident ? "" : " ";
const(char)* s = !ident ? "" : ident.toChars();
error(loc, "instead of C-style syntax, use D-style `%s%s%s`", t.toChars(), sp, s);
}
/*****************************************
* Determines additional argument types for parseForeach.
*/
private template ParseForeachArgs(bool isStatic, bool isDecl)
{
static alias Seq(T...) = T;
static if(isDecl)
{
alias ParseForeachArgs = Seq!(AST.Dsymbol*);
}
else
{
alias ParseForeachArgs = Seq!();
}
}
/*****************************************
* Determines the result type for parseForeach.
*/
private template ParseForeachRet(bool isStatic, bool isDecl)
{
static if(!isStatic)
{
alias ParseForeachRet = AST.Statement;
}
else static if(isDecl)
{
alias ParseForeachRet = AST.StaticForeachDeclaration;
}
else
{
alias ParseForeachRet = AST.StaticForeachStatement;
}
}
/*****************************************
* Parses `foreach` statements, `static foreach` statements and
* `static foreach` declarations. The template parameter
* `isStatic` is true, iff a `static foreach` should be parsed.
* If `isStatic` is true, `isDecl` can be true to indicate that a
* `static foreach` declaration should be parsed.
*/
private ParseForeachRet!(isStatic, isDecl) parseForeach(bool isStatic, bool isDecl)(Loc loc, ParseForeachArgs!(isStatic, isDecl) args)
{
static if(isDecl)
{
static assert(isStatic);
}
static if(isStatic)
{
nextToken();
static if(isDecl) auto pLastDecl = args[0];
}
TOK op = token.value;
nextToken();
check(TOK.leftParentheses);
auto parameters = new AST.Parameters();
while (1)
{
Identifier ai = null;
AST.Type at;
StorageClass storageClass = 0;
StorageClass stc = 0;
Lagain:
if (stc)
{
storageClass = appendStorageClass(storageClass, stc);
nextToken();
}
switch (token.value)
{
case TOK.ref_:
stc = STC.ref_;
goto Lagain;
case TOK.enum_:
stc = STC.manifest;
goto Lagain;
case TOK.alias_:
storageClass = appendStorageClass(storageClass, STC.alias_);
nextToken();
break;
case TOK.const_:
if (peekNext() != TOK.leftParentheses)
{
stc = STC.const_;
goto Lagain;
}
break;
case TOK.immutable_:
if (peekNext() != TOK.leftParentheses)
{
stc = STC.immutable_;
goto Lagain;
}
break;
case TOK.shared_:
if (peekNext() != TOK.leftParentheses)
{
stc = STC.shared_;
goto Lagain;
}
break;
case TOK.inout_:
if (peekNext() != TOK.leftParentheses)
{
stc = STC.wild;
goto Lagain;
}
break;
default:
break;
}
if (token.value == TOK.identifier)
{
const tv = peekNext();
if (tv == TOK.comma || tv == TOK.semicolon)
{
ai = token.ident;
at = null; // infer argument type
nextToken();
goto Larg;
}
}
at = parseType(&ai);
if (!ai)
error("no identifier for declarator `%s`", at.toChars());
Larg:
auto p = new AST.Parameter(storageClass, at, ai, null, null);
parameters.push(p);
if (token.value == TOK.comma)
{
nextToken();
continue;
}
break;
}
check(TOK.semicolon);
AST.Expression aggr = parseExpression();
if (token.value == TOK.slice && parameters.dim == 1)
{
AST.Parameter p = (*parameters)[0];
nextToken();
AST.Expression upr = parseExpression();
check(TOK.rightParentheses);
Loc endloc;
static if (!isDecl)
{
AST.Statement _body = parseStatement(0, null, &endloc);
}
else
{
AST.Statement _body = null;
}
auto rangefe = new AST.ForeachRangeStatement(loc, op, p, aggr, upr, _body, endloc);
static if (!isStatic)
{
return rangefe;
}
else static if(isDecl)
{
return new AST.StaticForeachDeclaration(new AST.StaticForeach(loc, null, rangefe), parseBlock(pLastDecl));
}
else
{
return new AST.StaticForeachStatement(loc, new AST.StaticForeach(loc, null, rangefe));
}
}
else
{
check(TOK.rightParentheses);
Loc endloc;
static if (!isDecl)
{
AST.Statement _body = parseStatement(0, null, &endloc);
}
else
{
AST.Statement _body = null;
}
auto aggrfe = new AST.ForeachStatement(loc, op, parameters, aggr, _body, endloc);
static if(!isStatic)
{
return aggrfe;
}
else static if(isDecl)
{
return new AST.StaticForeachDeclaration(new AST.StaticForeach(loc, aggrfe, null), parseBlock(pLastDecl));
}
else
{
return new AST.StaticForeachStatement(loc, new AST.StaticForeach(loc, aggrfe, null));
}
}
}
/*****************************************
* Input:
* flags PSxxxx
* Output:
* pEndloc if { ... statements ... }, store location of closing brace, otherwise loc of last token of statement
*/
AST.Statement parseStatement(int flags, const(char)** endPtr = null, Loc* pEndloc = null)
{
AST.Statement s;
AST.Condition cond;
AST.Statement ifbody;
AST.Statement elsebody;
bool isfinal;
const loc = token.loc;
//printf("parseStatement()\n");
if (flags & ParseStatementFlags.curly && token.value != TOK.leftCurly)
error("statement expected to be `{ }`, not `%s`", token.toChars());
switch (token.value)
{
case TOK.identifier:
{
/* A leading identifier can be a declaration, label, or expression.
* The easiest case to check first is label:
*/
if (peekNext() == TOK.colon)
{
if (peekNext2() == TOK.colon)
{
// skip ident::
nextToken();
nextToken();
nextToken();
error("use `.` for member lookup, not `::`");
break;
}
// It's a label
Identifier ident = token.ident;
nextToken();
nextToken();
if (token.value == TOK.rightCurly)
s = null;
else if (token.value == TOK.leftCurly)
s = parseStatement(ParseStatementFlags.curly | ParseStatementFlags.scope_);
else
s = parseStatement(ParseStatementFlags.semiOk);
s = new AST.LabelStatement(loc, ident, s);
break;
}
goto case TOK.dot;
}
case TOK.dot:
case TOK.typeof_:
case TOK.vector:
case TOK.traits:
/* https://issues.dlang.org/show_bug.cgi?id=15163
* If tokens can be handled as
* old C-style declaration or D expression, prefer the latter.
*/
if (isDeclaration(&token, NeedDeclaratorId.mustIfDstyle, TOK.reserved, null))
goto Ldeclaration;
goto Lexp;
case TOK.assert_:
case TOK.this_:
case TOK.super_:
case TOK.int32Literal:
case TOK.uns32Literal:
case TOK.int64Literal:
case TOK.uns64Literal:
case TOK.int128Literal:
case TOK.uns128Literal:
case TOK.float32Literal:
case TOK.float64Literal:
case TOK.float80Literal:
case TOK.imaginary32Literal:
case TOK.imaginary64Literal:
case TOK.imaginary80Literal:
case TOK.charLiteral:
case TOK.wcharLiteral:
case TOK.dcharLiteral:
case TOK.null_:
case TOK.true_:
case TOK.false_:
case TOK.string_:
case TOK.hexadecimalString:
case TOK.leftParentheses:
case TOK.cast_:
case TOK.mul:
case TOK.min:
case TOK.add:
case TOK.tilde:
case TOK.not:
case TOK.plusPlus:
case TOK.minusMinus:
case TOK.new_:
case TOK.delete_:
case TOK.delegate_:
case TOK.function_:
case TOK.typeid_:
case TOK.is_:
case TOK.leftBracket:
case TOK.file:
case TOK.fileFullPath:
case TOK.line:
case TOK.moduleString:
case TOK.functionString:
case TOK.prettyFunction:
Lexp:
{
AST.Expression exp = parseExpression();
check(TOK.semicolon, "statement");
s = new AST.ExpStatement(loc, exp);
break;
}
case TOK.static_:
{
// Look ahead to see if it's static assert() or static if()
const tv = peekNext();
if (tv == TOK.assert_)
{
s = new AST.StaticAssertStatement(parseStaticAssert());
break;
}
if (tv == TOK.if_)
{
cond = parseStaticIfCondition();
goto Lcondition;
}
if (tv == TOK.foreach_ || tv == TOK.foreach_reverse_)
{
s = parseForeach!(true,false)(loc);
if (flags & ParseStatementFlags.scope_)
s = new AST.ScopeStatement(loc, s, token.loc);
break;
}
if (tv == TOK.import_)
{
AST.Dsymbols* imports = parseImport();
s = new AST.ImportStatement(loc, imports);
if (flags & ParseStatementFlags.scope_)
s = new AST.ScopeStatement(loc, s, token.loc);
break;
}
goto Ldeclaration;
}
case TOK.final_:
if (peekNext() == TOK.switch_)
{
nextToken();
isfinal = true;
goto Lswitch;
}
goto Ldeclaration;
case TOK.wchar_:
case TOK.dchar_:
case TOK.bool_:
case TOK.char_:
case TOK.int8:
case TOK.uns8:
case TOK.int16:
case TOK.uns16:
case TOK.int32:
case TOK.uns32:
case TOK.int64:
case TOK.uns64:
case TOK.int128:
case TOK.uns128:
case TOK.float32:
case TOK.float64:
case TOK.float80:
case TOK.imaginary32:
case TOK.imaginary64:
case TOK.imaginary80:
case TOK.complex32:
case TOK.complex64:
case TOK.complex80:
case TOK.void_:
// bug 7773: int.max is always a part of expression
if (peekNext() == TOK.dot)
goto Lexp;
if (peekNext() == TOK.leftParentheses)
goto Lexp;
goto case;
case TOK.alias_:
case TOK.const_:
case TOK.auto_:
case TOK.abstract_:
case TOK.extern_:
case TOK.align_:
case TOK.immutable_:
case TOK.shared_:
case TOK.inout_:
case TOK.deprecated_:
case TOK.nothrow_:
case TOK.pure_:
case TOK.ref_:
case TOK.gshared:
case TOK.at:
case TOK.struct_:
case TOK.union_:
case TOK.class_:
case TOK.interface_:
Ldeclaration:
{
AST.Dsymbols* a = parseDeclarations(false, null, null);
if (a.dim > 1)
{
auto as = new AST.Statements();
as.reserve(a.dim);
foreach (i; 0 .. a.dim)
{
AST.Dsymbol d = (*a)[i];
s = new AST.ExpStatement(loc, d);
as.push(s);
}
s = new AST.CompoundDeclarationStatement(loc, as);
}
else if (a.dim == 1)
{
AST.Dsymbol d = (*a)[0];
s = new AST.ExpStatement(loc, d);
}
else
s = new AST.ExpStatement(loc, cast(AST.Expression)null);
if (flags & ParseStatementFlags.scope_)
s = new AST.ScopeStatement(loc, s, token.loc);
break;
}
case TOK.enum_:
{
/* Determine if this is a manifest constant declaration,
* or a conventional enum.
*/
AST.Dsymbol d;
const tv = peekNext();
if (tv == TOK.leftCurly || tv == TOK.colon)
d = parseEnum();
else if (tv != TOK.identifier)
goto Ldeclaration;
else
{
const nextv = peekNext2();
if (nextv == TOK.leftCurly || nextv == TOK.colon || nextv == TOK.semicolon)
d = parseEnum();
else
goto Ldeclaration;
}
s = new AST.ExpStatement(loc, d);
if (flags & ParseStatementFlags.scope_)
s = new AST.ScopeStatement(loc, s, token.loc);
break;
}
case TOK.mixin_:
{
if (isDeclaration(&token, NeedDeclaratorId.mustIfDstyle, TOK.reserved, null))
goto Ldeclaration;
if (peekNext() == TOK.leftParentheses)
{
// mixin(string)
AST.Expression e = parseAssignExp();
check(TOK.semicolon);
if (e.op == TOK.mixin_)
{
AST.CompileExp cpe = cast(AST.CompileExp)e;
s = new AST.CompileStatement(loc, cpe.exps);
}
else
{
s = new AST.ExpStatement(loc, e);
}
break;
}
AST.Dsymbol d = parseMixin();
s = new AST.ExpStatement(loc, d);
if (flags & ParseStatementFlags.scope_)
s = new AST.ScopeStatement(loc, s, token.loc);
break;
}
case TOK.leftCurly:
{
const lookingForElseSave = lookingForElse;
lookingForElse = Loc.initial;
nextToken();
//if (token.value == TOK.semicolon)
// error("use `{ }` for an empty statement, not `;`");
auto statements = new AST.Statements();
while (token.value != TOK.rightCurly && token.value != TOK.endOfFile)
{
statements.push(parseStatement(ParseStatementFlags.semi | ParseStatementFlags.curlyScope));
}
if (endPtr)
*endPtr = token.ptr;
endloc = token.loc;
if (pEndloc)
{
*pEndloc = token.loc;
pEndloc = null; // don't set it again
}
s = new AST.CompoundStatement(loc, statements);
if (flags & (ParseStatementFlags.scope_ | ParseStatementFlags.curlyScope))
s = new AST.ScopeStatement(loc, s, token.loc);
check(TOK.rightCurly, "compound statement");
lookingForElse = lookingForElseSave;
break;
}
case TOK.while_:
{
nextToken();
check(TOK.leftParentheses);
AST.Expression condition = parseExpression();
check(TOK.rightParentheses);
Loc endloc;
AST.Statement _body = parseStatement(ParseStatementFlags.scope_, null, &endloc);
s = new AST.WhileStatement(loc, condition, _body, endloc);
break;
}
case TOK.semicolon:
if (!(flags & ParseStatementFlags.semiOk))
{
if (flags & ParseStatementFlags.semi)
deprecation("use `{ }` for an empty statement, not `;`");
else
error("use `{ }` for an empty statement, not `;`");
}
nextToken();
s = new AST.ExpStatement(loc, cast(AST.Expression)null);
break;
case TOK.do_:
{
AST.Statement _body;
AST.Expression condition;
nextToken();
const lookingForElseSave = lookingForElse;
lookingForElse = Loc.initial;
_body = parseStatement(ParseStatementFlags.scope_);
lookingForElse = lookingForElseSave;
check(TOK.while_);
check(TOK.leftParentheses);
condition = parseExpression();
check(TOK.rightParentheses);
if (token.value == TOK.semicolon)
nextToken();
else
error("terminating `;` required after do-while statement");
s = new AST.DoStatement(loc, _body, condition, token.loc);
break;
}
case TOK.for_:
{
AST.Statement _init;
AST.Expression condition;
AST.Expression increment;
nextToken();
check(TOK.leftParentheses);
if (token.value == TOK.semicolon)
{
_init = null;
nextToken();
}
else
{
const lookingForElseSave = lookingForElse;
lookingForElse = Loc.initial;
_init = parseStatement(0);
lookingForElse = lookingForElseSave;
}
if (token.value == TOK.semicolon)
{
condition = null;
nextToken();
}
else
{
condition = parseExpression();
check(TOK.semicolon, "`for` condition");
}
if (token.value == TOK.rightParentheses)
{
increment = null;
nextToken();
}
else
{
increment = parseExpression();
check(TOK.rightParentheses);
}
Loc endloc;
AST.Statement _body = parseStatement(ParseStatementFlags.scope_, null, &endloc);
s = new AST.ForStatement(loc, _init, condition, increment, _body, endloc);
break;
}
case TOK.foreach_:
case TOK.foreach_reverse_:
{
s = parseForeach!(false,false)(loc);
break;
}
case TOK.if_:
{
AST.Parameter param = null;
AST.Expression condition;
nextToken();
check(TOK.leftParentheses);
StorageClass storageClass = 0;
StorageClass stc = 0;
LagainStc:
if (stc)
{
storageClass = appendStorageClass(storageClass, stc);
nextToken();
}
switch (token.value)
{
case TOK.ref_:
stc = STC.ref_;
goto LagainStc;
case TOK.auto_:
stc = STC.auto_;
goto LagainStc;
case TOK.const_:
if (peekNext() != TOK.leftParentheses)
{
stc = STC.const_;
goto LagainStc;
}
break;
case TOK.immutable_:
if (peekNext() != TOK.leftParentheses)
{
stc = STC.immutable_;
goto LagainStc;
}
break;
case TOK.shared_:
if (peekNext() != TOK.leftParentheses)
{
stc = STC.shared_;
goto LagainStc;
}
break;
case TOK.inout_:
if (peekNext() != TOK.leftParentheses)
{
stc = STC.wild;
goto LagainStc;
}
break;
default:
break;
}
auto n = peek(&token);
if (storageClass != 0 && token.value == TOK.identifier &&
n.value != TOK.assign && n.value != TOK.identifier)
{
error("found `%s` while expecting `=` or identifier", n.toChars());
}
else if (storageClass != 0 && token.value == TOK.identifier && n.value == TOK.assign)
{
Identifier ai = token.ident;
AST.Type at = null; // infer parameter type
nextToken();
check(TOK.assign);
param = new AST.Parameter(storageClass, at, ai, null, null);
}
else if (isDeclaration(&token, NeedDeclaratorId.must, TOK.assign, null))
{
Identifier ai;
AST.Type at = parseType(&ai);
check(TOK.assign);
param = new AST.Parameter(storageClass, at, ai, null, null);
}
condition = parseExpression();
check(TOK.rightParentheses);
{
const lookingForElseSave = lookingForElse;
lookingForElse = loc;
ifbody = parseStatement(ParseStatementFlags.scope_);
lookingForElse = lookingForElseSave;
}
if (token.value == TOK.else_)
{
const elseloc = token.loc;
nextToken();
elsebody = parseStatement(ParseStatementFlags.scope_);
checkDanglingElse(elseloc);
}
else
elsebody = null;
if (condition && ifbody)
s = new AST.IfStatement(loc, param, condition, ifbody, elsebody, token.loc);
else
s = null; // don't propagate parsing errors
break;
}
case TOK.else_:
error("found `else` without a corresponding `if`, `version` or `debug` statement");
goto Lerror;
case TOK.scope_:
if (peekNext() != TOK.leftParentheses)
goto Ldeclaration; // scope used as storage class
nextToken();
check(TOK.leftParentheses);
if (token.value != TOK.identifier)
{
error("scope identifier expected");
goto Lerror;
}
else
{
TOK t = TOK.onScopeExit;
Identifier id = token.ident;
if (id == Id.exit)
t = TOK.onScopeExit;
else if (id == Id.failure)
t = TOK.onScopeFailure;
else if (id == Id.success)
t = TOK.onScopeSuccess;
else
error("valid scope identifiers are `exit`, `failure`, or `success`, not `%s`", id.toChars());
nextToken();
check(TOK.rightParentheses);
AST.Statement st = parseStatement(ParseStatementFlags.scope_);
s = new AST.ScopeGuardStatement(loc, t, st);
break;
}
case TOK.debug_:
nextToken();
if (token.value == TOK.assign)
{
error("debug conditions can only be declared at module scope");
nextToken();
nextToken();
goto Lerror;
}
cond = parseDebugCondition();
goto Lcondition;
case TOK.version_:
nextToken();
if (token.value == TOK.assign)
{
error("version conditions can only be declared at module scope");
nextToken();
nextToken();
goto Lerror;
}
cond = parseVersionCondition();
goto Lcondition;
Lcondition:
{
const lookingForElseSave = lookingForElse;
lookingForElse = loc;
ifbody = parseStatement(0);
lookingForElse = lookingForElseSave;
}
elsebody = null;
if (token.value == TOK.else_)
{
const elseloc = token.loc;
nextToken();
elsebody = parseStatement(0);
checkDanglingElse(elseloc);
}
s = new AST.ConditionalStatement(loc, cond, ifbody, elsebody);
if (flags & ParseStatementFlags.scope_)
s = new AST.ScopeStatement(loc, s, token.loc);
break;
case TOK.pragma_:
{
Identifier ident;
AST.Expressions* args = null;
AST.Statement _body;
nextToken();
check(TOK.leftParentheses);
if (token.value != TOK.identifier)
{
error("`pragma(identifier)` expected");
goto Lerror;
}
ident = token.ident;
nextToken();
if (token.value == TOK.comma && peekNext() != TOK.rightParentheses)
args = parseArguments(); // pragma(identifier, args...);
else
check(TOK.rightParentheses); // pragma(identifier);
if (token.value == TOK.semicolon)
{
nextToken();
_body = null;
}
else
_body = parseStatement(ParseStatementFlags.semi);
s = new AST.PragmaStatement(loc, ident, args, _body);
break;
}
case TOK.switch_:
isfinal = false;
goto Lswitch;
Lswitch:
{
nextToken();
check(TOK.leftParentheses);
AST.Expression condition = parseExpression();
check(TOK.rightParentheses);
AST.Statement _body = parseStatement(ParseStatementFlags.scope_);
s = new AST.SwitchStatement(loc, condition, _body, isfinal);
break;
}
case TOK.case_:
{
AST.Expression exp;
AST.Expressions cases; // array of Expression's
AST.Expression last = null;
while (1)
{
nextToken();
exp = parseAssignExp();
cases.push(exp);
if (token.value != TOK.comma)
break;
}
check(TOK.colon);
/* case exp: .. case last:
*/
if (token.value == TOK.slice)
{
if (cases.dim > 1)
error("only one `case` allowed for start of case range");
nextToken();
check(TOK.case_);
last = parseAssignExp();
check(TOK.colon);
}
if (flags & ParseStatementFlags.curlyScope)
{
auto statements = new AST.Statements();
while (token.value != TOK.case_ && token.value != TOK.default_ && token.value != TOK.endOfFile && token.value != TOK.rightCurly)
{
statements.push(parseStatement(ParseStatementFlags.semi | ParseStatementFlags.curlyScope));
}
s = new AST.CompoundStatement(loc, statements);
}
else
{
s = parseStatement(ParseStatementFlags.semi);
}
s = new AST.ScopeStatement(loc, s, token.loc);
if (last)
{
s = new AST.CaseRangeStatement(loc, exp, last, s);
}
else
{
// Keep cases in order by building the case statements backwards
for (size_t i = cases.dim; i; i--)
{
exp = cases[i - 1];
s = new AST.CaseStatement(loc, exp, s);
}
}
break;
}
case TOK.default_:
{
nextToken();
check(TOK.colon);
if (flags & ParseStatementFlags.curlyScope)
{
auto statements = new AST.Statements();
while (token.value != TOK.case_ && token.value != TOK.default_ && token.value != TOK.endOfFile && token.value != TOK.rightCurly)
{
statements.push(parseStatement(ParseStatementFlags.semi | ParseStatementFlags.curlyScope));
}
s = new AST.CompoundStatement(loc, statements);
}
else
s = parseStatement(ParseStatementFlags.semi);
s = new AST.ScopeStatement(loc, s, token.loc);
s = new AST.DefaultStatement(loc, s);
break;
}
case TOK.return_:
{
AST.Expression exp;
nextToken();
exp = token.value == TOK.semicolon ? null : parseExpression();
check(TOK.semicolon, "`return` statement");
s = new AST.ReturnStatement(loc, exp);
break;
}
case TOK.break_:
{
Identifier ident;
nextToken();
ident = null;
if (token.value == TOK.identifier)
{
ident = token.ident;
nextToken();
}
check(TOK.semicolon, "`break` statement");
s = new AST.BreakStatement(loc, ident);
break;
}
case TOK.continue_:
{
Identifier ident;
nextToken();
ident = null;
if (token.value == TOK.identifier)
{
ident = token.ident;
nextToken();
}
check(TOK.semicolon, "`continue` statement");
s = new AST.ContinueStatement(loc, ident);
break;
}
case TOK.goto_:
{
Identifier ident;
nextToken();
if (token.value == TOK.default_)
{
nextToken();
s = new AST.GotoDefaultStatement(loc);
}
else if (token.value == TOK.case_)
{
AST.Expression exp = null;
nextToken();
if (token.value != TOK.semicolon)
exp = parseExpression();
s = new AST.GotoCaseStatement(loc, exp);
}
else
{
if (token.value != TOK.identifier)
{
error("identifier expected following `goto`");
ident = null;
}
else
{
ident = token.ident;
nextToken();
}
s = new AST.GotoStatement(loc, ident);
}
check(TOK.semicolon, "`goto` statement");
break;
}
case TOK.synchronized_:
{
AST.Expression exp;
AST.Statement _body;
Token* t = peek(&token);
if (skipAttributes(t, &t) && t.value == TOK.class_)
goto Ldeclaration;
nextToken();
if (token.value == TOK.leftParentheses)
{
nextToken();
exp = parseExpression();
check(TOK.rightParentheses);
}
else
exp = null;
_body = parseStatement(ParseStatementFlags.scope_);
s = new AST.SynchronizedStatement(loc, exp, _body);
break;
}
case TOK.with_:
{
AST.Expression exp;
AST.Statement _body;
Loc endloc = loc;
nextToken();
check(TOK.leftParentheses);
exp = parseExpression();
check(TOK.rightParentheses);
_body = parseStatement(ParseStatementFlags.scope_, null, &endloc);
s = new AST.WithStatement(loc, exp, _body, endloc);
break;
}
case TOK.try_:
{
AST.Statement _body;
AST.Catches* catches = null;
AST.Statement finalbody = null;
nextToken();
const lookingForElseSave = lookingForElse;
lookingForElse = Loc.initial;
_body = parseStatement(ParseStatementFlags.scope_);
lookingForElse = lookingForElseSave;
while (token.value == TOK.catch_)
{
AST.Statement handler;
AST.Catch c;
AST.Type t;
Identifier id;
const catchloc = token.loc;
nextToken();
if (token.value == TOK.leftCurly || token.value != TOK.leftParentheses)
{
t = null;
id = null;
}
else
{
check(TOK.leftParentheses);
id = null;
t = parseType(&id);
check(TOK.rightParentheses);
}
handler = parseStatement(0);
c = new AST.Catch(catchloc, t, id, handler);
if (!catches)
catches = new AST.Catches();
catches.push(c);
}
if (token.value == TOK.finally_)
{
nextToken();
finalbody = parseStatement(ParseStatementFlags.scope_);
}
s = _body;
if (!catches && !finalbody)
error("`catch` or `finally` expected following `try`");
else
{
if (catches)
s = new AST.TryCatchStatement(loc, _body, catches);
if (finalbody)
s = new AST.TryFinallyStatement(loc, s, finalbody);
}
break;
}
case TOK.throw_:
{
AST.Expression exp;
nextToken();
exp = parseExpression();
check(TOK.semicolon, "`throw` statement");
s = new AST.ThrowStatement(loc, exp);
break;
}
case TOK.asm_:
{
// Parse the asm block into a sequence of AsmStatements,
// each AsmStatement is one instruction.
// Separate out labels.
// Defer parsing of AsmStatements until semantic processing.
Loc labelloc;
nextToken();
StorageClass stc = parsePostfix(STC.undefined_, null);
if (stc & (STC.const_ | STC.immutable_ | STC.shared_ | STC.wild))
error("`const`/`immutable`/`shared`/`inout` attributes are not allowed on `asm` blocks");
check(TOK.leftCurly);
Token* toklist = null;
Token** ptoklist = &toklist;
Identifier label = null;
auto statements = new AST.Statements();
size_t nestlevel = 0;
while (1)
{
switch (token.value)
{
case TOK.identifier:
if (!toklist)
{
// Look ahead to see if it is a label
if (peekNext() == TOK.colon)
{
// It's a label
label = token.ident;
labelloc = token.loc;
nextToken();
nextToken();
continue;
}
}
goto default;
case TOK.leftCurly:
++nestlevel;
goto default;
case TOK.rightCurly:
if (nestlevel > 0)
{
--nestlevel;
goto default;
}
if (toklist || label)
{
error("`asm` statements must end in `;`");
}
break;
case TOK.semicolon:
if (nestlevel != 0)
error("mismatched number of curly brackets");
s = null;
if (toklist || label)
{
// Create AsmStatement from list of tokens we've saved
s = new AST.AsmStatement(token.loc, toklist);
toklist = null;
ptoklist = &toklist;
if (label)
{
s = new AST.LabelStatement(labelloc, label, s);
label = null;
}
statements.push(s);
}
nextToken();
continue;
case TOK.endOfFile:
/* { */
error("matching `}` expected, not end of file");
goto Lerror;
default:
*ptoklist = allocateToken();
memcpy(*ptoklist, &token, Token.sizeof);
ptoklist = &(*ptoklist).next;
*ptoklist = null;
nextToken();
continue;
}
break;
}
s = new AST.CompoundAsmStatement(loc, statements, stc);
nextToken();
break;
}
case TOK.import_:
{
/* https://issues.dlang.org/show_bug.cgi?id=16088
*
* At this point it can either be an
* https://dlang.org/spec/grammar.html#ImportExpression
* or an
* https://dlang.org/spec/grammar.html#ImportDeclaration.
* See if the next token after `import` is a `(`; if so,
* then it is an import expression.
*/
if (peekNext() == TOK.leftParentheses)
{
AST.Expression e = parseExpression();
check(TOK.semicolon);
s = new AST.ExpStatement(loc, e);
}
else
{
AST.Dsymbols* imports = parseImport();
s = new AST.ImportStatement(loc, imports);
if (flags & ParseStatementFlags.scope_)
s = new AST.ScopeStatement(loc, s, token.loc);
}
break;
}
case TOK.template_:
{
AST.Dsymbol d = parseTemplateDeclaration();
s = new AST.ExpStatement(loc, d);
break;
}
default:
error("found `%s` instead of statement", token.toChars());
goto Lerror;
Lerror:
while (token.value != TOK.rightCurly && token.value != TOK.semicolon && token.value != TOK.endOfFile)
nextToken();
if (token.value == TOK.semicolon)
nextToken();
s = null;
break;
}
if (pEndloc)
*pEndloc = prevloc;
return s;
}
/*****************************************
* Parse initializer for variable declaration.
*/
private AST.Initializer parseInitializer()
{
AST.StructInitializer _is;
AST.ArrayInitializer ia;
AST.ExpInitializer ie;
AST.Expression e;
Identifier id;
AST.Initializer value;
int comma;
const loc = token.loc;
Token* t;
int braces;
int brackets;
switch (token.value)
{
case TOK.leftCurly:
/* Scan ahead to discern between a struct initializer and
* parameterless function literal.
*
* We'll scan the topmost curly bracket level for statement-related
* tokens, thereby ruling out a struct initializer. (A struct
* initializer which itself contains function literals may have
* statements at nested curly bracket levels.)
*
* It's important that this function literal check not be
* pendantic, otherwise a function having the slightest syntax
* error would emit confusing errors when we proceed to parse it
* as a struct initializer.
*
* The following two ambiguous cases will be treated as a struct
* initializer (best we can do without type info):
* {}
* {{statements...}} - i.e. it could be struct initializer
* with one function literal, or function literal having an
* extra level of curly brackets
* If a function literal is intended in these cases (unlikely),
* source can use a more explicit function literal syntax
* (e.g. prefix with "()" for empty parameter list).
*/
braces = 1;
for (t = peek(&token); 1; t = peek(t))
{
switch (t.value)
{
/* Look for a semicolon or keyword of statements which don't
* require a semicolon (typically containing BlockStatement).
* Tokens like "else", "catch", etc. are omitted where the
* leading token of the statement is sufficient.
*/
case TOK.asm_:
case TOK.class_:
case TOK.debug_:
case TOK.enum_:
case TOK.if_:
case TOK.interface_:
case TOK.pragma_:
case TOK.scope_:
case TOK.semicolon:
case TOK.struct_:
case TOK.switch_:
case TOK.synchronized_:
case TOK.try_:
case TOK.union_:
case TOK.version_:
case TOK.while_:
case TOK.with_:
if (braces == 1)
goto Lexpression;
continue;
case TOK.leftCurly:
braces++;
continue;
case TOK.rightCurly:
if (--braces == 0)
break;
continue;
case TOK.endOfFile:
break;
default:
continue;
}
break;
}
_is = new AST.StructInitializer(loc);
nextToken();
comma = 2;
while (1)
{
switch (token.value)
{
case TOK.identifier:
if (comma == 1)
error("comma expected separating field initializers");
t = peek(&token);
if (t.value == TOK.colon)
{
id = token.ident;
nextToken();
nextToken(); // skip over ':'
}
else
{
id = null;
}
value = parseInitializer();
_is.addInit(id, value);
comma = 1;
continue;
case TOK.comma:
if (comma == 2)
error("expression expected, not `,`");
nextToken();
comma = 2;
continue;
case TOK.rightCurly: // allow trailing comma's
nextToken();
break;
case TOK.endOfFile:
error("found end of file instead of initializer");
break;
default:
if (comma == 1)
error("comma expected separating field initializers");
value = parseInitializer();
_is.addInit(null, value);
comma = 1;
continue;
//error("found `%s` instead of field initializer", token.toChars());
//break;
}
break;
}
return _is;
case TOK.leftBracket:
/* Scan ahead to see if it is an array initializer or
* an expression.
* If it ends with a ';' ',' or '}', it is an array initializer.
*/
brackets = 1;
for (t = peek(&token); 1; t = peek(t))
{
switch (t.value)
{
case TOK.leftBracket:
brackets++;
continue;
case TOK.rightBracket:
if (--brackets == 0)
{
t = peek(t);
if (t.value != TOK.semicolon && t.value != TOK.comma && t.value != TOK.rightBracket && t.value != TOK.rightCurly)
goto Lexpression;
break;
}
continue;
case TOK.endOfFile:
break;
default:
continue;
}
break;
}
ia = new AST.ArrayInitializer(loc);
nextToken();
comma = 2;
while (1)
{
switch (token.value)
{
default:
if (comma == 1)
{
error("comma expected separating array initializers, not `%s`", token.toChars());
nextToken();
break;
}
e = parseAssignExp();
if (!e)
break;
if (token.value == TOK.colon)
{
nextToken();
value = parseInitializer();
}
else
{
value = new AST.ExpInitializer(e.loc, e);
e = null;
}
ia.addInit(e, value);
comma = 1;
continue;
case TOK.leftCurly:
case TOK.leftBracket:
if (comma == 1)
error("comma expected separating array initializers, not `%s`", token.toChars());
value = parseInitializer();
if (token.value == TOK.colon)
{
nextToken();
if (auto ei = value.isExpInitializer())
{
e = ei.exp;
value = parseInitializer();
}
else
error("initializer expression expected following colon, not `%s`", token.toChars());
}
else
e = null;
ia.addInit(e, value);
comma = 1;
continue;
case TOK.comma:
if (comma == 2)
error("expression expected, not `,`");
nextToken();
comma = 2;
continue;
case TOK.rightBracket: // allow trailing comma's
nextToken();
break;
case TOK.endOfFile:
error("found `%s` instead of array initializer", token.toChars());
break;
}
break;
}
return ia;
case TOK.void_:
const tv = peekNext();
if (tv == TOK.semicolon || tv == TOK.comma)
{
nextToken();
return new AST.VoidInitializer(loc);
}
goto Lexpression;
default:
Lexpression:
e = parseAssignExp();
ie = new AST.ExpInitializer(loc, e);
return ie;
}
}
/*****************************************
* Parses default argument initializer expression that is an assign expression,
* with special handling for __FILE__, __FILE_DIR__, __LINE__, __MODULE__, __FUNCTION__, and __PRETTY_FUNCTION__.
*/
private AST.Expression parseDefaultInitExp()
{
AST.Expression e = null;
const tv = peekNext();
if (tv == TOK.comma || tv == TOK.rightParentheses)
{
switch (token.value)
{
case TOK.file: e = new AST.FileInitExp(token.loc, TOK.file); break;
case TOK.fileFullPath: e = new AST.FileInitExp(token.loc, TOK.fileFullPath); break;
case TOK.line: e = new AST.LineInitExp(token.loc); break;
case TOK.moduleString: e = new AST.ModuleInitExp(token.loc); break;
case TOK.functionString: e = new AST.FuncInitExp(token.loc); break;
case TOK.prettyFunction: e = new AST.PrettyFuncInitExp(token.loc); break;
default: goto LExp;
}
nextToken();
return e;
}
LExp:
return parseAssignExp();
}
private void check(Loc loc, TOK value)
{
if (token.value != value)
error(loc, "found `%s` when expecting `%s`", token.toChars(), Token.toChars(value));
nextToken();
}
void check(TOK value)
{
check(token.loc, value);
}
private void check(TOK value, const(char)* string)
{
if (token.value != value)
error("found `%s` when expecting `%s` following %s", token.toChars(), Token.toChars(value), string);
nextToken();
}
private void checkParens(TOK value, AST.Expression e)
{
if (precedence[e.op] == PREC.rel && !e.parens)
error(e.loc, "`%s` must be surrounded by parentheses when next to operator `%s`", e.toChars(), Token.toChars(value));
}
///
private enum NeedDeclaratorId
{
no, // Declarator part must have no identifier
opt, // Declarator part identifier is optional
must, // Declarator part must have identifier
mustIfDstyle, // Declarator part must have identifier, but don't recognize old C-style syntax
}
/************************************
* Determine if the scanner is sitting on the start of a declaration.
* Params:
* t = current token of the scanner
* needId = flag with additional requirements for a declaration
* endtok = ending token
* pt = will be set ending token (if not null)
* Output:
* true if the token `t` is a declaration, false otherwise
*/
private bool isDeclaration(Token* t, NeedDeclaratorId needId, TOK endtok, Token** pt)
{
//printf("isDeclaration(needId = %d)\n", needId);
int haveId = 0;
int haveTpl = 0;
while (1)
{
if ((t.value == TOK.const_ || t.value == TOK.immutable_ || t.value == TOK.inout_ || t.value == TOK.shared_) && peek(t).value != TOK.leftParentheses)
{
/* const type
* immutable type
* shared type
* wild type
*/
t = peek(t);
continue;
}
break;
}
if (!isBasicType(&t))
{
goto Lisnot;
}
if (!isDeclarator(&t, &haveId, &haveTpl, endtok, needId != NeedDeclaratorId.mustIfDstyle))
goto Lisnot;
if ((needId == NeedDeclaratorId.no && !haveId) ||
(needId == NeedDeclaratorId.opt) ||
(needId == NeedDeclaratorId.must && haveId) ||
(needId == NeedDeclaratorId.mustIfDstyle && haveId))
{
if (pt)
*pt = t;
goto Lis;
}
goto Lisnot;
Lis:
//printf("\tis declaration, t = %s\n", t.toChars());
return true;
Lisnot:
//printf("\tis not declaration\n");
return false;
}
private bool isBasicType(Token** pt)
{
// This code parallels parseBasicType()
Token* t = *pt;
switch (t.value)
{
case TOK.wchar_:
case TOK.dchar_:
case TOK.bool_:
case TOK.char_:
case TOK.int8:
case TOK.uns8:
case TOK.int16:
case TOK.uns16:
case TOK.int32:
case TOK.uns32:
case TOK.int64:
case TOK.uns64:
case TOK.int128:
case TOK.uns128:
case TOK.float32:
case TOK.float64:
case TOK.float80:
case TOK.imaginary32:
case TOK.imaginary64:
case TOK.imaginary80:
case TOK.complex32:
case TOK.complex64:
case TOK.complex80:
case TOK.void_:
t = peek(t);
break;
case TOK.identifier:
L5:
t = peek(t);
if (t.value == TOK.not)
{
goto L4;
}
goto L3;
while (1)
{
L2:
t = peek(t);
L3:
if (t.value == TOK.dot)
{
Ldot:
t = peek(t);
if (t.value != TOK.identifier)
goto Lfalse;
t = peek(t);
if (t.value != TOK.not)
goto L3;
L4:
/* Seen a !
* Look for:
* !( args ), !identifier, etc.
*/
t = peek(t);
switch (t.value)
{
case TOK.identifier:
goto L5;
case TOK.leftParentheses:
if (!skipParens(t, &t))
goto Lfalse;
goto L3;
case TOK.wchar_:
case TOK.dchar_:
case TOK.bool_:
case TOK.char_:
case TOK.int8:
case TOK.uns8:
case TOK.int16:
case TOK.uns16:
case TOK.int32:
case TOK.uns32:
case TOK.int64:
case TOK.uns64:
case TOK.int128:
case TOK.uns128:
case TOK.float32:
case TOK.float64:
case TOK.float80:
case TOK.imaginary32:
case TOK.imaginary64:
case TOK.imaginary80:
case TOK.complex32:
case TOK.complex64:
case TOK.complex80:
case TOK.void_:
case TOK.int32Literal:
case TOK.uns32Literal:
case TOK.int64Literal:
case TOK.uns64Literal:
case TOK.int128Literal:
case TOK.uns128Literal:
case TOK.float32Literal:
case TOK.float64Literal:
case TOK.float80Literal:
case TOK.imaginary32Literal:
case TOK.imaginary64Literal:
case TOK.imaginary80Literal:
case TOK.null_:
case TOK.true_:
case TOK.false_:
case TOK.charLiteral:
case TOK.wcharLiteral:
case TOK.dcharLiteral:
case TOK.string_:
case TOK.hexadecimalString:
case TOK.file:
case TOK.fileFullPath:
case TOK.line:
case TOK.moduleString:
case TOK.functionString:
case TOK.prettyFunction:
goto L2;
default:
goto Lfalse;
}
}
break;
}
break;
case TOK.dot:
goto Ldot;
case TOK.typeof_:
case TOK.vector:
case TOK.mixin_:
/* typeof(exp).identifier...
*/
t = peek(t);
if (!skipParens(t, &t))
goto Lfalse;
goto L3;
case TOK.traits:
// __traits(getMember
t = peek(t);
if (t.value != TOK.leftParentheses)
goto Lfalse;
auto lp = t;
t = peek(t);
if (t.value != TOK.identifier || t.ident != Id.getMember)
goto Lfalse;
if (!skipParens(lp, &lp))
goto Lfalse;
// we are in a lookup for decl VS statement
// so we expect a declarator following __trait if it's a type.
// other usages wont be ambiguous (alias, template instance, type qual, etc.)
if (lp.value != TOK.identifier)
goto Lfalse;
break;
case TOK.const_:
case TOK.immutable_:
case TOK.shared_:
case TOK.inout_:
// const(type) or immutable(type) or shared(type) or wild(type)
t = peek(t);
if (t.value != TOK.leftParentheses)
goto Lfalse;
t = peek(t);
if (!isDeclaration(t, NeedDeclaratorId.no, TOK.rightParentheses, &t))
{
goto Lfalse;
}
t = peek(t);
break;
default:
goto Lfalse;
}
*pt = t;
//printf("is\n");
return true;
Lfalse:
//printf("is not\n");
return false;
}
private bool isDeclarator(Token** pt, int* haveId, int* haveTpl, TOK endtok, bool allowAltSyntax = true)
{
// This code parallels parseDeclarator()
Token* t = *pt;
int parens;
//printf("Parser::isDeclarator() %s\n", t.toChars());
if (t.value == TOK.assign)
return false;
while (1)
{
parens = false;
switch (t.value)
{
case TOK.mul:
//case TOK.and:
t = peek(t);
continue;
case TOK.leftBracket:
t = peek(t);
if (t.value == TOK.rightBracket)
{
t = peek(t);
}
else if (isDeclaration(t, NeedDeclaratorId.no, TOK.rightBracket, &t))
{
// It's an associative array declaration
t = peek(t);
// ...[type].ident
if (t.value == TOK.dot && peek(t).value == TOK.identifier)
{
t = peek(t);
t = peek(t);
}
}
else
{
// [ expression ]
// [ expression .. expression ]
if (!isExpression(&t))
return false;
if (t.value == TOK.slice)
{
t = peek(t);
if (!isExpression(&t))
return false;
if (t.value != TOK.rightBracket)
return false;
t = peek(t);
}
else
{
if (t.value != TOK.rightBracket)
return false;
t = peek(t);
// ...[index].ident
if (t.value == TOK.dot && peek(t).value == TOK.identifier)
{
t = peek(t);
t = peek(t);
}
}
}
continue;
case TOK.identifier:
if (*haveId)
return false;
*haveId = true;
t = peek(t);
break;
case TOK.leftParentheses:
if (!allowAltSyntax)
return false; // Do not recognize C-style declarations.
t = peek(t);
if (t.value == TOK.rightParentheses)
return false; // () is not a declarator
/* Regard ( identifier ) as not a declarator
* BUG: what about ( *identifier ) in
* f(*p)(x);
* where f is a class instance with overloaded () ?
* Should we just disallow C-style function pointer declarations?
*/
if (t.value == TOK.identifier)
{
Token* t2 = peek(t);
if (t2.value == TOK.rightParentheses)
return false;
}
if (!isDeclarator(&t, haveId, null, TOK.rightParentheses))
return false;
t = peek(t);
parens = true;
break;
case TOK.delegate_:
case TOK.function_:
t = peek(t);
if (!isParameters(&t))
return false;
skipAttributes(t, &t);
continue;
default:
break;
}
break;
}
while (1)
{
switch (t.value)
{
static if (CARRAYDECL)
{
case TOK.leftBracket:
parens = false;
t = peek(t);
if (t.value == TOK.rightBracket)
{
t = peek(t);
}
else if (isDeclaration(t, NeedDeclaratorId.no, TOK.rightBracket, &t))
{
// It's an associative array declaration
t = peek(t);
}
else
{
// [ expression ]
if (!isExpression(&t))
return false;
if (t.value != TOK.rightBracket)
return false;
t = peek(t);
}
continue;
}
case TOK.leftParentheses:
parens = false;
if (Token* tk = peekPastParen(t))
{
if (tk.value == TOK.leftParentheses)
{
if (!haveTpl)
return false;
*haveTpl = 1;
t = tk;
}
else if (tk.value == TOK.assign)
{
if (!haveTpl)
return false;
*haveTpl = 1;
*pt = tk;
return true;
}
}
if (!isParameters(&t))
return false;
while (1)
{
switch (t.value)
{
case TOK.const_:
case TOK.immutable_:
case TOK.shared_:
case TOK.inout_:
case TOK.pure_:
case TOK.nothrow_:
case TOK.return_:
case TOK.scope_:
t = peek(t);
continue;
case TOK.at:
t = peek(t); // skip '@'
t = peek(t); // skip identifier
continue;
default:
break;
}
break;
}
continue;
// Valid tokens that follow a declaration
case TOK.rightParentheses:
case TOK.rightBracket:
case TOK.assign:
case TOK.comma:
case TOK.dotDotDot:
case TOK.semicolon:
case TOK.leftCurly:
case TOK.in_:
case TOK.out_:
case TOK.do_:
// The !parens is to disallow unnecessary parentheses
if (!parens && (endtok == TOK.reserved || endtok == t.value))
{
*pt = t;
return true;
}
return false;
case TOK.identifier:
if (t.ident == Id._body)
{
version (none)
{
// This deprecation has been disabled for the time being, see PR10763
// @@@DEPRECATED@@@
// https://github.com/dlang/DIPs/blob/1f5959abe482b1f9094f6484a7d0a3ade77fc2fc/DIPs/accepted/DIP1003.md
// Deprecated in 2.091 - Can be removed from 2.101
deprecation("Usage of the `body` keyword is deprecated. Use `do` instead.");
}
goto case TOK.do_;
}
goto default;
case TOK.if_:
return haveTpl ? true : false;
// Used for mixin type parsing
case TOK.endOfFile:
if (endtok == TOK.endOfFile)
goto case TOK.do_;
return false;
default:
return false;
}
}
assert(0);
}
private bool isParameters(Token** pt)
{
// This code parallels parseParameters()
Token* t = *pt;
//printf("isParameters()\n");
if (t.value != TOK.leftParentheses)
return false;
t = peek(t);
for (; 1; t = peek(t))
{
L1:
switch (t.value)
{
case TOK.rightParentheses:
break;
case TOK.dotDotDot:
t = peek(t);
break;
case TOK.in_:
case TOK.out_:
case TOK.ref_:
case TOK.lazy_:
case TOK.scope_:
case TOK.final_:
case TOK.auto_:
case TOK.return_:
continue;
case TOK.const_:
case TOK.immutable_:
case TOK.shared_:
case TOK.inout_:
t = peek(t);
if (t.value == TOK.leftParentheses)
{
t = peek(t);
if (!isDeclaration(t, NeedDeclaratorId.no, TOK.rightParentheses, &t))
return false;
t = peek(t); // skip past closing ')'
goto L2;
}
goto L1;
version (none)
{
case TOK.static_:
continue;
case TOK.auto_:
case TOK.alias_:
t = peek(t);
if (t.value == TOK.identifier)
t = peek(t);
if (t.value == TOK.assign)
{
t = peek(t);
if (!isExpression(&t))
return false;
}
goto L3;
}
default:
{
if (!isBasicType(&t))
return false;
L2:
int tmp = false;
if (t.value != TOK.dotDotDot && !isDeclarator(&t, &tmp, null, TOK.reserved))
return false;
if (t.value == TOK.assign)
{
t = peek(t);
if (!isExpression(&t))
return false;
}
if (t.value == TOK.dotDotDot)
{
t = peek(t);
break;
}
}
if (t.value == TOK.comma)
{
continue;
}
break;
}
break;
}
if (t.value != TOK.rightParentheses)
return false;
t = peek(t);
*pt = t;
return true;
}
private bool isExpression(Token** pt)
{
// This is supposed to determine if something is an expression.
// What it actually does is scan until a closing right bracket
// is found.
Token* t = *pt;
int brnest = 0;
int panest = 0;
int curlynest = 0;
for (;; t = peek(t))
{
switch (t.value)
{
case TOK.leftBracket:
brnest++;
continue;
case TOK.rightBracket:
if (--brnest >= 0)
continue;
break;
case TOK.leftParentheses:
panest++;
continue;
case TOK.comma:
if (brnest || panest)
continue;
break;
case TOK.rightParentheses:
if (--panest >= 0)
continue;
break;
case TOK.leftCurly:
curlynest++;
continue;
case TOK.rightCurly:
if (--curlynest >= 0)
continue;
return false;
case TOK.slice:
if (brnest)
continue;
break;
case TOK.semicolon:
if (curlynest)
continue;
return false;
case TOK.endOfFile:
return false;
default:
continue;
}
break;
}
*pt = t;
return true;
}
/*******************************************
* Skip parens, brackets.
* Input:
* t is on opening $(LPAREN)
* Output:
* *pt is set to closing token, which is '$(RPAREN)' on success
* Returns:
* true successful
* false some parsing error
*/
private bool skipParens(Token* t, Token** pt)
{
if (t.value != TOK.leftParentheses)
return false;
int parens = 0;
while (1)
{
switch (t.value)
{
case TOK.leftParentheses:
parens++;
break;
case TOK.rightParentheses:
parens--;
if (parens < 0)
goto Lfalse;
if (parens == 0)
goto Ldone;
break;
case TOK.endOfFile:
goto Lfalse;
default:
break;
}
t = peek(t);
}
Ldone:
if (pt)
*pt = peek(t); // skip found rparen
return true;
Lfalse:
return false;
}
private bool skipParensIf(Token* t, Token** pt)
{
if (t.value != TOK.leftParentheses)
{
if (pt)
*pt = t;
return true;
}
return skipParens(t, pt);
}
//returns true if the next value (after optional matching parens) is expected
private bool hasOptionalParensThen(Token* t, TOK expected)
{
Token* tk;
if (!skipParensIf(t, &tk))
return false;
return tk.value == expected;
}
/*******************************************
* Skip attributes.
* Input:
* t is on a candidate attribute
* Output:
* *pt is set to first non-attribute token on success
* Returns:
* true successful
* false some parsing error
*/
private bool skipAttributes(Token* t, Token** pt)
{
while (1)
{
switch (t.value)
{
case TOK.const_:
case TOK.immutable_:
case TOK.shared_:
case TOK.inout_:
case TOK.final_:
case TOK.auto_:
case TOK.scope_:
case TOK.override_:
case TOK.abstract_:
case TOK.synchronized_:
break;
case TOK.deprecated_:
if (peek(t).value == TOK.leftParentheses)
{
t = peek(t);
if (!skipParens(t, &t))
goto Lerror;
// t is on the next of closing parenthesis
continue;
}
break;
case TOK.nothrow_:
case TOK.pure_:
case TOK.ref_:
case TOK.gshared:
case TOK.return_:
break;
case TOK.at:
t = peek(t);
if (t.value == TOK.identifier)
{
/* @identifier
* @identifier!arg
* @identifier!(arglist)
* any of the above followed by (arglist)
* @predefined_attribute
*/
if (isBuiltinAtAttribute(t.ident))
break;
t = peek(t);
if (t.value == TOK.not)
{
t = peek(t);
if (t.value == TOK.leftParentheses)
{
// @identifier!(arglist)
if (!skipParens(t, &t))
goto Lerror;
// t is on the next of closing parenthesis
}
else
{
// @identifier!arg
// Do low rent skipTemplateArgument
if (t.value == TOK.vector)
{
// identifier!__vector(type)
t = peek(t);
if (!skipParens(t, &t))
goto Lerror;
}
else
t = peek(t);
}
}
if (t.value == TOK.leftParentheses)
{
if (!skipParens(t, &t))
goto Lerror;
// t is on the next of closing parenthesis
continue;
}
continue;
}
if (t.value == TOK.leftParentheses)
{
// @( ArgumentList )
if (!skipParens(t, &t))
goto Lerror;
// t is on the next of closing parenthesis
continue;
}
goto Lerror;
default:
goto Ldone;
}
t = peek(t);
}
Ldone:
if (pt)
*pt = t;
return true;
Lerror:
return false;
}
AST.Expression parseExpression()
{
auto loc = token.loc;
//printf("Parser::parseExpression() loc = %d\n", loc.linnum);
auto e = parseAssignExp();
while (token.value == TOK.comma)
{
nextToken();
auto e2 = parseAssignExp();
e = new AST.CommaExp(loc, e, e2, false);
loc = token.loc;
}
return e;
}
/********************************* Expression Parser ***************************/
AST.Expression parsePrimaryExp()
{
AST.Expression e;
AST.Type t;
Identifier id;
const loc = token.loc;
//printf("parsePrimaryExp(): loc = %d\n", loc.linnum);
switch (token.value)
{
case TOK.identifier:
{
if (peekNext() == TOK.min && peekNext2() == TOK.greaterThan)
{
// skip ident.
nextToken();
nextToken();
nextToken();
error("use `.` for member lookup, not `->`");
goto Lerr;
}
if (peekNext() == TOK.goesTo)
goto case_delegate;
id = token.ident;
nextToken();
TOK save;
if (token.value == TOK.not && (save = peekNext()) != TOK.is_ && save != TOK.in_)
{
// identifier!(template-argument-list)
auto tempinst = new AST.TemplateInstance(loc, id, parseTemplateArguments());
e = new AST.ScopeExp(loc, tempinst);
}
else
e = new AST.IdentifierExp(loc, id);
break;
}
case TOK.dollar:
if (!inBrackets)
error("`$` is valid only inside [] of index or slice");
e = new AST.DollarExp(loc);
nextToken();
break;
case TOK.dot:
// Signal global scope '.' operator with "" identifier
e = new AST.IdentifierExp(loc, Id.empty);
break;
case TOK.this_:
e = new AST.ThisExp(loc);
nextToken();
break;
case TOK.super_:
e = new AST.SuperExp(loc);
nextToken();
break;
case TOK.int32Literal:
e = new AST.IntegerExp(loc, cast(d_int32)token.intvalue, AST.Type.tint32);
nextToken();
break;
case TOK.uns32Literal:
e = new AST.IntegerExp(loc, cast(d_uns32)token.unsvalue, AST.Type.tuns32);
nextToken();
break;
case TOK.int64Literal:
e = new AST.IntegerExp(loc, token.intvalue, AST.Type.tint64);
nextToken();
break;
case TOK.uns64Literal:
e = new AST.IntegerExp(loc, token.unsvalue, AST.Type.tuns64);
nextToken();
break;
case TOK.float32Literal:
e = new AST.RealExp(loc, token.floatvalue, AST.Type.tfloat32);
nextToken();
break;
case TOK.float64Literal:
e = new AST.RealExp(loc, token.floatvalue, AST.Type.tfloat64);
nextToken();
break;
case TOK.float80Literal:
e = new AST.RealExp(loc, token.floatvalue, AST.Type.tfloat80);
nextToken();
break;
case TOK.imaginary32Literal:
e = new AST.RealExp(loc, token.floatvalue, AST.Type.timaginary32);
nextToken();
break;
case TOK.imaginary64Literal:
e = new AST.RealExp(loc, token.floatvalue, AST.Type.timaginary64);
nextToken();
break;
case TOK.imaginary80Literal:
e = new AST.RealExp(loc, token.floatvalue, AST.Type.timaginary80);
nextToken();
break;
case TOK.null_:
e = new AST.NullExp(loc);
nextToken();
break;
case TOK.file:
{
const(char)* s = loc.filename ? loc.filename : mod.ident.toChars();
e = new AST.StringExp(loc, s.toDString());
nextToken();
break;
}
case TOK.fileFullPath:
{
assert(loc.isValid(), "__FILE_FULL_PATH__ does not work with an invalid location");
const s = FileName.toAbsolute(loc.filename);
e = new AST.StringExp(loc, s.toDString());
nextToken();
break;
}
case TOK.line:
e = new AST.IntegerExp(loc, loc.linnum, AST.Type.tint32);
nextToken();
break;
case TOK.moduleString:
{
const(char)* s = md ? md.toChars() : mod.toChars();
e = new AST.StringExp(loc, s.toDString());
nextToken();
break;
}
case TOK.functionString:
e = new AST.FuncInitExp(loc);
nextToken();
break;
case TOK.prettyFunction:
e = new AST.PrettyFuncInitExp(loc);
nextToken();
break;
case TOK.true_:
e = new AST.IntegerExp(loc, 1, AST.Type.tbool);
nextToken();
break;
case TOK.false_:
e = new AST.IntegerExp(loc, 0, AST.Type.tbool);
nextToken();
break;
case TOK.charLiteral:
e = new AST.IntegerExp(loc, cast(d_uns8)token.unsvalue, AST.Type.tchar);
nextToken();
break;
case TOK.wcharLiteral:
e = new AST.IntegerExp(loc, cast(d_uns16)token.unsvalue, AST.Type.twchar);
nextToken();
break;
case TOK.dcharLiteral:
e = new AST.IntegerExp(loc, cast(d_uns32)token.unsvalue, AST.Type.tdchar);
nextToken();
break;
case TOK.string_:
case TOK.hexadecimalString:
{
// cat adjacent strings
auto s = token.ustring;
auto len = token.len;
auto postfix = token.postfix;
while (1)
{
const prev = token;
nextToken();
if (token.value == TOK.string_ || token.value == TOK.hexadecimalString)
{
if (token.postfix)
{
if (token.postfix != postfix)
error("mismatched string literal postfixes `'%c'` and `'%c'`", postfix, token.postfix);
postfix = token.postfix;
}
error("Implicit string concatenation is deprecated, use %s ~ %s instead",
prev.toChars(), token.toChars());
const len1 = len;
const len2 = token.len;
len = len1 + len2;
auto s2 = cast(char*)mem.xmalloc_noscan(len * char.sizeof);
memcpy(s2, s, len1 * char.sizeof);
memcpy(s2 + len1, token.ustring, len2 * char.sizeof);
s = s2;
}
else
break;
}
e = new AST.StringExp(loc, s[0 .. len], len, 1, postfix);
break;
}
case TOK.void_:
t = AST.Type.tvoid;
goto LabelX;
case TOK.int8:
t = AST.Type.tint8;
goto LabelX;
case TOK.uns8:
t = AST.Type.tuns8;
goto LabelX;
case TOK.int16:
t = AST.Type.tint16;
goto LabelX;
case TOK.uns16:
t = AST.Type.tuns16;
goto LabelX;
case TOK.int32:
t = AST.Type.tint32;
goto LabelX;
case TOK.uns32:
t = AST.Type.tuns32;
goto LabelX;
case TOK.int64:
t = AST.Type.tint64;
goto LabelX;
case TOK.uns64:
t = AST.Type.tuns64;
goto LabelX;
case TOK.int128:
t = AST.Type.tint128;
goto LabelX;
case TOK.uns128:
t = AST.Type.tuns128;
goto LabelX;
case TOK.float32:
t = AST.Type.tfloat32;
goto LabelX;
case TOK.float64:
t = AST.Type.tfloat64;
goto LabelX;
case TOK.float80:
t = AST.Type.tfloat80;
goto LabelX;
case TOK.imaginary32:
t = AST.Type.timaginary32;
goto LabelX;
case TOK.imaginary64:
t = AST.Type.timaginary64;
goto LabelX;
case TOK.imaginary80:
t = AST.Type.timaginary80;
goto LabelX;
case TOK.complex32:
t = AST.Type.tcomplex32;
goto LabelX;
case TOK.complex64:
t = AST.Type.tcomplex64;
goto LabelX;
case TOK.complex80:
t = AST.Type.tcomplex80;
goto LabelX;
case TOK.bool_:
t = AST.Type.tbool;
goto LabelX;
case TOK.char_:
t = AST.Type.tchar;
goto LabelX;
case TOK.wchar_:
t = AST.Type.twchar;
goto LabelX;
case TOK.dchar_:
t = AST.Type.tdchar;
goto LabelX;
LabelX:
nextToken();
if (token.value == TOK.leftParentheses)
{
e = new AST.TypeExp(loc, t);
e = new AST.CallExp(loc, e, parseArguments());
break;
}
check(TOK.dot, t.toChars());
if (token.value != TOK.identifier)
{
error("found `%s` when expecting identifier following `%s`.", token.toChars(), t.toChars());
goto Lerr;
}
e = new AST.DotIdExp(loc, new AST.TypeExp(loc, t), token.ident);
nextToken();
break;
case TOK.typeof_:
{
t = parseTypeof();
e = new AST.TypeExp(loc, t);
break;
}
case TOK.vector:
{
t = parseVector();
e = new AST.TypeExp(loc, t);
break;
}
case TOK.typeid_:
{
nextToken();
check(TOK.leftParentheses, "`typeid`");
RootObject o = parseTypeOrAssignExp();
check(TOK.rightParentheses);
e = new AST.TypeidExp(loc, o);
break;
}
case TOK.traits:
{
/* __traits(identifier, args...)
*/
Identifier ident;
AST.Objects* args = null;
nextToken();
check(TOK.leftParentheses);
if (token.value != TOK.identifier)
{
error("`__traits(identifier, args...)` expected");
goto Lerr;
}
ident = token.ident;
nextToken();
if (token.value == TOK.comma)
args = parseTemplateArgumentList(); // __traits(identifier, args...)
else
check(TOK.rightParentheses); // __traits(identifier)
e = new AST.TraitsExp(loc, ident, args);
break;
}
case TOK.is_:
{
AST.Type targ;
Identifier ident = null;
AST.Type tspec = null;
TOK tok = TOK.reserved;
TOK tok2 = TOK.reserved;
AST.TemplateParameters* tpl = null;
nextToken();
if (token.value == TOK.leftParentheses)
{
nextToken();
if (token.value == TOK.identifier && peekNext() == TOK.leftParentheses)
{
error(loc, "unexpected `(` after `%s`, inside `is` expression. Try enclosing the contents of `is` with a `typeof` expression", token.toChars());
nextToken();
Token* tempTok = peekPastParen(&token);
memcpy(&token, tempTok, Token.sizeof);
goto Lerr;
}
targ = parseType(&ident);
if (token.value == TOK.colon || token.value == TOK.equal)
{
tok = token.value;
nextToken();
if (tok == TOK.equal && (token.value == TOK.struct_ || token.value == TOK.union_
|| token.value == TOK.class_ || token.value == TOK.super_ || token.value == TOK.enum_
|| token.value == TOK.interface_ || token.value == TOK.package_ || token.value == TOK.module_
|| token.value == TOK.argumentTypes || token.value == TOK.parameters
|| token.value == TOK.const_ && peekNext() == TOK.rightParentheses
|| token.value == TOK.immutable_ && peekNext() == TOK.rightParentheses
|| token.value == TOK.shared_ && peekNext() == TOK.rightParentheses
|| token.value == TOK.inout_ && peekNext() == TOK.rightParentheses || token.value == TOK.function_
|| token.value == TOK.delegate_ || token.value == TOK.return_
|| (token.value == TOK.vector && peekNext() == TOK.rightParentheses)))
{
tok2 = token.value;
nextToken();
}
else
{
tspec = parseType();
}
}
if (tspec)
{
if (token.value == TOK.comma)
tpl = parseTemplateParameterList(1);
else
{
tpl = new AST.TemplateParameters();
check(TOK.rightParentheses);
}
}
else
check(TOK.rightParentheses);
}
else
{
error("`type identifier : specialization` expected following `is`");
goto Lerr;
}
e = new AST.IsExp(loc, targ, ident, tok, tspec, tok2, tpl);
break;
}
case TOK.assert_:
{
// https://dlang.org/spec/expression.html#assert_expressions
AST.Expression msg = null;
nextToken();
check(TOK.leftParentheses, "`assert`");
e = parseAssignExp();
if (token.value == TOK.comma)
{
nextToken();
if (token.value != TOK.rightParentheses)
{
msg = parseAssignExp();
if (token.value == TOK.comma)
nextToken();
}
}
check(TOK.rightParentheses);
e = new AST.AssertExp(loc, e, msg);
break;
}
case TOK.mixin_:
{
// https://dlang.org/spec/expression.html#mixin_expressions
nextToken();
if (token.value != TOK.leftParentheses)
error("found `%s` when expecting `%s` following %s", token.toChars(), Token.toChars(TOK.leftParentheses), "`mixin`".ptr);
auto exps = parseArguments();
e = new AST.CompileExp(loc, exps);
break;
}
case TOK.import_:
{
nextToken();
check(TOK.leftParentheses, "`import`");
e = parseAssignExp();
check(TOK.rightParentheses);
e = new AST.ImportExp(loc, e);
break;
}
case TOK.new_:
e = parseNewExp(null);
break;
case TOK.ref_:
{
if (peekNext() == TOK.leftParentheses)
{
Token* tk = peekPastParen(peek(&token));
if (skipAttributes(tk, &tk) && (tk.value == TOK.goesTo || tk.value == TOK.leftCurly))
{
// ref (arguments) => expression
// ref (arguments) { statements... }
goto case_delegate;
}
}
nextToken();
error("found `%s` when expecting function literal following `ref`", token.toChars());
goto Lerr;
}
case TOK.leftParentheses:
{
Token* tk = peekPastParen(&token);
if (skipAttributes(tk, &tk) && (tk.value == TOK.goesTo || tk.value == TOK.leftCurly))
{
// (arguments) => expression
// (arguments) { statements... }
goto case_delegate;
}
// ( expression )
nextToken();
e = parseExpression();
e.parens = 1;
check(loc, TOK.rightParentheses);
break;
}
case TOK.leftBracket:
{
/* Parse array literals and associative array literals:
* [ value, value, value ... ]
* [ key:value, key:value, key:value ... ]
*/
auto values = new AST.Expressions();
AST.Expressions* keys = null;
nextToken();
while (token.value != TOK.rightBracket && token.value != TOK.endOfFile)
{
e = parseAssignExp();
if (token.value == TOK.colon && (keys || values.dim == 0))
{
nextToken();
if (!keys)
keys = new AST.Expressions();
keys.push(e);
e = parseAssignExp();
}
else if (keys)
{
error("`key:value` expected for associative array literal");
keys = null;
}
values.push(e);
if (token.value == TOK.rightBracket)
break;
check(TOK.comma);
}
check(loc, TOK.rightBracket);
if (keys)
e = new AST.AssocArrayLiteralExp(loc, keys, values);
else
e = new AST.ArrayLiteralExp(loc, null, values);
break;
}
case TOK.leftCurly:
case TOK.function_:
case TOK.delegate_:
case_delegate:
{
AST.Dsymbol s = parseFunctionLiteral();
e = new AST.FuncExp(loc, s);
break;
}
default:
error("expression expected, not `%s`", token.toChars());
Lerr:
// Anything for e, as long as it's not NULL
e = new AST.IntegerExp(loc, 0, AST.Type.tint32);
nextToken();
break;
}
return e;
}
private AST.Expression parseUnaryExp()
{
AST.Expression e;
const loc = token.loc;
switch (token.value)
{
case TOK.and:
nextToken();
e = parseUnaryExp();
e = new AST.AddrExp(loc, e);
break;
case TOK.plusPlus:
nextToken();
e = parseUnaryExp();
//e = new AddAssignExp(loc, e, new IntegerExp(loc, 1, Type::tint32));
e = new AST.PreExp(TOK.prePlusPlus, loc, e);
break;
case TOK.minusMinus:
nextToken();
e = parseUnaryExp();
//e = new MinAssignExp(loc, e, new IntegerExp(loc, 1, Type::tint32));
e = new AST.PreExp(TOK.preMinusMinus, loc, e);
break;
case TOK.mul:
nextToken();
e = parseUnaryExp();
e = new AST.PtrExp(loc, e);
break;
case TOK.min:
nextToken();
e = parseUnaryExp();
e = new AST.NegExp(loc, e);
break;
case TOK.add:
nextToken();
e = parseUnaryExp();
e = new AST.UAddExp(loc, e);
break;
case TOK.not:
nextToken();
e = parseUnaryExp();
e = new AST.NotExp(loc, e);
break;
case TOK.tilde:
nextToken();
e = parseUnaryExp();
e = new AST.ComExp(loc, e);
break;
case TOK.delete_:
nextToken();
e = parseUnaryExp();
e = new AST.DeleteExp(loc, e, false);
break;
case TOK.cast_: // cast(type) expression
{
nextToken();
check(TOK.leftParentheses);
/* Look for cast(), cast(const), cast(immutable),
* cast(shared), cast(shared const), cast(wild), cast(shared wild)
*/
ubyte m = 0;
while (1)
{
switch (token.value)
{
case TOK.const_:
if (peekNext() == TOK.leftParentheses)
break; // const as type constructor
m |= AST.MODFlags.const_; // const as storage class
nextToken();
continue;
case TOK.immutable_:
if (peekNext() == TOK.leftParentheses)
break;
m |= AST.MODFlags.immutable_;
nextToken();
continue;
case TOK.shared_:
if (peekNext() == TOK.leftParentheses)
break;
m |= AST.MODFlags.shared_;
nextToken();
continue;
case TOK.inout_:
if (peekNext() == TOK.leftParentheses)
break;
m |= AST.MODFlags.wild;
nextToken();
continue;
default:
break;
}
break;
}
if (token.value == TOK.rightParentheses)
{
nextToken();
e = parseUnaryExp();
e = new AST.CastExp(loc, e, m);
}
else
{
AST.Type t = parseType(); // cast( type )
t = t.addMod(m); // cast( const type )
check(TOK.rightParentheses);
e = parseUnaryExp();
e = new AST.CastExp(loc, e, t);
}
break;
}
case TOK.inout_:
case TOK.shared_:
case TOK.const_:
case TOK.immutable_: // immutable(type)(arguments) / immutable(type).init
{
StorageClass stc = parseTypeCtor();
AST.Type t = parseBasicType();
t = t.addSTC(stc);
if (stc == 0 && token.value == TOK.dot)
{
nextToken();
if (token.value != TOK.identifier)
{
error("identifier expected following `(type)`.");
return null;
}
e = new AST.DotIdExp(loc, new AST.TypeExp(loc, t), token.ident);
nextToken();
e = parsePostExp(e);
}
else
{
e = new AST.TypeExp(loc, t);
if (token.value != TOK.leftParentheses)
{
error("`(arguments)` expected following `%s`", t.toChars());
return e;
}
e = new AST.CallExp(loc, e, parseArguments());
}
break;
}
case TOK.leftParentheses:
{
auto tk = peek(&token);
static if (CCASTSYNTAX)
{
// If cast
if (isDeclaration(tk, NeedDeclaratorId.no, TOK.rightParentheses, &tk))
{
tk = peek(tk); // skip over right parenthesis
switch (tk.value)
{
case TOK.not:
tk = peek(tk);
if (tk.value == TOK.is_ || tk.value == TOK.in_) // !is or !in
break;
goto case;
case TOK.dot:
case TOK.plusPlus:
case TOK.minusMinus:
case TOK.delete_:
case TOK.new_:
case TOK.leftParentheses:
case TOK.identifier:
case TOK.this_:
case TOK.super_:
case TOK.int32Literal:
case TOK.uns32Literal:
case TOK.int64Literal:
case TOK.uns64Literal:
case TOK.int128Literal:
case TOK.uns128Literal:
case TOK.float32Literal:
case TOK.float64Literal:
case TOK.float80Literal:
case TOK.imaginary32Literal:
case TOK.imaginary64Literal:
case TOK.imaginary80Literal:
case TOK.null_:
case TOK.true_:
case TOK.false_:
case TOK.charLiteral:
case TOK.wcharLiteral:
case TOK.dcharLiteral:
case TOK.string_:
version (none)
{
case TOK.tilde:
case TOK.and:
case TOK.mul:
case TOK.min:
case TOK.add:
}
case TOK.function_:
case TOK.delegate_:
case TOK.typeof_:
case TOK.traits:
case TOK.vector:
case TOK.file:
case TOK.fileFullPath:
case TOK.line:
case TOK.moduleString:
case TOK.functionString:
case TOK.prettyFunction:
case TOK.wchar_:
case TOK.dchar_:
case TOK.bool_:
case TOK.char_:
case TOK.int8:
case TOK.uns8:
case TOK.int16:
case TOK.uns16:
case TOK.int32:
case TOK.uns32:
case TOK.int64:
case TOK.uns64:
case TOK.int128:
case TOK.uns128:
case TOK.float32:
case TOK.float64:
case TOK.float80:
case TOK.imaginary32:
case TOK.imaginary64:
case TOK.imaginary80:
case TOK.complex32:
case TOK.complex64:
case TOK.complex80:
case TOK.void_:
{
// (type) una_exp
nextToken();
auto t = parseType();
check(TOK.rightParentheses);
// if .identifier
// or .identifier!( ... )
if (token.value == TOK.dot)
{
if (peekNext() != TOK.identifier && peekNext() != TOK.new_)
{
error("identifier or new keyword expected following `(...)`.");
return null;
}
e = new AST.TypeExp(loc, t);
e.parens = true;
e = parsePostExp(e);
}
else
{
e = parseUnaryExp();
e = new AST.CastExp(loc, e, t);
error("C style cast illegal, use `%s`", e.toChars());
}
return e;
}
default:
break;
}
}
}
e = parsePrimaryExp();
e = parsePostExp(e);
break;
}
default:
e = parsePrimaryExp();
e = parsePostExp(e);
break;
}
assert(e);
// ^^ is right associative and has higher precedence than the unary operators
while (token.value == TOK.pow)
{
nextToken();
AST.Expression e2 = parseUnaryExp();
e = new AST.PowExp(loc, e, e2);
}
return e;
}
private AST.Expression parsePostExp(AST.Expression e)
{
while (1)
{
const loc = token.loc;
switch (token.value)
{
case TOK.dot:
nextToken();
if (token.value == TOK.identifier)
{
Identifier id = token.ident;
nextToken();
if (token.value == TOK.not && peekNext() != TOK.is_ && peekNext() != TOK.in_)
{
AST.Objects* tiargs = parseTemplateArguments();
e = new AST.DotTemplateInstanceExp(loc, e, id, tiargs);
}
else
e = new AST.DotIdExp(loc, e, id);
continue;
}
if (token.value == TOK.new_)
{
e = parseNewExp(e);
continue;
}
error("identifier or `new` expected following `.`, not `%s`", token.toChars());
break;
case TOK.plusPlus:
e = new AST.PostExp(TOK.plusPlus, loc, e);
break;
case TOK.minusMinus:
e = new AST.PostExp(TOK.minusMinus, loc, e);
break;
case TOK.leftParentheses:
e = new AST.CallExp(loc, e, parseArguments());
continue;
case TOK.leftBracket:
{
// array dereferences:
// array[index]
// array[]
// array[lwr .. upr]
AST.Expression index;
AST.Expression upr;
auto arguments = new AST.Expressions();
inBrackets++;
nextToken();
while (token.value != TOK.rightBracket && token.value != TOK.endOfFile)
{
index = parseAssignExp();
if (token.value == TOK.slice)
{
// array[..., lwr..upr, ...]
nextToken();
upr = parseAssignExp();
arguments.push(new AST.IntervalExp(loc, index, upr));
}
else
arguments.push(index);
if (token.value == TOK.rightBracket)
break;
check(TOK.comma);
}
check(TOK.rightBracket);
inBrackets--;
e = new AST.ArrayExp(loc, e, arguments);
continue;
}
default:
return e;
}
nextToken();
}
}
private AST.Expression parseMulExp()
{
const loc = token.loc;
auto e = parseUnaryExp();
while (1)
{
switch (token.value)
{
case TOK.mul:
nextToken();
auto e2 = parseUnaryExp();
e = new AST.MulExp(loc, e, e2);
continue;
case TOK.div:
nextToken();
auto e2 = parseUnaryExp();
e = new AST.DivExp(loc, e, e2);
continue;
case TOK.mod:
nextToken();
auto e2 = parseUnaryExp();
e = new AST.ModExp(loc, e, e2);
continue;
default:
break;
}
break;
}
return e;
}
private AST.Expression parseAddExp()
{
const loc = token.loc;
auto e = parseMulExp();
while (1)
{
switch (token.value)
{
case TOK.add:
nextToken();
auto e2 = parseMulExp();
e = new AST.AddExp(loc, e, e2);
continue;
case TOK.min:
nextToken();
auto e2 = parseMulExp();
e = new AST.MinExp(loc, e, e2);
continue;
case TOK.tilde:
nextToken();
auto e2 = parseMulExp();
e = new AST.CatExp(loc, e, e2);
continue;
default:
break;
}
break;
}
return e;
}
private AST.Expression parseShiftExp()
{
const loc = token.loc;
auto e = parseAddExp();
while (1)
{
switch (token.value)
{
case TOK.leftShift:
nextToken();
auto e2 = parseAddExp();
e = new AST.ShlExp(loc, e, e2);
continue;
case TOK.rightShift:
nextToken();
auto e2 = parseAddExp();
e = new AST.ShrExp(loc, e, e2);
continue;
case TOK.unsignedRightShift:
nextToken();
auto e2 = parseAddExp();
e = new AST.UshrExp(loc, e, e2);
continue;
default:
break;
}
break;
}
return e;
}
private AST.Expression parseCmpExp()
{
const loc = token.loc;
auto e = parseShiftExp();
TOK op = token.value;
switch (op)
{
case TOK.equal:
case TOK.notEqual:
nextToken();
auto e2 = parseShiftExp();
e = new AST.EqualExp(op, loc, e, e2);
break;
case TOK.is_:
op = TOK.identity;
goto L1;
case TOK.not:
{
// Attempt to identify '!is'
const tv = peekNext();
if (tv == TOK.in_)
{
nextToken();
nextToken();
auto e2 = parseShiftExp();
e = new AST.InExp(loc, e, e2);
e = new AST.NotExp(loc, e);
break;
}
if (tv != TOK.is_)
break;
nextToken();
op = TOK.notIdentity;
goto L1;
}
L1:
nextToken();
auto e2 = parseShiftExp();
e = new AST.IdentityExp(op, loc, e, e2);
break;
case TOK.lessThan:
case TOK.lessOrEqual:
case TOK.greaterThan:
case TOK.greaterOrEqual:
nextToken();
auto e2 = parseShiftExp();
e = new AST.CmpExp(op, loc, e, e2);
break;
case TOK.in_:
nextToken();
auto e2 = parseShiftExp();
e = new AST.InExp(loc, e, e2);
break;
default:
break;
}
return e;
}
private AST.Expression parseAndExp()
{
Loc loc = token.loc;
auto e = parseCmpExp();
while (token.value == TOK.and)
{
checkParens(TOK.and, e);
nextToken();
auto e2 = parseCmpExp();
checkParens(TOK.and, e2);
e = new AST.AndExp(loc, e, e2);
loc = token.loc;
}
return e;
}
private AST.Expression parseXorExp()
{
const loc = token.loc;
auto e = parseAndExp();
while (token.value == TOK.xor)
{
checkParens(TOK.xor, e);
nextToken();
auto e2 = parseAndExp();
checkParens(TOK.xor, e2);
e = new AST.XorExp(loc, e, e2);
}
return e;
}
private AST.Expression parseOrExp()
{
const loc = token.loc;
auto e = parseXorExp();
while (token.value == TOK.or)
{
checkParens(TOK.or, e);
nextToken();
auto e2 = parseXorExp();
checkParens(TOK.or, e2);
e = new AST.OrExp(loc, e, e2);
}
return e;
}
private AST.Expression parseAndAndExp()
{
const loc = token.loc;
auto e = parseOrExp();
while (token.value == TOK.andAnd)
{
nextToken();
auto e2 = parseOrExp();
e = new AST.LogicalExp(loc, TOK.andAnd, e, e2);
}
return e;
}
private AST.Expression parseOrOrExp()
{
const loc = token.loc;
auto e = parseAndAndExp();
while (token.value == TOK.orOr)
{
nextToken();
auto e2 = parseAndAndExp();
e = new AST.LogicalExp(loc, TOK.orOr, e, e2);
}
return e;
}
private AST.Expression parseCondExp()
{
const loc = token.loc;
auto e = parseOrOrExp();
if (token.value == TOK.question)
{
nextToken();
auto e1 = parseExpression();
check(TOK.colon);
auto e2 = parseCondExp();
e = new AST.CondExp(loc, e, e1, e2);
}
return e;
}
AST.Expression parseAssignExp()
{
AST.Expression e;
e = parseCondExp();
if (e is null)
return e;
// require parens for e.g. `t ? a = 1 : b = 2`
// Deprecated in 2018-05.
// @@@DEPRECATED_2.091@@@.
if (e.op == TOK.question && !e.parens && precedence[token.value] == PREC.assign)
dmd.errors.deprecation(e.loc, "`%s` must be surrounded by parentheses when next to operator `%s`",
e.toChars(), Token.toChars(token.value));
const loc = token.loc;
switch (token.value)
{
case TOK.assign:
nextToken();
auto e2 = parseAssignExp();
e = new AST.AssignExp(loc, e, e2);
break;
case TOK.addAssign:
nextToken();
auto e2 = parseAssignExp();
e = new AST.AddAssignExp(loc, e, e2);
break;
case TOK.minAssign:
nextToken();
auto e2 = parseAssignExp();
e = new AST.MinAssignExp(loc, e, e2);
break;
case TOK.mulAssign:
nextToken();
auto e2 = parseAssignExp();
e = new AST.MulAssignExp(loc, e, e2);
break;
case TOK.divAssign:
nextToken();
auto e2 = parseAssignExp();
e = new AST.DivAssignExp(loc, e, e2);
break;
case TOK.modAssign:
nextToken();
auto e2 = parseAssignExp();
e = new AST.ModAssignExp(loc, e, e2);
break;
case TOK.powAssign:
nextToken();
auto e2 = parseAssignExp();
e = new AST.PowAssignExp(loc, e, e2);
break;
case TOK.andAssign:
nextToken();
auto e2 = parseAssignExp();
e = new AST.AndAssignExp(loc, e, e2);
break;
case TOK.orAssign:
nextToken();
auto e2 = parseAssignExp();
e = new AST.OrAssignExp(loc, e, e2);
break;
case TOK.xorAssign:
nextToken();
auto e2 = parseAssignExp();
e = new AST.XorAssignExp(loc, e, e2);
break;
case TOK.leftShiftAssign:
nextToken();
auto e2 = parseAssignExp();
e = new AST.ShlAssignExp(loc, e, e2);
break;
case TOK.rightShiftAssign:
nextToken();
auto e2 = parseAssignExp();
e = new AST.ShrAssignExp(loc, e, e2);
break;
case TOK.unsignedRightShiftAssign:
nextToken();
auto e2 = parseAssignExp();
e = new AST.UshrAssignExp(loc, e, e2);
break;
case TOK.concatenateAssign:
nextToken();
auto e2 = parseAssignExp();
e = new AST.CatAssignExp(loc, e, e2);
break;
default:
break;
}
return e;
}
/*************************
* Collect argument list.
* Assume current token is ',', '$(LPAREN)' or '['.
*/
private AST.Expressions* parseArguments()
{
// function call
AST.Expressions* arguments;
arguments = new AST.Expressions();
const endtok = token.value == TOK.leftBracket ? TOK.rightBracket : TOK.rightParentheses;
nextToken();
while (token.value != endtok && token.value != TOK.endOfFile)
{
auto arg = parseAssignExp();
arguments.push(arg);
if (token.value != TOK.comma)
break;
nextToken(); //comma
}
check(endtok);
return arguments;
}
/*******************************************
*/
private AST.Expression parseNewExp(AST.Expression thisexp)
{
const loc = token.loc;
nextToken();
AST.Expressions* newargs = null;
AST.Expressions* arguments = null;
if (token.value == TOK.leftParentheses)
{
newargs = parseArguments();
}
// An anonymous nested class starts with "class"
if (token.value == TOK.class_)
{
nextToken();
if (token.value == TOK.leftParentheses)
arguments = parseArguments();
AST.BaseClasses* baseclasses = null;
if (token.value != TOK.leftCurly)
baseclasses = parseBaseClasses();
Identifier id = null;
AST.Dsymbols* members = null;
if (token.value != TOK.leftCurly)
{
error("`{ members }` expected for anonymous class");
}
else
{
nextToken();
members = parseDeclDefs(0);
if (token.value != TOK.rightCurly)
error("class member expected");
nextToken();
}
auto cd = new AST.ClassDeclaration(loc, id, baseclasses, members, false);
auto e = new AST.NewAnonClassExp(loc, thisexp, newargs, cd, arguments);
return e;
}
const stc = parseTypeCtor();
auto t = parseBasicType(true);
t = parseBasicType2(t);
t = t.addSTC(stc);
if (t.ty == AST.Taarray)
{
AST.TypeAArray taa = cast(AST.TypeAArray)t;
AST.Type index = taa.index;
auto edim = AST.typeToExpression(index);
if (!edim)
{
error("cannot create a `%s` with `new`", t.toChars);
return new AST.NullExp(loc);
}
t = new AST.TypeSArray(taa.next, edim);
}
else if (token.value == TOK.leftParentheses && t.ty != AST.Tsarray)
{
arguments = parseArguments();
}
auto e = new AST.NewExp(loc, thisexp, newargs, t, arguments);
return e;
}
/**********************************************
*/
private void addComment(AST.Dsymbol s, const(char)* blockComment)
{
if (s !is null)
this.addComment(s, blockComment.toDString());
}
private void addComment(AST.Dsymbol s, const(char)[] blockComment)
{
if (s !is null)
{
s.addComment(combineComments(blockComment, token.lineComment, true));
token.lineComment = null;
}
}
/**********************************************
* Recognize builtin @ attributes
* Params:
* ident = identifier
* Returns:
* storage class for attribute, 0 if not
*/
static StorageClass isBuiltinAtAttribute(Identifier ident)
{
return (ident == Id.property) ? AST.STC.property :
(ident == Id.nogc) ? AST.STC.nogc :
(ident == Id.safe) ? AST.STC.safe :
(ident == Id.trusted) ? AST.STC.trusted :
(ident == Id.system) ? AST.STC.system :
(ident == Id.live) ? AST.STC.live :
(ident == Id.future) ? AST.STC.future :
(ident == Id.disable) ? AST.STC.disable :
0;
}
enum StorageClass atAttrGroup =
AST.STC.property |
AST.STC.nogc |
AST.STC.safe |
AST.STC.trusted |
AST.STC.system |
AST.STC.live |
/*AST.STC.future |*/ // probably should be included
AST.STC.disable;
}
enum PREC : int
{
zero,
expr,
assign,
cond,
oror,
andand,
or,
xor,
and,
equal,
rel,
shift,
add,
mul,
pow,
unary,
primary,
}
|
D
|
/Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/Kitura.build/Stack.swift.o : /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/Kitura.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterHTTPVerbs_generated.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterMethod.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/HTTPStatusCode.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/contentType/MediaType.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/contentType/ContentType.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/CodableRouter+TypeSafeMiddleware.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/TypeSafeMiddleware.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterMiddleware.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterResponse.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/SSLConfig.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/Stack.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/BodyParserProtocol.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/HTTPVersion.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/RangeHeader.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterMiddlewareWalker.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterParameterWalker.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterElementWalker.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/ResourcePathHandler.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterHandler.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/BodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/JSONBodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/URLEncodedBodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/MultiPartBodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/TextBodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/RawBodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/LinkParameter.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/CacheRelatedHeadersSetter.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/ResponseHeadersSetter.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/CompositeHeadersSetter.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/Router.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/CodableRouter.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/FileResourceServer.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/FileServer.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/StaticFileServer.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterHTTPVerbs+Error.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/Error.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/JSONPError.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/TemplatingError.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/InternalError.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterMiddlewareGenerator.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/SwaggerGenerator.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/MimeTypeAcceptor.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/contentType/types.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/String+Extensions.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/DecodingError+Extensions.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/Headers.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterElement.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/Part.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterRequest.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouteRegex.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/ParsedBody.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/LoggerAPI.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/SSLService.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/KituraTemplateEngine.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 /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/TypeDecoder.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/KituraContracts.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/KituraNet.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/Socket.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/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura-net.git-4378304010554470451/Sources/CHTTPParser/include/CHTTPParser.h /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura-net.git-4378304010554470451/Sources/CHTTPParser/include/http_parser.h /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura-net.git-4378304010554470451/Sources/CHTTPParser/include/utils.h /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/agentcore.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/hcapiplugin.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/memplugin.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/mqttplugin.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/cpuplugin.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/envplugin.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/paho.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/CHTTPParser.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura-net.git-4378304010554470451/Sources/CCurl/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/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.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/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/Kitura.build/Stack~partial.swiftmodule : /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/Kitura.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterHTTPVerbs_generated.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterMethod.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/HTTPStatusCode.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/contentType/MediaType.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/contentType/ContentType.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/CodableRouter+TypeSafeMiddleware.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/TypeSafeMiddleware.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterMiddleware.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterResponse.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/SSLConfig.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/Stack.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/BodyParserProtocol.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/HTTPVersion.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/RangeHeader.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterMiddlewareWalker.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterParameterWalker.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterElementWalker.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/ResourcePathHandler.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterHandler.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/BodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/JSONBodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/URLEncodedBodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/MultiPartBodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/TextBodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/RawBodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/LinkParameter.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/CacheRelatedHeadersSetter.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/ResponseHeadersSetter.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/CompositeHeadersSetter.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/Router.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/CodableRouter.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/FileResourceServer.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/FileServer.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/StaticFileServer.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterHTTPVerbs+Error.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/Error.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/JSONPError.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/TemplatingError.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/InternalError.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterMiddlewareGenerator.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/SwaggerGenerator.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/MimeTypeAcceptor.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/contentType/types.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/String+Extensions.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/DecodingError+Extensions.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/Headers.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterElement.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/Part.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterRequest.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouteRegex.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/ParsedBody.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/LoggerAPI.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/SSLService.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/KituraTemplateEngine.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 /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/TypeDecoder.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/KituraContracts.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/KituraNet.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/Socket.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/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura-net.git-4378304010554470451/Sources/CHTTPParser/include/CHTTPParser.h /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura-net.git-4378304010554470451/Sources/CHTTPParser/include/http_parser.h /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura-net.git-4378304010554470451/Sources/CHTTPParser/include/utils.h /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/agentcore.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/hcapiplugin.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/memplugin.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/mqttplugin.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/cpuplugin.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/envplugin.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/paho.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/CHTTPParser.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura-net.git-4378304010554470451/Sources/CCurl/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/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.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/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/Kitura.build/Stack~partial.swiftdoc : /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/Kitura.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterHTTPVerbs_generated.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterMethod.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/HTTPStatusCode.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/contentType/MediaType.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/contentType/ContentType.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/CodableRouter+TypeSafeMiddleware.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/TypeSafeMiddleware.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterMiddleware.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterResponse.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/SSLConfig.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/Stack.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/BodyParserProtocol.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/HTTPVersion.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/RangeHeader.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterMiddlewareWalker.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterParameterWalker.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterElementWalker.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/ResourcePathHandler.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterHandler.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/BodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/JSONBodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/URLEncodedBodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/MultiPartBodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/TextBodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/RawBodyParser.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/LinkParameter.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/CacheRelatedHeadersSetter.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/ResponseHeadersSetter.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/CompositeHeadersSetter.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/Router.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/CodableRouter.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/FileResourceServer.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/FileServer.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/staticFileServer/StaticFileServer.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterHTTPVerbs+Error.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/Error.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/JSONPError.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/TemplatingError.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/InternalError.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterMiddlewareGenerator.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/SwaggerGenerator.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/MimeTypeAcceptor.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/contentType/types.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/String+Extensions.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/DecodingError+Extensions.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/Headers.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterElement.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/Part.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouterRequest.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/RouteRegex.swift /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura.git--2811809642908056391/Sources/Kitura/bodyParser/ParsedBody.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/LoggerAPI.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/SSLService.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/KituraTemplateEngine.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 /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/TypeDecoder.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/KituraContracts.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/KituraNet.swiftmodule /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/Socket.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/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura-net.git-4378304010554470451/Sources/CHTTPParser/include/CHTTPParser.h /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura-net.git-4378304010554470451/Sources/CHTTPParser/include/http_parser.h /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura-net.git-4378304010554470451/Sources/CHTTPParser/include/utils.h /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/agentcore.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/hcapiplugin.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/memplugin.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/mqttplugin.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/cpuplugin.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/envplugin.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/paho.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/x86_64-apple-macosx/debug/CHTTPParser.build/module.modulemap /Users/patbutler/Developer/Server/Kitura/EmojiJournalServer/.build/checkouts/Kitura-net.git-4378304010554470451/Sources/CCurl/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/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.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
|
/Users/WenYu/Desktop/Contacts1/build/Pods.build/Debug-iphonesimulator/ObjectMapper.build/Objects-normal/x86_64/TransformType.o : /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/CustomDateFormatTransform.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/DateFormatterTransform.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/DateTransform.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/EnumTransform.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/FromJSON.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/ISO8601DateTransform.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/Map.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/Mappable.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/Mapper.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/Operators.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/ToJSON.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/TransformOf.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/TransformType.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/URLTransform.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/WenYu/Desktop/Contacts1/Pods/Target\ Support\ Files/ObjectMapper/ObjectMapper-umbrella.h /Users/WenYu/Desktop/Contacts1/build/Pods.build/Debug-iphonesimulator/ObjectMapper.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/WenYu/Desktop/Contacts1/build/Pods.build/Debug-iphonesimulator/ObjectMapper.build/Objects-normal/x86_64/TransformType~partial.swiftmodule : /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/CustomDateFormatTransform.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/DateFormatterTransform.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/DateTransform.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/EnumTransform.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/FromJSON.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/ISO8601DateTransform.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/Map.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/Mappable.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/Mapper.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/Operators.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/ToJSON.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/TransformOf.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/TransformType.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/URLTransform.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/WenYu/Desktop/Contacts1/Pods/Target\ Support\ Files/ObjectMapper/ObjectMapper-umbrella.h /Users/WenYu/Desktop/Contacts1/build/Pods.build/Debug-iphonesimulator/ObjectMapper.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/WenYu/Desktop/Contacts1/build/Pods.build/Debug-iphonesimulator/ObjectMapper.build/Objects-normal/x86_64/TransformType~partial.swiftdoc : /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/CustomDateFormatTransform.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/DateFormatterTransform.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/DateTransform.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/EnumTransform.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/FromJSON.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/ISO8601DateTransform.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/Map.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/Mappable.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/Mapper.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/Operators.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Core/ToJSON.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/TransformOf.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/TransformType.swift /Users/WenYu/Desktop/Contacts1/Pods/ObjectMapper/ObjectMapper/Transforms/URLTransform.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/WenYu/Desktop/Contacts1/Pods/Target\ Support\ Files/ObjectMapper/ObjectMapper-umbrella.h /Users/WenYu/Desktop/Contacts1/build/Pods.build/Debug-iphonesimulator/ObjectMapper.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
|
D
|
module Levels;
import std.file;
import std.algorithm;
//import std.range;
//import std.string;
enum levelsPath = "Levels/";
enum levelExt = ".MrPFLevel";
void GetLevelNames(out string[] allLevelNames) {
allLevelNames.length = 0;
if (levelsPath.exists) {
foreach (f; dirEntries(levelsPath, SpanMode.shallow)) {
if (f.isFile && f.name.endsWith(levelExt)) {
allLevelNames ~= f.name[levelsPath.length..$-levelExt.length];
}
}
allLevelNames.sort();
}
}
|
D
|
/*
TEST_OUTPUT:
---
fail_compilation/fail122.d(12): Error: undefined identifier `y`
---
*/
// https://issues.dlang.org/show_bug.cgi?id=228
// Crash on inferring function literal return type after prior errors
void main()
{
y = 2;
auto x = function(){};
}
|
D
|
// Written in the D programming language.
/**
This is a submodule of $(MREF std, algorithm).
It contains generic _comparison algorithms.
$(BOOKTABLE Cheat Sheet,
$(TR $(TH Function Name) $(TH Description))
$(T2 among,
Checks if a value is among a set of values, e.g.
$(D if (v.among(1, 2, 3)) // `v` is 1, 2 or 3))
$(T2 castSwitch,
$(D (new A()).castSwitch((A a)=>1,(B b)=>2)) returns $(D 1).)
$(T2 clamp,
$(D clamp(1, 3, 6)) returns $(D 3). $(D clamp(4, 3, 6)) returns $(D 4).)
$(T2 cmp,
$(D cmp("abc", "abcd")) is $(D -1), $(D cmp("abc", "aba")) is $(D 1),
and $(D cmp("abc", "abc")) is $(D 0).)
$(T2 either,
Return first parameter $(D p) that passes an $(D if (p)) test, e.g.
$(D either(0, 42, 43)) returns $(D 42).)
$(T2 equal,
Compares ranges for element-by-element equality, e.g.
$(D equal([1, 2, 3], [1.0, 2.0, 3.0])) returns $(D true).)
$(T2 isPermutation,
$(D isPermutation([1, 2], [2, 1])) returns $(D true).)
$(T2 isSameLength,
$(D isSameLength([1, 2, 3], [4, 5, 6])) returns $(D true).)
$(T2 levenshteinDistance,
$(D levenshteinDistance("kitten", "sitting")) returns $(D 3) by using
the $(LUCKY Levenshtein distance _algorithm).)
$(T2 levenshteinDistanceAndPath,
$(D levenshteinDistanceAndPath("kitten", "sitting")) returns
$(D tuple(3, "snnnsni")) by using the $(LUCKY Levenshtein distance
_algorithm).)
$(T2 max,
$(D max(3, 4, 2)) returns $(D 4).)
$(T2 min,
$(D min(3, 4, 2)) returns $(D 2).)
$(T2 mismatch,
$(D mismatch("oh hi", "ohayo")) returns $(D tuple(" hi", "ayo")).)
$(T2 predSwitch,
$(D 2.predSwitch(1, "one", 2, "two", 3, "three")) returns $(D "two").)
)
Copyright: Andrei Alexandrescu 2008-.
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP erdani.com, Andrei Alexandrescu)
Source: $(PHOBOSSRC std/algorithm/_comparison.d)
Macros:
T2=$(TR $(TDNW $(LREF $1)) $(TD $+))
*/
module std.algorithm.comparison;
// FIXME
import std.functional; // : unaryFun, binaryFun;
import std.range.primitives;
import std.traits;
// FIXME
import std.typecons; // : tuple, Tuple, Flag, Yes;
import std.meta : allSatisfy;
/**
Find $(D value) _among $(D values), returning the 1-based index
of the first matching value in $(D values), or $(D 0) if $(D value)
is not _among $(D values). The predicate $(D pred) is used to
compare values, and uses equality by default.
Params:
pred = The predicate used to compare the values.
value = The value to search for.
values = The values to compare the value to.
Returns:
0 if value was not found among the values, otherwise the index of the
found value plus one is returned.
See_Also:
$(REF_ALTTEXT find, find, std,algorithm,searching) and $(REF_ALTTEXT canFind, canFind, std,algorithm,searching) for finding a value in a
range.
*/
uint among(alias pred = (a, b) => a == b, Value, Values...)
(Value value, Values values)
if (Values.length != 0)
{
foreach (uint i, ref v; values)
{
import std.functional : binaryFun;
if (binaryFun!pred(value, v)) return i + 1;
}
return 0;
}
/// Ditto
template among(values...)
if (isExpressionTuple!values)
{
uint among(Value)(Value value)
if (!is(CommonType!(Value, values) == void))
{
switch (value)
{
foreach (uint i, v; values)
case v:
return i + 1;
default:
return 0;
}
}
}
///
@safe unittest
{
assert(3.among(1, 42, 24, 3, 2));
if (auto pos = "bar".among("foo", "bar", "baz"))
assert(pos == 2);
else
assert(false);
// 42 is larger than 24
assert(42.among!((lhs, rhs) => lhs > rhs)(43, 24, 100) == 2);
}
/**
Alternatively, $(D values) can be passed at compile-time, allowing for a more
efficient search, but one that only supports matching on equality:
*/
@safe unittest
{
assert(3.among!(2, 3, 4));
assert("bar".among!("foo", "bar", "baz") == 2);
}
@safe unittest
{
import std.meta : AliasSeq;
if (auto pos = 3.among(1, 2, 3))
assert(pos == 3);
else
assert(false);
assert(!4.among(1, 2, 3));
auto position = "hello".among("hello", "world");
assert(position);
assert(position == 1);
alias values = AliasSeq!("foo", "bar", "baz");
auto arr = [values];
assert(arr[0 .. "foo".among(values)] == ["foo"]);
assert(arr[0 .. "bar".among(values)] == ["foo", "bar"]);
assert(arr[0 .. "baz".among(values)] == arr);
assert("foobar".among(values) == 0);
if (auto pos = 3.among!(1, 2, 3))
assert(pos == 3);
else
assert(false);
assert(!4.among!(1, 2, 3));
position = "hello".among!("hello", "world");
assert(position);
assert(position == 1);
static assert(!__traits(compiles, "a".among!("a", 42)));
static assert(!__traits(compiles, (Object.init).among!(42, "a")));
}
// Used in castSwitch to find the first choice that overshadows the last choice
// in a tuple.
private template indexOfFirstOvershadowingChoiceOnLast(choices...)
{
alias firstParameterTypes = Parameters!(choices[0]);
alias lastParameterTypes = Parameters!(choices[$ - 1]);
static if (lastParameterTypes.length == 0)
{
// If the last is null-typed choice, check if the first is null-typed.
enum isOvershadowing = firstParameterTypes.length == 0;
}
else static if (firstParameterTypes.length == 1)
{
// If the both first and last are not null-typed, check for overshadowing.
enum isOvershadowing =
is(firstParameterTypes[0] == Object) // Object overshadows all other classes!(this is needed for interfaces)
|| is(lastParameterTypes[0] : firstParameterTypes[0]);
}
else
{
// If the first is null typed and the last is not - the is no overshadowing.
enum isOvershadowing = false;
}
static if (isOvershadowing)
{
enum indexOfFirstOvershadowingChoiceOnLast = 0;
}
else
{
enum indexOfFirstOvershadowingChoiceOnLast =
1 + indexOfFirstOvershadowingChoiceOnLast!(choices[1..$]);
}
}
/**
Executes and returns one of a collection of handlers based on the type of the
switch object.
The first choice that $(D switchObject) can be casted to the type
of argument it accepts will be called with $(D switchObject) casted to that
type, and the value it'll return will be returned by $(D castSwitch).
If a choice's return type is void, the choice must throw an exception, unless
all the choices are void. In that case, castSwitch itself will return void.
Throws: If none of the choice matches, a $(D SwitchError) will be thrown. $(D
SwitchError) will also be thrown if not all the choices are void and a void
choice was executed without throwing anything.
Params:
choices = The $(D choices) needs to be composed of function or delegate
handlers that accept one argument. There can also be a choice that
accepts zero arguments. That choice will be invoked if the $(D
switchObject) is null.
switchObject = the object against which the tests are being made.
Returns:
The value of the selected choice.
Note: $(D castSwitch) can only be used with object types.
*/
auto castSwitch(choices...)(Object switchObject)
{
import core.exception : SwitchError;
// Check to see if all handlers return void.
enum areAllHandlersVoidResult = {
bool result = true;
foreach (index, choice; choices)
{
result &= is(ReturnType!choice == void);
}
return result;
}();
if (switchObject !is null)
{
// Checking for exact matches:
const classInfo = typeid(switchObject);
foreach (index, choice; choices)
{
static assert(isCallable!choice,
"A choice handler must be callable");
alias choiceParameterTypes = Parameters!choice;
static assert(choiceParameterTypes.length <= 1,
"A choice handler can not have more than one argument.");
static if (choiceParameterTypes.length == 1)
{
alias CastClass = choiceParameterTypes[0];
static assert(is(CastClass == class) || is(CastClass == interface),
"A choice handler can have only class or interface typed argument.");
// Check for overshadowing:
immutable indexOfOvershadowingChoice =
indexOfFirstOvershadowingChoiceOnLast!(choices[0..index + 1]);
static assert(indexOfOvershadowingChoice == index,
"choice number %d(type %s) is overshadowed by choice number %d(type %s)".format(
index + 1, CastClass.stringof, indexOfOvershadowingChoice + 1,
Parameters!(choices[indexOfOvershadowingChoice])[0].stringof));
if (classInfo == typeid(CastClass))
{
static if (is(ReturnType!(choice) == void))
{
choice(cast(CastClass) switchObject);
static if (areAllHandlersVoidResult)
{
return;
}
else
{
throw new SwitchError("Handlers that return void should throw");
}
}
else
{
return choice(cast(CastClass) switchObject);
}
}
}
}
// Checking for derived matches:
foreach (choice; choices)
{
alias choiceParameterTypes = Parameters!choice;
static if (choiceParameterTypes.length == 1)
{
if (auto castedObject = cast(choiceParameterTypes[0]) switchObject)
{
static if (is(ReturnType!(choice) == void))
{
choice(castedObject);
static if (areAllHandlersVoidResult)
{
return;
}
else
{
throw new SwitchError("Handlers that return void should throw");
}
}
else
{
return choice(castedObject);
}
}
}
}
}
else // If switchObject is null:
{
// Checking for null matches:
foreach (index, choice; choices)
{
static if (Parameters!(choice).length == 0)
{
immutable indexOfOvershadowingChoice =
indexOfFirstOvershadowingChoiceOnLast!(choices[0..index + 1]);
// Check for overshadowing:
static assert(indexOfOvershadowingChoice == index,
"choice number %d(null reference) is overshadowed by choice number %d(null reference)".format(
index + 1, indexOfOvershadowingChoice + 1));
if (switchObject is null)
{
static if (is(ReturnType!(choice) == void))
{
choice();
static if (areAllHandlersVoidResult)
{
return;
}
else
{
throw new SwitchError("Handlers that return void should throw");
}
}
else
{
return choice();
}
}
}
}
}
// In case nothing matched:
throw new SwitchError("Input not matched by any choice");
}
///
@system unittest
{
import std.algorithm.iteration : map;
import std.format : format;
class A
{
int a;
this(int a) {this.a = a;}
@property int i() { return a; }
}
interface I { }
class B : I { }
Object[] arr = [new A(1), new B(), null];
auto results = arr.map!(castSwitch!(
(A a) => "A with a value of %d".format(a.a),
(I i) => "derived from I",
() => "null reference",
))();
// A is handled directly:
assert(results[0] == "A with a value of 1");
// B has no handler - it is handled by the handler of I:
assert(results[1] == "derived from I");
// null is handled by the null handler:
assert(results[2] == "null reference");
}
/// Using with void handlers:
@system unittest
{
import std.exception : assertThrown;
class A { }
class B { }
// Void handlers are allowed if they throw:
assertThrown!Exception(
new B().castSwitch!(
(A a) => 1,
(B d) { throw new Exception("B is not allowed!"); }
)()
);
// Void handlers are also allowed if all the handlers are void:
new A().castSwitch!(
(A a) { assert(true); },
(B b) { assert(false); },
)();
}
@system unittest
{
import core.exception : SwitchError;
import std.exception : assertThrown;
interface I { }
class A : I { }
class B { }
// Nothing matches:
assertThrown!SwitchError((new A()).castSwitch!(
(B b) => 1,
() => 2,
)());
// Choices with multiple arguments are not allowed:
static assert(!__traits(compiles,
(new A()).castSwitch!(
(A a, B b) => 0,
)()));
// Only callable handlers allowed:
static assert(!__traits(compiles,
(new A()).castSwitch!(
1234,
)()));
// Only object arguments allowed:
static assert(!__traits(compiles,
(new A()).castSwitch!(
(int x) => 0,
)()));
// Object overshadows regular classes:
static assert(!__traits(compiles,
(new A()).castSwitch!(
(Object o) => 0,
(A a) => 1,
)()));
// Object overshadows interfaces:
static assert(!__traits(compiles,
(new A()).castSwitch!(
(Object o) => 0,
(I i) => 1,
)()));
// No multiple null handlers allowed:
static assert(!__traits(compiles,
(new A()).castSwitch!(
() => 0,
() => 1,
)()));
// No non-throwing void handlers allowed(when there are non-void handlers):
assertThrown!SwitchError((new A()).castSwitch!(
(A a) {},
(B b) => 2,
)());
// All-void handlers work for the null case:
null.castSwitch!(
(Object o) { assert(false); },
() { assert(true); },
)();
// Throwing void handlers work for the null case:
assertThrown!Exception(null.castSwitch!(
(Object o) => 1,
() { throw new Exception("null"); },
)());
}
/** Clamps a value into the given bounds.
This functions is equivalent to $(D max(lower, min(upper,val))).
Params:
val = The value to _clamp.
lower = The _lower bound of the _clamp.
upper = The _upper bound of the _clamp.
Returns:
Returns $(D val), if it is between $(D lower) and $(D upper).
Otherwise returns the nearest of the two.
*/
auto clamp(T1, T2, T3)(T1 val, T2 lower, T3 upper)
in
{
import std.functional : greaterThan;
assert(!lower.greaterThan(upper));
}
body
{
return max(lower, min(upper, val));
}
///
@safe unittest
{
assert(clamp(2, 1, 3) == 2);
assert(clamp(0, 1, 3) == 1);
assert(clamp(4, 1, 3) == 3);
assert(clamp(1, 1, 1) == 1);
assert(clamp(5, -1, 2u) == 2);
}
@safe unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int a = 1;
short b = 6;
double c = 2;
static assert(is(typeof(clamp(c,a,b)) == double));
assert(clamp(c, a, b) == c);
assert(clamp(a-c, a, b) == a);
assert(clamp(b+c, a, b) == b);
// mixed sign
a = -5;
uint f = 5;
static assert(is(typeof(clamp(f, a, b)) == int));
assert(clamp(f, a, b) == f);
// similar type deduction for (u)long
static assert(is(typeof(clamp(-1L, -2L, 2UL)) == long));
// user-defined types
import std.datetime : Date;
assert(clamp(Date(1982, 1, 4), Date(1012, 12, 21), Date(2012, 12, 21)) == Date(1982, 1, 4));
assert(clamp(Date(1982, 1, 4), Date.min, Date.max) == Date(1982, 1, 4));
// UFCS style
assert(Date(1982, 1, 4).clamp(Date.min, Date.max) == Date(1982, 1, 4));
}
// cmp
/**********************************
Performs three-way lexicographical comparison on two input ranges
according to predicate $(D pred). Iterating $(D r1) and $(D r2) in
lockstep, $(D cmp) compares each element $(D e1) of $(D r1) with the
corresponding element $(D e2) in $(D r2). If one of the ranges has been
finished, $(D cmp) returns a negative value if $(D r1) has fewer
elements than $(D r2), a positive value if $(D r1) has more elements
than $(D r2), and $(D 0) if the ranges have the same number of
elements.
If the ranges are strings, $(D cmp) performs UTF decoding
appropriately and compares the ranges one code point at a time.
Params:
pred = The predicate used for comparison.
r1 = The first range.
r2 = The second range.
Returns:
0 if both ranges compare equal. -1 if the first differing element of $(D
r1) is less than the corresponding element of $(D r2) according to $(D
pred). 1 if the first differing element of $(D r2) is less than the
corresponding element of $(D r1) according to $(D pred).
*/
int cmp(alias pred = "a < b", R1, R2)(R1 r1, R2 r2)
if (isInputRange!R1 && isInputRange!R2 && !(isSomeString!R1 && isSomeString!R2))
{
for (;; r1.popFront(), r2.popFront())
{
if (r1.empty) return -cast(int)!r2.empty;
if (r2.empty) return !r1.empty;
auto a = r1.front, b = r2.front;
if (binaryFun!pred(a, b)) return -1;
if (binaryFun!pred(b, a)) return 1;
}
}
/// ditto
int cmp(alias pred = "a < b", R1, R2)(R1 r1, R2 r2) if (isSomeString!R1 && isSomeString!R2)
{
import core.stdc.string : memcmp;
import std.utf : decode;
static if (is(typeof(pred) : string))
enum isLessThan = pred == "a < b";
else
enum isLessThan = false;
// For speed only
static int threeWay(size_t a, size_t b)
{
static if (size_t.sizeof == int.sizeof && isLessThan)
return a - b;
else
return binaryFun!pred(b, a) ? 1 : binaryFun!pred(a, b) ? -1 : 0;
}
// For speed only
// @@@BUG@@@ overloading should be allowed for nested functions
static int threeWayInt(int a, int b)
{
static if (isLessThan)
return a - b;
else
return binaryFun!pred(b, a) ? 1 : binaryFun!pred(a, b) ? -1 : 0;
}
static if (typeof(r1[0]).sizeof == typeof(r2[0]).sizeof && isLessThan)
{
static if (typeof(r1[0]).sizeof == 1)
{
immutable len = min(r1.length, r2.length);
immutable result = __ctfe ?
{
foreach (i; 0 .. len)
{
if (r1[i] != r2[i])
return threeWayInt(r1[i], r2[i]);
}
return 0;
}()
: () @trusted { return memcmp(r1.ptr, r2.ptr, len); }();
if (result) return result;
}
else
{
auto p1 = r1.ptr, p2 = r2.ptr,
pEnd = p1 + min(r1.length, r2.length);
for (; p1 != pEnd; ++p1, ++p2)
{
if (*p1 != *p2) return threeWayInt(cast(int) *p1, cast(int) *p2);
}
}
return threeWay(r1.length, r2.length);
}
else
{
for (size_t i1, i2;;)
{
if (i1 == r1.length) return threeWay(i2, r2.length);
if (i2 == r2.length) return threeWay(r1.length, i1);
immutable c1 = decode(r1, i1),
c2 = decode(r2, i2);
if (c1 != c2) return threeWayInt(cast(int) c1, cast(int) c2);
}
}
}
///
@safe unittest
{
int result;
result = cmp("abc", "abc");
assert(result == 0);
result = cmp("", "");
assert(result == 0);
result = cmp("abc", "abcd");
assert(result < 0);
result = cmp("abcd", "abc");
assert(result > 0);
result = cmp("abc"d, "abd");
assert(result < 0);
result = cmp("bbc", "abc"w);
assert(result > 0);
result = cmp("aaa", "aaaa"d);
assert(result < 0);
result = cmp("aaaa", "aaa"d);
assert(result > 0);
result = cmp("aaa", "aaa"d);
assert(result == 0);
result = cmp(cast(int[])[], cast(int[])[]);
assert(result == 0);
result = cmp([1, 2, 3], [1, 2, 3]);
assert(result == 0);
result = cmp([1, 3, 2], [1, 2, 3]);
assert(result > 0);
result = cmp([1, 2, 3], [1L, 2, 3, 4]);
assert(result < 0);
result = cmp([1L, 2, 3], [1, 2]);
assert(result > 0);
}
// equal
/**
Compares two ranges for equality, as defined by predicate $(D pred)
(which is $(D ==) by default).
*/
template equal(alias pred = "a == b")
{
enum isEmptyRange(R) =
isInputRange!R && __traits(compiles, {static assert(R.empty);});
enum hasFixedLength(T) = hasLength!T || isNarrowString!T;
/++
Compares two ranges for equality. The ranges may have
different element types, as long as $(D pred(r1.front, r2.front))
evaluates to $(D bool).
Performs $(BIGOH min(r1.length, r2.length)) evaluations of $(D pred).
Params:
r1 = The first range to be compared.
r2 = The second range to be compared.
Returns:
$(D true) if and only if the two ranges compare _equal element
for element, according to binary predicate $(D pred).
See_Also:
$(HTTP sgi.com/tech/stl/_equal.html, STL's _equal)
+/
bool equal(Range1, Range2)(Range1 r1, Range2 r2)
if (isInputRange!Range1 && isInputRange!Range2 &&
is(typeof(binaryFun!pred(r1.front, r2.front))))
{
static assert(!(isInfinite!Range1 && isInfinite!Range2),
"Both ranges are known to be infinite");
//No pred calls necessary
static if (isEmptyRange!Range1 || isEmptyRange!Range2)
{
return r1.empty && r2.empty;
}
else static if ((isInfinite!Range1 && hasFixedLength!Range2) ||
(hasFixedLength!Range1 && isInfinite!Range2))
{
return false;
}
//Detect default pred and compatible dynamic array
else static if (is(typeof(pred) == string) && pred == "a == b" &&
isArray!Range1 && isArray!Range2 && is(typeof(r1 == r2)))
{
return r1 == r2;
}
// if one of the arguments is a string and the other isn't, then auto-decoding
// can be avoided if they have the same ElementEncodingType
else static if (is(typeof(pred) == string) && pred == "a == b" &&
isAutodecodableString!Range1 != isAutodecodableString!Range2 &&
is(ElementEncodingType!Range1 == ElementEncodingType!Range2))
{
import std.utf : byCodeUnit;
static if (isAutodecodableString!Range1)
{
return equal(r1.byCodeUnit, r2);
}
else
{
return equal(r2.byCodeUnit, r1);
}
}
//Try a fast implementation when the ranges have comparable lengths
else static if (hasLength!Range1 && hasLength!Range2 && is(typeof(r1.length == r2.length)))
{
immutable len1 = r1.length;
immutable len2 = r2.length;
if (len1 != len2) return false; //Short circuit return
//Lengths are the same, so we need to do an actual comparison
//Good news is we can squeeze out a bit of performance by not checking if r2 is empty
for (; !r1.empty; r1.popFront(), r2.popFront())
{
if (!binaryFun!(pred)(r1.front, r2.front)) return false;
}
return true;
}
else
{
//Generic case, we have to walk both ranges making sure neither is empty
for (; !r1.empty; r1.popFront(), r2.popFront())
{
if (r2.empty) return false;
if (!binaryFun!(pred)(r1.front, r2.front)) return false;
}
static if (!isInfinite!Range1)
return r2.empty;
}
}
}
///
@safe unittest
{
import std.math : approxEqual;
import std.algorithm.comparison : equal;
int[] a = [ 1, 2, 4, 3 ];
assert(!equal(a, a[1..$]));
assert(equal(a, a));
assert(equal!((a, b) => a == b)(a, a));
// different types
double[] b = [ 1.0, 2, 4, 3];
assert(!equal(a, b[1..$]));
assert(equal(a, b));
// predicated: ensure that two vectors are approximately equal
double[] c = [ 1.005, 2, 4, 3];
assert(equal!approxEqual(b, c));
}
/++
Tip: $(D equal) can itself be used as a predicate to other functions.
This can be very useful when the element type of a range is itself a
range. In particular, $(D equal) can be its own predicate, allowing
range of range (of range...) comparisons.
+/
@safe unittest
{
import std.range : iota, chunks;
import std.algorithm.comparison : equal;
assert(equal!(equal!equal)(
[[[0, 1], [2, 3]], [[4, 5], [6, 7]]],
iota(0, 8).chunks(2).chunks(2)
));
}
@safe unittest
{
import std.algorithm.iteration : map;
import std.math : approxEqual;
import std.internal.test.dummyrange : ReferenceForwardRange,
ReferenceInputRange, ReferenceInfiniteForwardRange;
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
// various strings
assert(equal("æøå", "æøå")); //UTF8 vs UTF8
assert(!equal("???", "æøå")); //UTF8 vs UTF8
assert(equal("æøå"w, "æøå"d)); //UTF16 vs UTF32
assert(!equal("???"w, "æøå"d));//UTF16 vs UTF32
assert(equal("æøå"d, "æøå"d)); //UTF32 vs UTF32
assert(!equal("???"d, "æøå"d));//UTF32 vs UTF32
assert(!equal("hello", "world"));
// same strings, but "explicit non default" comparison (to test the non optimized array comparison)
assert( equal!("a == b")("æøå", "æøå")); //UTF8 vs UTF8
assert(!equal!("a == b")("???", "æøå")); //UTF8 vs UTF8
assert( equal!("a == b")("æøå"w, "æøå"d)); //UTF16 vs UTF32
assert(!equal!("a == b")("???"w, "æøå"d));//UTF16 vs UTF32
assert( equal!("a == b")("æøå"d, "æøå"d)); //UTF32 vs UTF32
assert(!equal!("a == b")("???"d, "æøå"d));//UTF32 vs UTF32
assert(!equal!("a == b")("hello", "world"));
//Array of string
assert(equal(["hello", "world"], ["hello", "world"]));
assert(!equal(["hello", "world"], ["hello"]));
assert(!equal(["hello", "world"], ["hello", "Bob!"]));
//Should not compile, because "string == dstring" is illegal
static assert(!is(typeof(equal(["hello", "world"], ["hello"d, "world"d]))));
//However, arrays of non-matching string can be compared using equal!equal. Neat-o!
equal!equal(["hello", "world"], ["hello"d, "world"d]);
//Tests, with more fancy map ranges
int[] a = [ 1, 2, 4, 3 ];
assert(equal([2, 4, 8, 6], map!"a*2"(a)));
double[] b = [ 1.0, 2, 4, 3];
double[] c = [ 1.005, 2, 4, 3];
assert(equal!approxEqual(map!"a*2"(b), map!"a*2"(c)));
assert(!equal([2, 4, 1, 3], map!"a*2"(a)));
assert(!equal([2, 4, 1], map!"a*2"(a)));
assert(!equal!approxEqual(map!"a*3"(b), map!"a*2"(c)));
//Tests with some fancy reference ranges.
ReferenceInputRange!int cir = new ReferenceInputRange!int([1, 2, 4, 3]);
ReferenceForwardRange!int cfr = new ReferenceForwardRange!int([1, 2, 4, 3]);
assert(equal(cir, a));
cir = new ReferenceInputRange!int([1, 2, 4, 3]);
assert(equal(cir, cfr.save));
assert(equal(cfr.save, cfr.save));
cir = new ReferenceInputRange!int([1, 2, 8, 1]);
assert(!equal(cir, cfr));
//Test with an infinite range
auto ifr = new ReferenceInfiniteForwardRange!int;
assert(!equal(a, ifr));
assert(!equal(ifr, a));
//Test InputRange without length
assert(!equal(ifr, cir));
assert(!equal(cir, ifr));
}
@safe pure unittest
{
import std.utf : byChar, byWchar, byDchar;
assert(equal("æøå".byChar, "æøå"));
assert(equal("æøå", "æøå".byChar));
assert(equal("æøå".byWchar, "æøå"w));
assert(equal("æøå"w, "æøå".byWchar));
assert(equal("æøå".byDchar, "æøå"d));
assert(equal("æøå"d, "æøå".byDchar));
}
@safe pure unittest
{
struct R(bool _empty) {
enum empty = _empty;
@property char front(){assert(0);}
void popFront(){assert(0);}
}
alias I = R!false;
static assert(!__traits(compiles, I().equal(I())));
// strings have fixed length so don't need to compare elements
assert(!I().equal("foo"));
assert(!"bar".equal(I()));
alias E = R!true;
assert(E().equal(E()));
assert(E().equal(""));
assert("".equal(E()));
assert(!E().equal("foo"));
assert(!"bar".equal(E()));
}
// MaxType
private template MaxType(T...)
if (T.length >= 1)
{
static if (T.length == 1)
{
alias MaxType = T[0];
}
else static if (T.length == 2)
{
static if (!is(typeof(T[0].min)))
alias MaxType = CommonType!T;
else static if (T[1].max > T[0].max)
alias MaxType = T[1];
else
alias MaxType = T[0];
}
else
{
alias MaxType = MaxType!(MaxType!(T[0 .. ($+1)/2]), MaxType!(T[($+1)/2 .. $]));
}
}
// levenshteinDistance
/**
Encodes $(HTTP realityinteractive.com/rgrzywinski/archives/000249.html,
edit operations) necessary to transform one sequence into
another. Given sequences $(D s) (source) and $(D t) (target), a
sequence of $(D EditOp) encodes the steps that need to be taken to
convert $(D s) into $(D t). For example, if $(D s = "cat") and $(D
"cars"), the minimal sequence that transforms $(D s) into $(D t) is:
skip two characters, replace 't' with 'r', and insert an 's'. Working
with edit operations is useful in applications such as spell-checkers
(to find the closest word to a given misspelled word), approximate
searches, diff-style programs that compute the difference between
files, efficient encoding of patches, DNA sequence analysis, and
plagiarism detection.
*/
enum EditOp : char
{
/** Current items are equal; no editing is necessary. */
none = 'n',
/** Substitute current item in target with current item in source. */
substitute = 's',
/** Insert current item from the source into the target. */
insert = 'i',
/** Remove current item from the target. */
remove = 'r'
}
private struct Levenshtein(Range, alias equals, CostType = size_t)
{
EditOp[] path()
{
import std.algorithm.mutation : reverse;
EditOp[] result;
size_t i = rows - 1, j = cols - 1;
// restore the path
while (i || j)
{
auto cIns = j == 0 ? CostType.max : matrix(i,j - 1);
auto cDel = i == 0 ? CostType.max : matrix(i - 1,j);
auto cSub = i == 0 || j == 0
? CostType.max
: matrix(i - 1,j - 1);
switch (min_index(cSub, cIns, cDel))
{
case 0:
result ~= matrix(i - 1,j - 1) == matrix(i,j)
? EditOp.none
: EditOp.substitute;
--i;
--j;
break;
case 1:
result ~= EditOp.insert;
--j;
break;
default:
result ~= EditOp.remove;
--i;
break;
}
}
reverse(result);
return result;
}
~this() {
FreeMatrix();
}
private:
CostType _deletionIncrement = 1,
_insertionIncrement = 1,
_substitutionIncrement = 1;
CostType[] _matrix;
size_t rows, cols;
// Treat _matrix as a rectangular array
ref CostType matrix(size_t row, size_t col) { return _matrix[row * cols + col]; }
void AllocMatrix(size_t r, size_t c) @trusted {
import core.checkedint : mulu;
bool overflow;
const rc = mulu(r, c, overflow);
if (overflow) assert(0);
rows = r;
cols = c;
if (_matrix.length < rc)
{
import core.stdc.stdlib : realloc;
import core.exception : onOutOfMemoryError;
const nbytes = mulu(rc, _matrix[0].sizeof, overflow);
if (overflow) assert(0);
auto m = cast(CostType *)realloc(_matrix.ptr, nbytes);
if (!m)
onOutOfMemoryError();
_matrix = m[0 .. r * c];
InitMatrix();
}
}
void FreeMatrix() @trusted {
import core.stdc.stdlib : free;
free(_matrix.ptr);
_matrix = null;
}
void InitMatrix() {
foreach (r; 0 .. rows)
matrix(r,0) = r * _deletionIncrement;
foreach (c; 0 .. cols)
matrix(0,c) = c * _insertionIncrement;
}
static uint min_index(CostType i0, CostType i1, CostType i2)
{
if (i0 <= i1)
{
return i0 <= i2 ? 0 : 2;
}
else
{
return i1 <= i2 ? 1 : 2;
}
}
CostType distanceWithPath(Range s, Range t)
{
auto slen = walkLength(s.save), tlen = walkLength(t.save);
AllocMatrix(slen + 1, tlen + 1);
foreach (i; 1 .. rows)
{
auto sfront = s.front;
auto tt = t.save;
foreach (j; 1 .. cols)
{
auto cSub = matrix(i - 1,j - 1)
+ (equals(sfront, tt.front) ? 0 : _substitutionIncrement);
tt.popFront();
auto cIns = matrix(i,j - 1) + _insertionIncrement;
auto cDel = matrix(i - 1,j) + _deletionIncrement;
switch (min_index(cSub, cIns, cDel))
{
case 0:
matrix(i,j) = cSub;
break;
case 1:
matrix(i,j) = cIns;
break;
default:
matrix(i,j) = cDel;
break;
}
}
s.popFront();
}
return matrix(slen,tlen);
}
CostType distanceLowMem(Range s, Range t, CostType slen, CostType tlen)
{
CostType lastdiag, olddiag;
AllocMatrix(slen + 1, 1);
foreach (y; 1 .. slen + 1)
{
_matrix[y] = y;
}
foreach (x; 1 .. tlen + 1)
{
auto tfront = t.front;
auto ss = s.save;
_matrix[0] = x;
lastdiag = x - 1;
foreach (y; 1 .. rows)
{
olddiag = _matrix[y];
auto cSub = lastdiag + (equals(ss.front, tfront) ? 0 : _substitutionIncrement);
ss.popFront();
auto cIns = _matrix[y - 1] + _insertionIncrement;
auto cDel = _matrix[y] + _deletionIncrement;
switch (min_index(cSub, cIns, cDel))
{
case 0:
_matrix[y] = cSub;
break;
case 1:
_matrix[y] = cIns;
break;
default:
_matrix[y] = cDel;
break;
}
lastdiag = olddiag;
}
t.popFront();
}
return _matrix[slen];
}
}
/**
Returns the $(HTTP wikipedia.org/wiki/Levenshtein_distance, Levenshtein
distance) between $(D s) and $(D t). The Levenshtein distance computes
the minimal amount of edit operations necessary to transform $(D s)
into $(D t). Performs $(BIGOH s.length * t.length) evaluations of $(D
equals) and occupies $(BIGOH s.length * t.length) storage.
Params:
equals = The binary predicate to compare the elements of the two ranges.
s = The original range.
t = The transformation target
Returns:
The minimal number of edits to transform s into t.
Does not allocate GC memory.
*/
size_t levenshteinDistance(alias equals = (a,b) => a == b, Range1, Range2)
(Range1 s, Range2 t)
if (isForwardRange!(Range1) && isForwardRange!(Range2))
{
alias eq = binaryFun!(equals);
for (;;)
{
if (s.empty) return t.walkLength;
if (t.empty) return s.walkLength;
if (eq(s.front, t.front))
{
s.popFront();
t.popFront();
continue;
}
static if (isBidirectionalRange!(Range1) && isBidirectionalRange!(Range2))
{
if (eq(s.back, t.back))
{
s.popBack();
t.popBack();
continue;
}
}
break;
}
auto slen = walkLength(s.save);
auto tlen = walkLength(t.save);
if (slen == 1 && tlen == 1)
{
return eq(s.front, t.front) ? 0 : 1;
}
if (slen > tlen)
{
Levenshtein!(Range1, eq, size_t) lev;
return lev.distanceLowMem(s, t, slen, tlen);
}
else
{
Levenshtein!(Range2, eq, size_t) lev;
return lev.distanceLowMem(t, s, tlen, slen);
}
}
///
@safe unittest
{
import std.algorithm.iteration : filter;
import std.uni : toUpper;
assert(levenshteinDistance("cat", "rat") == 1);
assert(levenshteinDistance("parks", "spark") == 2);
assert(levenshteinDistance("abcde", "abcde") == 0);
assert(levenshteinDistance("abcde", "abCde") == 1);
assert(levenshteinDistance("kitten", "sitting") == 3);
assert(levenshteinDistance!((a, b) => toUpper(a) == toUpper(b))
("parks", "SPARK") == 2);
assert(levenshteinDistance("parks".filter!"true", "spark".filter!"true") == 2);
assert(levenshteinDistance("ID", "I♥D") == 1);
}
@safe @nogc nothrow unittest
{
assert(levenshteinDistance("cat"d, "rat"d) == 1);
}
/// ditto
size_t levenshteinDistance(alias equals = (a,b) => a == b, Range1, Range2)
(auto ref Range1 s, auto ref Range2 t)
if (isConvertibleToString!Range1 || isConvertibleToString!Range2)
{
import std.meta : staticMap;
alias Types = staticMap!(convertToString, Range1, Range2);
return levenshteinDistance!(equals, Types)(s, t);
}
@safe unittest
{
static struct S { string s; alias s this; }
assert(levenshteinDistance(S("cat"), S("rat")) == 1);
assert(levenshteinDistance("cat", S("rat")) == 1);
assert(levenshteinDistance(S("cat"), "rat") == 1);
}
@safe @nogc nothrow unittest
{
static struct S { dstring s; alias s this; }
assert(levenshteinDistance(S("cat"d), S("rat"d)) == 1);
assert(levenshteinDistance("cat"d, S("rat"d)) == 1);
assert(levenshteinDistance(S("cat"d), "rat"d) == 1);
}
/**
Returns the Levenshtein distance and the edit path between $(D s) and
$(D t).
Params:
equals = The binary predicate to compare the elements of the two ranges.
s = The original range.
t = The transformation target
Returns:
Tuple with the first element being the minimal amount of edits to transform s into t and
the second element being the sequence of edits to effect this transformation.
Allocates GC memory for the returned EditOp[] array.
*/
Tuple!(size_t, EditOp[])
levenshteinDistanceAndPath(alias equals = (a,b) => a == b, Range1, Range2)
(Range1 s, Range2 t)
if (isForwardRange!(Range1) && isForwardRange!(Range2))
{
Levenshtein!(Range1, binaryFun!(equals)) lev;
auto d = lev.distanceWithPath(s, t);
return tuple(d, lev.path());
}
///
@safe unittest
{
string a = "Saturday", b = "Sundays";
auto p = levenshteinDistanceAndPath(a, b);
assert(p[0] == 4);
assert(equal(p[1], "nrrnsnnni"));
}
@safe unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
assert(levenshteinDistance("a", "a") == 0);
assert(levenshteinDistance("a", "b") == 1);
assert(levenshteinDistance("aa", "ab") == 1);
assert(levenshteinDistance("aa", "abc") == 2);
assert(levenshteinDistance("Saturday", "Sunday") == 3);
assert(levenshteinDistance("kitten", "sitting") == 3);
}
/// ditto
Tuple!(size_t, EditOp[])
levenshteinDistanceAndPath(alias equals = (a,b) => a == b, Range1, Range2)
(auto ref Range1 s, auto ref Range2 t)
if (isConvertibleToString!Range1 || isConvertibleToString!Range2)
{
import std.meta : staticMap;
alias Types = staticMap!(convertToString, Range1, Range2);
return levenshteinDistanceAndPath!(equals, Types)(s, t);
}
@safe unittest
{
static struct S { string s; alias s this; }
assert(levenshteinDistanceAndPath(S("cat"), S("rat"))[0] == 1);
assert(levenshteinDistanceAndPath("cat", S("rat"))[0] == 1);
assert(levenshteinDistanceAndPath(S("cat"), "rat")[0] == 1);
}
// max
/**
Iterates the passed arguments and return the maximum value.
Params:
args = The values to select the maximum from. At least two arguments must
be passed.
Returns:
The maximum of the passed-in args. The type of the returned value is
the type among the passed arguments that is able to store the largest value.
See_Also:
$(REF maxElement, std,algorithm,searching)
*/
MaxType!T max(T...)(T args)
if (T.length >= 2)
{
//Get "a"
static if (T.length <= 2)
alias a = args[0];
else
auto a = max(args[0 .. ($+1)/2]);
alias T0 = typeof(a);
//Get "b"
static if (T.length <= 3)
alias b = args[$-1];
else
auto b = max(args[($+1)/2 .. $]);
alias T1 = typeof(b);
import std.algorithm.internal : algoFormat;
static assert (is(typeof(a < b)),
algoFormat("Invalid arguments: Cannot compare types %s and %s.", T0.stringof, T1.stringof));
//Do the "max" proper with a and b
import std.functional : lessThan;
immutable chooseB = lessThan!(T0, T1)(a, b);
return cast(typeof(return)) (chooseB ? b : a);
}
///
@safe unittest
{
int a = 5;
short b = 6;
double c = 2;
auto d = max(a, b);
assert(is(typeof(d) == int));
assert(d == 6);
auto e = min(a, b, c);
assert(is(typeof(e) == double));
assert(e == 2);
}
@safe unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int a = 5;
short b = 6;
double c = 2;
auto d = max(a, b);
static assert(is(typeof(d) == int));
assert(d == 6);
auto e = max(a, b, c);
static assert(is(typeof(e) == double));
assert(e == 6);
// mixed sign
a = -5;
uint f = 5;
static assert(is(typeof(max(a, f)) == uint));
assert(max(a, f) == 5);
//Test user-defined types
import std.datetime : Date;
assert(max(Date(2012, 12, 21), Date(1982, 1, 4)) == Date(2012, 12, 21));
assert(max(Date(1982, 1, 4), Date(2012, 12, 21)) == Date(2012, 12, 21));
assert(max(Date(1982, 1, 4), Date.min) == Date(1982, 1, 4));
assert(max(Date.min, Date(1982, 1, 4)) == Date(1982, 1, 4));
assert(max(Date(1982, 1, 4), Date.max) == Date.max);
assert(max(Date.max, Date(1982, 1, 4)) == Date.max);
assert(max(Date.min, Date.max) == Date.max);
assert(max(Date.max, Date.min) == Date.max);
}
// MinType
private template MinType(T...)
if (T.length >= 1)
{
static if (T.length == 1)
{
alias MinType = T[0];
}
else static if (T.length == 2)
{
static if (!is(typeof(T[0].min)))
alias MinType = CommonType!T;
else
{
enum hasMostNegative = is(typeof(mostNegative!(T[0]))) &&
is(typeof(mostNegative!(T[1])));
static if (hasMostNegative && mostNegative!(T[1]) < mostNegative!(T[0]))
alias MinType = T[1];
else static if (hasMostNegative && mostNegative!(T[1]) > mostNegative!(T[0]))
alias MinType = T[0];
else static if (T[1].max < T[0].max)
alias MinType = T[1];
else
alias MinType = T[0];
}
}
else
{
alias MinType = MinType!(MinType!(T[0 .. ($+1)/2]), MinType!(T[($+1)/2 .. $]));
}
}
// min
/**
Iterates the passed arguments and returns the minimum value.
Params: args = The values to select the minimum from. At least two arguments
must be passed, and they must be comparable with `<`.
Returns: The minimum of the passed-in values.
See_Also:
$(REF minElement, std,algorithm,searching)
*/
MinType!T min(T...)(T args)
if (T.length >= 2)
{
//Get "a"
static if (T.length <= 2)
alias a = args[0];
else
auto a = min(args[0 .. ($+1)/2]);
alias T0 = typeof(a);
//Get "b"
static if (T.length <= 3)
alias b = args[$-1];
else
auto b = min(args[($+1)/2 .. $]);
alias T1 = typeof(b);
import std.algorithm.internal : algoFormat;
static assert (is(typeof(a < b)),
algoFormat("Invalid arguments: Cannot compare types %s and %s.", T0.stringof, T1.stringof));
//Do the "min" proper with a and b
import std.functional : lessThan;
immutable chooseA = lessThan!(T0, T1)(a, b);
return cast(typeof(return)) (chooseA ? a : b);
}
///
@safe unittest
{
int a = 5;
short b = 6;
double c = 2;
auto d = min(a, b);
static assert(is(typeof(d) == int));
assert(d == 5);
auto e = min(a, b, c);
static assert(is(typeof(e) == double));
assert(e == 2);
// With arguments of mixed signedness, the return type is the one that can
// store the lowest values.
a = -10;
uint f = 10;
static assert(is(typeof(min(a, f)) == int));
assert(min(a, f) == -10);
// User-defined types that support comparison with < are supported.
import std.datetime;
assert(min(Date(2012, 12, 21), Date(1982, 1, 4)) == Date(1982, 1, 4));
assert(min(Date(1982, 1, 4), Date(2012, 12, 21)) == Date(1982, 1, 4));
assert(min(Date(1982, 1, 4), Date.min) == Date.min);
assert(min(Date.min, Date(1982, 1, 4)) == Date.min);
assert(min(Date(1982, 1, 4), Date.max) == Date(1982, 1, 4));
assert(min(Date.max, Date(1982, 1, 4)) == Date(1982, 1, 4));
assert(min(Date.min, Date.max) == Date.min);
assert(min(Date.max, Date.min) == Date.min);
}
// mismatch
/**
Sequentially compares elements in $(D r1) and $(D r2) in lockstep, and
stops at the first mismatch (according to $(D pred), by default
equality). Returns a tuple with the reduced ranges that start with the
two mismatched values. Performs $(BIGOH min(r1.length, r2.length))
evaluations of $(D pred).
See_Also:
$(HTTP sgi.com/tech/stl/_mismatch.html, STL's _mismatch)
*/
Tuple!(Range1, Range2)
mismatch(alias pred = "a == b", Range1, Range2)(Range1 r1, Range2 r2)
if (isInputRange!(Range1) && isInputRange!(Range2))
{
for (; !r1.empty && !r2.empty; r1.popFront(), r2.popFront())
{
if (!binaryFun!(pred)(r1.front, r2.front)) break;
}
return tuple(r1, r2);
}
///
@safe unittest
{
int[] x = [ 1, 5, 2, 7, 4, 3 ];
double[] y = [ 1.0, 5, 2, 7.3, 4, 8 ];
auto m = mismatch(x, y);
assert(m[0] == x[3 .. $]);
assert(m[1] == y[3 .. $]);
}
@safe unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 3 ];
int[] b = [ 1, 2, 4, 5 ];
auto mm = mismatch(a, b);
assert(mm[0] == [3]);
assert(mm[1] == [4, 5]);
}
/**
Returns one of a collection of expressions based on the value of the switch
expression.
$(D choices) needs to be composed of pairs of test expressions and return
expressions. Each test-expression is compared with $(D switchExpression) using
$(D pred)($(D switchExpression) is the first argument) and if that yields true
- the return expression is returned.
Both the test and the return expressions are lazily evaluated.
Params:
switchExpression = The first argument for the predicate.
choices = Pairs of test expressions and return expressions. The test
expressions will be the second argument for the predicate, and the return
expression will be returned if the predicate yields true with $(D
switchExpression) and the test expression as arguments. May also have a
default return expression, that needs to be the last expression without a test
expression before it. A return expression may be of void type only if it
always throws.
Returns: The return expression associated with the first test expression that
made the predicate yield true, or the default return expression if no test
expression matched.
Throws: If there is no default return expression and the predicate does not
yield true with any test expression - $(D SwitchError) is thrown. $(D
SwitchError) is also thrown if a void return expression was executed without
throwing anything.
*/
auto predSwitch(alias pred = "a == b", T, R ...)(T switchExpression, lazy R choices)
{
import core.exception : SwitchError;
alias predicate = binaryFun!(pred);
foreach (index, ChoiceType; R)
{
//The even places in `choices` are for the predicate.
static if (index % 2 == 1)
{
if (predicate(switchExpression, choices[index - 1]()))
{
static if (is(typeof(choices[index]()) == void))
{
choices[index]();
throw new SwitchError("Choices that return void should throw");
}
else
{
return choices[index]();
}
}
}
}
//In case nothing matched:
static if (R.length % 2 == 1) //If there is a default return expression:
{
static if (is(typeof(choices[$ - 1]()) == void))
{
choices[$ - 1]();
throw new SwitchError("Choices that return void should throw");
}
else
{
return choices[$ - 1]();
}
}
else //If there is no default return expression:
{
throw new SwitchError("Input not matched by any pattern");
}
}
///
@safe unittest
{
string res = 2.predSwitch!"a < b"(
1, "less than 1",
5, "less than 5",
10, "less than 10",
"greater or equal to 10");
assert(res == "less than 5");
//The arguments are lazy, which allows us to use predSwitch to create
//recursive functions:
int factorial(int n)
{
return n.predSwitch!"a <= b"(
-1, {throw new Exception("Can not calculate n! for n < 0");}(),
0, 1, // 0! = 1
n * factorial(n - 1) // n! = n * (n - 1)! for n >= 0
);
}
assert(factorial(3) == 6);
//Void return expressions are allowed if they always throw:
import std.exception : assertThrown;
assertThrown!Exception(factorial(-9));
}
@system unittest
{
import core.exception : SwitchError;
import std.exception : assertThrown;
//Nothing matches - with default return expression:
assert(20.predSwitch!"a < b"(
1, "less than 1",
5, "less than 5",
10, "less than 10",
"greater or equal to 10") == "greater or equal to 10");
//Nothing matches - without default return expression:
assertThrown!SwitchError(20.predSwitch!"a < b"(
1, "less than 1",
5, "less than 5",
10, "less than 10",
));
//Using the default predicate:
assert(2.predSwitch(
1, "one",
2, "two",
3, "three",
) == "two");
//Void return expressions must always throw:
assertThrown!SwitchError(1.predSwitch(
0, "zero",
1, {}(), //A void return expression that doesn't throw
2, "two",
));
}
/**
Checks if the two ranges have the same number of elements. This function is
optimized to always take advantage of the $(D length) member of either range
if it exists.
If both ranges have a length member, this function is $(BIGOH 1). Otherwise,
this function is $(BIGOH min(r1.length, r2.length)).
Params:
r1 = a finite input range
r2 = a finite input range
Returns:
$(D true) if both ranges have the same length, $(D false) otherwise.
*/
bool isSameLength(Range1, Range2)(Range1 r1, Range2 r2)
if (isInputRange!Range1 &&
isInputRange!Range2 &&
!isInfinite!Range1 &&
!isInfinite!Range2)
{
static if (hasLength!(Range1) && hasLength!(Range2))
{
return r1.length == r2.length;
}
else static if (hasLength!(Range1) && !hasLength!(Range2))
{
size_t length;
while (!r2.empty)
{
r2.popFront;
if (++length > r1.length)
{
return false;
}
}
return !(length < r1.length);
}
else static if (!hasLength!(Range1) && hasLength!(Range2))
{
size_t length;
while (!r1.empty)
{
r1.popFront;
if (++length > r2.length)
{
return false;
}
}
return !(length < r2.length);
}
else
{
while (!r1.empty)
{
if (r2.empty)
{
return false;
}
r1.popFront;
r2.popFront;
}
return r2.empty;
}
}
///
@safe nothrow pure unittest
{
assert(isSameLength([1, 2, 3], [4, 5, 6]));
assert(isSameLength([0.3, 90.4, 23.7, 119.2], [42.6, 23.6, 95.5, 6.3]));
assert(isSameLength("abc", "xyz"));
int[] a;
int[] b;
assert(isSameLength(a, b));
assert(!isSameLength([1, 2, 3], [4, 5]));
assert(!isSameLength([0.3, 90.4, 23.7], [42.6, 23.6, 95.5, 6.3]));
assert(!isSameLength("abcd", "xyz"));
}
// Test CTFE
@safe pure unittest
{
enum result1 = isSameLength([1, 2, 3], [4, 5, 6]);
static assert(result1);
enum result2 = isSameLength([0.3, 90.4, 23.7], [42.6, 23.6, 95.5, 6.3]);
static assert(!result2);
}
@safe nothrow pure unittest
{
import std.internal.test.dummyrange;
auto r1 = new ReferenceInputRange!int([1, 2, 3]);
auto r2 = new ReferenceInputRange!int([4, 5, 6]);
assert(isSameLength(r1, r2));
auto r3 = new ReferenceInputRange!int([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Input) r4;
assert(isSameLength(r3, r4));
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Input) r5;
auto r6 = new ReferenceInputRange!int([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
assert(isSameLength(r5, r6));
auto r7 = new ReferenceInputRange!int([1, 2]);
auto r8 = new ReferenceInputRange!int([4, 5, 6]);
assert(!isSameLength(r7, r8));
auto r9 = new ReferenceInputRange!int([1, 2, 3, 4, 5, 6, 7, 8]);
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Input) r10;
assert(!isSameLength(r9, r10));
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Input) r11;
auto r12 = new ReferenceInputRange!int([1, 2, 3, 4, 5, 6, 7, 8]);
assert(!isSameLength(r11, r12));
}
/// For convenience
alias AllocateGC = Flag!"allocateGC";
/**
Checks if both ranges are permutations of each other.
This function can allocate if the $(D Yes.allocateGC) flag is passed. This has
the benefit of have better complexity than the $(D Yes.allocateGC) option. However,
this option is only available for ranges whose equality can be determined via each
element's $(D toHash) method. If customized equality is needed, then the $(D pred)
template parameter can be passed, and the function will automatically switch to
the non-allocating algorithm. See $(REF binaryFun, std,functional) for more details on
how to define $(D pred).
Non-allocating forward range option: $(BIGOH n^2)
Non-allocating forward range option with custom $(D pred): $(BIGOH n^2)
Allocating forward range option: amortized $(BIGOH r1.length) + $(BIGOH r2.length)
Params:
pred = an optional parameter to change how equality is defined
allocate_gc = $(D Yes.allocateGC)/$(D No.allocateGC)
r1 = A finite forward range
r2 = A finite forward range
Returns:
$(D true) if all of the elements in $(D r1) appear the same number of times in $(D r2).
Otherwise, returns $(D false).
*/
bool isPermutation(AllocateGC allocate_gc, Range1, Range2)
(Range1 r1, Range2 r2)
if (allocate_gc == Yes.allocateGC &&
isForwardRange!Range1 &&
isForwardRange!Range2 &&
!isInfinite!Range1 &&
!isInfinite!Range2)
{
alias E1 = Unqual!(ElementType!Range1);
alias E2 = Unqual!(ElementType!Range2);
if (!isSameLength(r1.save, r2.save))
{
return false;
}
// Skip the elements at the beginning where r1.front == r2.front,
// they are in the same order and don't need to be counted.
while (!r1.empty && !r2.empty && r1.front == r2.front)
{
r1.popFront();
r2.popFront();
}
if (r1.empty && r2.empty)
{
return true;
}
int[CommonType!(E1, E2)] counts;
foreach (item; r1)
{
++counts[item];
}
foreach (item; r2)
{
if (--counts[item] < 0)
{
return false;
}
}
return true;
}
/// ditto
bool isPermutation(alias pred = "a == b", Range1, Range2)
(Range1 r1, Range2 r2)
if (is(typeof(binaryFun!(pred))) &&
isForwardRange!Range1 &&
isForwardRange!Range2 &&
!isInfinite!Range1 &&
!isInfinite!Range2)
{
import std.algorithm.searching : count;
alias predEquals = binaryFun!(pred);
alias E1 = Unqual!(ElementType!Range1);
alias E2 = Unqual!(ElementType!Range2);
if (!isSameLength(r1.save, r2.save))
{
return false;
}
// Skip the elements at the beginning where r1.front == r2.front,
// they are in the same order and don't need to be counted.
while (!r1.empty && !r2.empty && predEquals(r1.front, r2.front))
{
r1.popFront();
r2.popFront();
}
if (r1.empty && r2.empty)
{
return true;
}
size_t r1_count;
size_t r2_count;
// At each element item, when computing the count of item, scan it while
// also keeping track of the scanning index. If the first occurrence
// of item in the scanning loop has an index smaller than the current index,
// then you know that the element has been seen before
size_t index;
outloop: for (auto r1s1 = r1.save; !r1s1.empty; r1s1.popFront, index++)
{
auto item = r1s1.front;
r1_count = 0;
r2_count = 0;
size_t i;
for (auto r1s2 = r1.save; !r1s2.empty; r1s2.popFront, i++)
{
auto e = r1s2.front;
if (predEquals(e, item) && i < index)
{
continue outloop;
}
else if (predEquals(e, item))
{
++r1_count;
}
}
r2_count = r2.save.count!pred(item);
if (r1_count != r2_count)
{
return false;
}
}
return true;
}
///
@safe pure unittest
{
assert(isPermutation([1, 2, 3], [3, 2, 1]));
assert(isPermutation([1.1, 2.3, 3.5], [2.3, 3.5, 1.1]));
assert(isPermutation("abc", "bca"));
assert(!isPermutation([1, 2], [3, 4]));
assert(!isPermutation([1, 1, 2, 3], [1, 2, 2, 3]));
assert(!isPermutation([1, 1], [1, 1, 1]));
// Faster, but allocates GC handled memory
assert(isPermutation!(Yes.allocateGC)([1.1, 2.3, 3.5], [2.3, 3.5, 1.1]));
assert(!isPermutation!(Yes.allocateGC)([1, 2], [3, 4]));
}
// Test @nogc inference
@safe @nogc pure unittest
{
static immutable arr1 = [1, 2, 3];
static immutable arr2 = [3, 2, 1];
assert(isPermutation(arr1, arr2));
static immutable arr3 = [1, 1, 2, 3];
static immutable arr4 = [1, 2, 2, 3];
assert(!isPermutation(arr3, arr4));
}
@safe pure unittest
{
import std.internal.test.dummyrange;
auto r1 = new ReferenceForwardRange!int([1, 2, 3, 4]);
auto r2 = new ReferenceForwardRange!int([1, 2, 4, 3]);
assert(isPermutation(r1, r2));
auto r3 = new ReferenceForwardRange!int([1, 2, 3, 4]);
auto r4 = new ReferenceForwardRange!int([4, 2, 1, 3]);
assert(isPermutation!(Yes.allocateGC)(r3, r4));
auto r5 = new ReferenceForwardRange!int([1, 2, 3]);
auto r6 = new ReferenceForwardRange!int([4, 2, 1, 3]);
assert(!isPermutation(r5, r6));
auto r7 = new ReferenceForwardRange!int([4, 2, 1, 3]);
auto r8 = new ReferenceForwardRange!int([1, 2, 3]);
assert(!isPermutation!(Yes.allocateGC)(r7, r8));
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Random) r9;
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Random) r10;
assert(isPermutation(r9, r10));
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Random) r11;
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Random) r12;
assert(isPermutation!(Yes.allocateGC)(r11, r12));
alias mytuple = Tuple!(int, int);
assert(isPermutation!"a[0] == b[0]"(
[mytuple(1, 4), mytuple(2, 5)],
[mytuple(2, 3), mytuple(1, 2)]
));
}
/**
Get the _first argument `a` that passes an `if (unaryFun!pred(a))` test. If
no argument passes the test, return the last argument.
Similar to behaviour of the `or` operator in dynamic languages such as Lisp's
`(or ...)` and Python's `a or b or ...` except that the last argument is
returned upon no match.
Simplifies logic, for instance, in parsing rules where a set of alternative
matchers are tried. The _first one that matches returns it match result,
typically as an abstract syntax tree (AST).
Bugs:
Lazy parameters are currently, too restrictively, inferred by DMD to
always throw even though they don't need to be. This makes it impossible to
currently mark `either` as `nothrow`. See issue at $(BUGZILLA 12647).
Returns:
The _first argument that passes the test `pred`.
*/
CommonType!(T, Ts) either(alias pred = a => a, T, Ts...)(T first, lazy Ts alternatives)
if (alternatives.length >= 1 &&
!is(CommonType!(T, Ts) == void) &&
allSatisfy!(ifTestable, T, Ts))
{
alias predFun = unaryFun!pred;
if (predFun(first)) return first;
foreach (e; alternatives[0 .. $ - 1])
if (predFun(e)) return e;
return alternatives[$ - 1];
}
///
@safe pure unittest
{
const a = 1;
const b = 2;
auto ab = either(a, b);
static assert(is(typeof(ab) == const(int)));
assert(ab == a);
auto c = 2;
const d = 3;
auto cd = either!(a => a == 3)(c, d); // use predicate
static assert(is(typeof(cd) == int));
assert(cd == d);
auto e = 0;
const f = 2;
auto ef = either(e, f);
static assert(is(typeof(ef) == int));
assert(ef == f);
immutable p = 1;
immutable q = 2;
auto pq = either(p, q);
static assert(is(typeof(pq) == immutable(int)));
assert(pq == p);
assert(either(3, 4) == 3);
assert(either(0, 4) == 4);
assert(either(0, 0) == 0);
assert(either("", "a") == "");
string r = null;
assert(either(r, "a") == "a");
assert(either("a", "") == "a");
immutable s = [1, 2];
assert(either(s, s) == s);
assert(either([0, 1], [1, 2]) == [0, 1]);
assert(either([0, 1], [1]) == [0, 1]);
assert(either("a", "b") == "a");
static assert(!__traits(compiles, either(1, "a")));
static assert(!__traits(compiles, either(1.0, "a")));
static assert(!__traits(compiles, either('a', "a")));
}
|
D
|
module UnrealScript.Engine.Interface_NavMeshPathObstacle;
import ScriptClasses;
import UnrealScript.Helpers;
import UnrealScript.Core.UInterface;
extern(C++) interface Interface_NavMeshPathObstacle : UInterface
{
public extern(D):
private static __gshared ScriptClass mStaticClass;
@property final static ScriptClass StaticClass() { mixin(MGSCC("Class Engine.Interface_NavMeshPathObstacle")); }
private static __gshared Interface_NavMeshPathObstacle mDefaultProperties;
@property final static Interface_NavMeshPathObstacle DefaultProperties() { mixin(MGDPC("Interface_NavMeshPathObstacle", "Interface_NavMeshPathObstacle Engine.Default__Interface_NavMeshPathObstacle")); }
enum EEdgeHandlingStatus : ubyte
{
EHS_AddedBothDirs = 0,
EHS_Added0to1 = 1,
EHS_Added1to0 = 2,
EHS_AddedNone = 3,
EHS_MAX = 4,
}
}
|
D
|
instance Mod_7653_JG_Gandal_JL (Npc_Default)
{
// ------ NSC ------
name = "Gandal";
guild = GIL_OUT;
id = 7653;
voice = 12;
flags = 0; //NPC_FLAG_IMMORTAL oder 0
npctype = NPCTYPE_MAIN;
// ------ Attribute ------
B_SetAttributesToChapter (self, 3); //setzt Attribute und LEVEL entsprechend dem angegebenen Kapitel (1-6)
// ------ Kampf-Taktik ------
fight_tactic = FAI_HUMAN_STRONG; // MASTER / STRONG / COWARD
// ------ Equippte Waffen ------ //Munition wird automatisch generiert, darf aber angegeben werden
EquipItem (self, ItMw_1H_quantarie_Fantasyschwert_01);
EquipItem (self, ItRw_Bow_War_03);
// ------ 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_NormalBart20, BodyTex_N, ITAR_Waldlaeufer_01);
Mdl_SetModelFatness (self, 1);
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, 75); //Grenzen für Talent-Level liegen bei 30 und 60
// ------ TA anmelden ------
daily_routine = Rtn_Start_7653;
};
FUNC VOID Rtn_Start_7653 ()
{
TA_Practice_Bow (08,00,23,00,"JL_47");
TA_Sleep (23,00,08,00,"JL_40");
};
|
D
|
/home/roldan/Documentos/TFG/TFG/rust/rust_search_1000000_middle_case/target/release/build/rand_pcg-16535aed8fb34644/build_script_build-16535aed8fb34644: /home/roldan/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_pcg-0.1.2/build.rs
/home/roldan/Documentos/TFG/TFG/rust/rust_search_1000000_middle_case/target/release/build/rand_pcg-16535aed8fb34644/build_script_build-16535aed8fb34644.d: /home/roldan/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_pcg-0.1.2/build.rs
/home/roldan/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_pcg-0.1.2/build.rs:
|
D
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.