code
stringlengths
3
10M
language
stringclasses
31 values
/Users/dali/Documents/GitHub/rustlings/target/debug/deps/aho_corasick-7430d0e02822d037.rmeta: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/lib.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/ahocorasick.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/automaton.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/buffer.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/byte_frequencies.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/classes.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/dfa.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/error.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/nfa.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/mod.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/api.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/pattern.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/rabinkarp.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/teddy/mod.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/teddy/compile.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/teddy/runtime.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/vector.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/prefilter.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/state_id.rs /Users/dali/Documents/GitHub/rustlings/target/debug/deps/aho_corasick-7430d0e02822d037.d: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/lib.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/ahocorasick.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/automaton.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/buffer.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/byte_frequencies.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/classes.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/dfa.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/error.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/nfa.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/mod.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/api.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/pattern.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/rabinkarp.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/teddy/mod.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/teddy/compile.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/teddy/runtime.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/vector.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/prefilter.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/state_id.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/lib.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/ahocorasick.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/automaton.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/buffer.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/byte_frequencies.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/classes.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/dfa.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/error.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/nfa.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/mod.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/api.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/pattern.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/rabinkarp.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/teddy/mod.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/teddy/compile.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/teddy/runtime.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/packed/vector.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/prefilter.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/aho-corasick-0.7.15/src/state_id.rs:
D
/* ********************************************************************** ** md5.c ** ** RSA Data Security, Inc. MD5 Message Digest Algorithm ** ** Created: 2/17/90 RLR ** ** Revised: 1/91 SRD,AJ,BSK,JT Reference C Version ** ********************************************************************** */ module dmd.backend.md5; /* ********************************************************************** ** Copyright (C) 1990, RSA Data Security, Inc. All rights reserved. ** ** ** ** License to copy and use this software is granted provided that ** ** it is identified as the "RSA Data Security, Inc. MD5 Message ** ** Digest Algorithm" in all material mentioning or referencing this ** ** software or this function. ** ** ** ** License is also granted to make and use derivative works ** ** provided that such works are identified as "derived from the RSA ** ** Data Security, Inc. MD5 Message Digest Algorithm" in all ** ** material mentioning or referencing the derived work. ** ** ** ** RSA Data Security, Inc. makes no representations concerning ** ** either the merchantability of this software or the suitability ** ** of this software for any particular purpose. It is provided "as ** ** is" without express or implied warranty of any kind. ** ** ** ** These notices must be retained in any copies of any part of this ** ** documentation and/or software. ** ********************************************************************** */ /* -- include the following line if the md5.h header file is separate -- */ extern (C++): nothrow: @nogc: @safe: private: /* typedef a 32 bit type */ alias UINT4 = uint; /* Data structure for MD5 (Message Digest) computation */ public struct MD5_CTX { UINT4[2] i; /* number of _bits_ handled mod 2^64 */ UINT4[4] buf; /* scratch buffer */ ubyte[64] in_; /* input buffer */ ubyte[16] digest; /* actual digest after MD5Final call */ } __gshared ubyte[64] PADDING = [ 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ]; /* F, G and H are basic MD5 functions: selection, majority, parity */ UINT4 F(UINT4 x, UINT4 y, UINT4 z) { return (x & y) | (~x & z); } UINT4 G(UINT4 x, UINT4 y, UINT4 z) { return (x & z) | (y & ~z); } UINT4 H(UINT4 x, UINT4 y, UINT4 z) { return x ^ y ^ z; } UINT4 I(UINT4 x, UINT4 y, UINT4 z) { return y ^ (x | ~z); } /* ROTATE_LEFT rotates x left n bits */ UINT4 ROTATE_LEFT(UINT4 x, UINT4 n) { return (x << n) | (x >> (32-n)); } /* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4 */ /* Rotation is separate from addition to prevent recomputation */ void FF(ref UINT4 a, UINT4 b, UINT4 c, UINT4 d, UINT4 x, UINT4 s, UINT4 ac) {a += F (b, c, d) + x + cast(UINT4)ac; a = ROTATE_LEFT (a, s); a += b; } void GG(ref UINT4 a, UINT4 b, UINT4 c, UINT4 d, UINT4 x, UINT4 s, UINT4 ac) {a += G (b, c, d) + x + cast(UINT4)ac; a = ROTATE_LEFT (a, s); a += b; } void HH(ref UINT4 a, UINT4 b, UINT4 c, UINT4 d, UINT4 x, UINT4 s, UINT4 ac) {a += H (b, c, d) + x + cast(UINT4)ac; a = ROTATE_LEFT (a, s); a += b; } void II(ref UINT4 a, UINT4 b, UINT4 c, UINT4 d, UINT4 x, UINT4 s, UINT4 ac) {a += I (b, c, d) + x + cast(UINT4)ac; a = ROTATE_LEFT (a, s); a += b; } public void MD5Init (MD5_CTX *mdContext) { mdContext.i[0] = mdContext.i[1] = cast(UINT4)0; /* Load magic initialization constants. */ mdContext.buf[0] = cast(UINT4)0x67452301; mdContext.buf[1] = cast(UINT4)0xefcdab89; mdContext.buf[2] = cast(UINT4)0x98badcfe; mdContext.buf[3] = cast(UINT4)0x10325476; } @trusted public void MD5Update (MD5_CTX *mdContext, ubyte *inBuf, uint inLen) { UINT4[16] in_; int mdi; uint i, ii; /* compute number of bytes mod 64 */ mdi = cast(int)((mdContext.i[0] >> 3) & 0x3F); /* update number of bits */ if ((mdContext.i[0] + (cast(UINT4)inLen << 3)) < mdContext.i[0]) mdContext.i[1]++; mdContext.i[0] += (cast(UINT4)inLen << 3); mdContext.i[1] += (cast(UINT4)inLen >> 29); while (inLen--) { /* add new character to buffer, increment mdi */ mdContext.in_[mdi++] = *inBuf++; /* transform if necessary */ if (mdi == 0x40) { for (i = 0, ii = 0; i < 16; i++, ii += 4) in_[i] = ((cast(UINT4)mdContext.in_[ii+3]) << 24) | ((cast(UINT4)mdContext.in_[ii+2]) << 16) | ((cast(UINT4)mdContext.in_[ii+1]) << 8) | (cast(UINT4)mdContext.in_[ii]); Transform (&mdContext.buf[0], &in_[0]); mdi = 0; } } } @trusted public void MD5Final (MD5_CTX *mdContext) { UINT4[16] in_; int mdi; uint i, ii; uint padLen; /* save number of bits */ in_[14] = mdContext.i[0]; in_[15] = mdContext.i[1]; /* compute number of bytes mod 64 */ mdi = cast(int)((mdContext.i[0] >> 3) & 0x3F); /* pad out to 56 mod 64 */ padLen = (mdi < 56) ? (56 - mdi) : (120 - mdi); MD5Update (mdContext, &PADDING[0], padLen); /* append length in bits and transform */ for (i = 0, ii = 0; i < 14; i++, ii += 4) in_[i] = ((cast(UINT4)mdContext.in_[ii+3]) << 24) | ((cast(UINT4)mdContext.in_[ii+2]) << 16) | ((cast(UINT4)mdContext.in_[ii+1]) << 8) | (cast(UINT4)mdContext.in_[ii]); Transform (&mdContext.buf[0], &in_[0]); /* store buffer in digest */ for (i = 0, ii = 0; i < 4; i++, ii += 4) { mdContext.digest[ii] = cast(ubyte)(mdContext.buf[i] & 0xFF); mdContext.digest[ii+1] = cast(ubyte)((mdContext.buf[i] >> 8) & 0xFF); mdContext.digest[ii+2] = cast(ubyte)((mdContext.buf[i] >> 16) & 0xFF); mdContext.digest[ii+3] = cast(ubyte)((mdContext.buf[i] >> 24) & 0xFF); } } /* Basic MD5 step. Transform buf based on in. */ @trusted void Transform (UINT4 *buf, UINT4 *in_) { UINT4 a = buf[0], b = buf[1], c = buf[2], d = buf[3]; /* Round 1 */ enum S11 = 7; enum S12 = 12; enum S13 = 17; enum S14 = 22; FF ( a, b, c, d, in_[ 0], S11, 3614090360U); /* 1 */ FF ( d, a, b, c, in_[ 1], S12, 3905402710U); /* 2 */ FF ( c, d, a, b, in_[ 2], S13, 606105819U); /* 3 */ FF ( b, c, d, a, in_[ 3], S14, 3250441966U); /* 4 */ FF ( a, b, c, d, in_[ 4], S11, 4118548399U); /* 5 */ FF ( d, a, b, c, in_[ 5], S12, 1200080426U); /* 6 */ FF ( c, d, a, b, in_[ 6], S13, 2821735955U); /* 7 */ FF ( b, c, d, a, in_[ 7], S14, 4249261313U); /* 8 */ FF ( a, b, c, d, in_[ 8], S11, 1770035416U); /* 9 */ FF ( d, a, b, c, in_[ 9], S12, 2336552879U); /* 10 */ FF ( c, d, a, b, in_[10], S13, 4294925233U); /* 11 */ FF ( b, c, d, a, in_[11], S14, 2304563134U); /* 12 */ FF ( a, b, c, d, in_[12], S11, 1804603682U); /* 13 */ FF ( d, a, b, c, in_[13], S12, 4254626195U); /* 14 */ FF ( c, d, a, b, in_[14], S13, 2792965006U); /* 15 */ FF ( b, c, d, a, in_[15], S14, 1236535329U); /* 16 */ /* Round 2 */ enum S21 = 5; enum S22 = 9; enum S23 = 14; enum S24 = 20; GG ( a, b, c, d, in_[ 1], S21, 4129170786U); /* 17 */ GG ( d, a, b, c, in_[ 6], S22, 3225465664U); /* 18 */ GG ( c, d, a, b, in_[11], S23, 643717713U); /* 19 */ GG ( b, c, d, a, in_[ 0], S24, 3921069994U); /* 20 */ GG ( a, b, c, d, in_[ 5], S21, 3593408605U); /* 21 */ GG ( d, a, b, c, in_[10], S22, 38016083U); /* 22 */ GG ( c, d, a, b, in_[15], S23, 3634488961U); /* 23 */ GG ( b, c, d, a, in_[ 4], S24, 3889429448U); /* 24 */ GG ( a, b, c, d, in_[ 9], S21, 568446438U); /* 25 */ GG ( d, a, b, c, in_[14], S22, 3275163606U); /* 26 */ GG ( c, d, a, b, in_[ 3], S23, 4107603335U); /* 27 */ GG ( b, c, d, a, in_[ 8], S24, 1163531501U); /* 28 */ GG ( a, b, c, d, in_[13], S21, 2850285829U); /* 29 */ GG ( d, a, b, c, in_[ 2], S22, 4243563512U); /* 30 */ GG ( c, d, a, b, in_[ 7], S23, 1735328473U); /* 31 */ GG ( b, c, d, a, in_[12], S24, 2368359562U); /* 32 */ /* Round 3 */ enum S31 = 4; enum S32 = 11; enum S33 = 16; enum S34 = 23; HH ( a, b, c, d, in_[ 5], S31, 4294588738U); /* 33 */ HH ( d, a, b, c, in_[ 8], S32, 2272392833U); /* 34 */ HH ( c, d, a, b, in_[11], S33, 1839030562U); /* 35 */ HH ( b, c, d, a, in_[14], S34, 4259657740U); /* 36 */ HH ( a, b, c, d, in_[ 1], S31, 2763975236U); /* 37 */ HH ( d, a, b, c, in_[ 4], S32, 1272893353U); /* 38 */ HH ( c, d, a, b, in_[ 7], S33, 4139469664U); /* 39 */ HH ( b, c, d, a, in_[10], S34, 3200236656U); /* 40 */ HH ( a, b, c, d, in_[13], S31, 681279174U); /* 41 */ HH ( d, a, b, c, in_[ 0], S32, 3936430074U); /* 42 */ HH ( c, d, a, b, in_[ 3], S33, 3572445317U); /* 43 */ HH ( b, c, d, a, in_[ 6], S34, 76029189U); /* 44 */ HH ( a, b, c, d, in_[ 9], S31, 3654602809U); /* 45 */ HH ( d, a, b, c, in_[12], S32, 3873151461U); /* 46 */ HH ( c, d, a, b, in_[15], S33, 530742520U); /* 47 */ HH ( b, c, d, a, in_[ 2], S34, 3299628645U); /* 48 */ /* Round 4 */ enum S41 = 6; enum S42 = 10; enum S43 = 15; enum S44 = 21; II ( a, b, c, d, in_[ 0], S41, 4096336452U); /* 49 */ II ( d, a, b, c, in_[ 7], S42, 1126891415U); /* 50 */ II ( c, d, a, b, in_[14], S43, 2878612391U); /* 51 */ II ( b, c, d, a, in_[ 5], S44, 4237533241U); /* 52 */ II ( a, b, c, d, in_[12], S41, 1700485571U); /* 53 */ II ( d, a, b, c, in_[ 3], S42, 2399980690U); /* 54 */ II ( c, d, a, b, in_[10], S43, 4293915773U); /* 55 */ II ( b, c, d, a, in_[ 1], S44, 2240044497U); /* 56 */ II ( a, b, c, d, in_[ 8], S41, 1873313359U); /* 57 */ II ( d, a, b, c, in_[15], S42, 4264355552U); /* 58 */ II ( c, d, a, b, in_[ 6], S43, 2734768916U); /* 59 */ II ( b, c, d, a, in_[13], S44, 1309151649U); /* 60 */ II ( a, b, c, d, in_[ 4], S41, 4149444226U); /* 61 */ II ( d, a, b, c, in_[11], S42, 3174756917U); /* 62 */ II ( c, d, a, b, in_[ 2], S43, 718787259U); /* 63 */ II ( b, c, d, a, in_[ 9], S44, 3951481745U); /* 64 */ buf[0] += a; buf[1] += b; buf[2] += c; buf[3] += d; } /* ********************************************************************** ** End of md5.c ** ******************************* (cut) ******************************** */
D
module engine.chunk.meshgen; import engine.chunk.mesh; import engine; import engine.render; import std.concurrency; import core.atomic; import core.time; import core.sync.mutex; import core.thread; import std.algorithm.sorting; import std.algorithm.mutation; private { vec3[] voxelVerts = [ // TOP vec3(0, 1, 0), vec3(0, 1, 1), vec3(1, 1, 0), vec3(1, 1, 0), vec3(0, 1, 1), vec3(1, 1, 1), // BOTTOM vec3(0, 0, 0), vec3(1, 0, 0), vec3(0, 0, 1), vec3(0, 0, 1), vec3(1, 0, 0), vec3(1, 0, 1), // FRONT vec3(0, 1, 1), vec3(0, 0, 1), vec3(1, 1, 1), vec3(1, 1, 1), vec3(0, 0, 1), vec3(1, 0, 1), // BACK vec3(0, 1, 0), vec3(1, 1, 0), vec3(0, 0, 0), vec3(0, 0, 0), vec3(1, 1, 0), vec3(1, 0, 0), // RIGHT vec3(1, 1, 0), vec3(1, 1, 1), vec3(1, 0, 0), vec3(1, 0, 0), vec3(1, 1, 1), vec3(1, 0, 1), // LEFT vec3(0, 1, 0), vec3(0, 0, 0), vec3(0, 1, 1), vec3(0, 1, 1), vec3(0, 0, 0), vec3(0, 0, 1), ]; } /** View in to chunk TODO: Access the chunk data atomically */ struct CMView { this(ref Chunk chunk) { Chunk chl = chunk.chunkLeft; Chunk chr = chunk.chunkRight; Chunk chf = chunk.chunkFront; Chunk chb = chunk.chunkBack; import core.atomic : atomicLoad; position = vec3(chunk.worldPosition.x, chunk.worldPosition.y, chunk.worldPosition.z); this.mstore = chunk.store; if (chl) this.cl = chl.store; else if (!chl || !chl.store) hasLeft = false; if (chr) this.cr = chr.store; else if (!chr || !chr.store) hasRight = false; if (chf) this.cf = chf.store; else if (!chf || !chf.store) hasFront = false; if (chb) this.cb = chb.store; else if (!chb || !chb.store) hasBack = false; } immutable(vec3) position; immutable(ChunkBlockStore)* mstore; immutable(ChunkBlockStore)* cl; bool hasLeft = true; immutable(ChunkBlockStore)* cr; bool hasRight = true; immutable(ChunkBlockStore)* cf; bool hasFront = true; immutable(ChunkBlockStore)* cb; bool hasBack = true; } /** Mesh generation task */ struct MeshGenTask { ChunkVertexBuffer* buffer; ChunkVertexBuffer* trbuffer; CMView data; /** Returns the distance of this task to the player */ float distanceToPlayer() { return abs(data.position.distance(FcCamera.worldPosition)); } } /** Mesh generation task return data */ struct MeshGenResponse { ChunkVertexBuffer* buffer; ChunkVertexBuffer* trbuffer; immutable(CMData[]) data; immutable(CMData[]) trdata; } /** The mesh generator */ class MeshGenerator { private static: CMData[][2] generateMesh(CMView data) { CMData[] bufferToWrite; CMData[] tbufferToWrite; for(int y; y < ChunkHeight; y++) { for(int z; z < ChunkSize; z++) { for(int x; x < ChunkSize; x++) { // Air blocks create no meshed part if (data.mstore.blocks[x][y][z] == 0) continue; Block block = fcGetBlock(data.mstore.blocks[x][y][z]); // Skip blocks with invalid IDs; TODO: make those blocks a special placeholder block if (block is null) continue; bool blockTr = block.isTransparent; bool blockFreeLeft = (x > 0 && ( data.mstore.blocks[x-1][y][z] == 0 || (!blockTr && fcGetBlock(data.mstore.blocks[x-1][y][z]).isTransparent) )) || (x == 0 && data.hasLeft && ( data.cl.blocks[ChunkSize-1][y][z] == 0 || (!blockTr && fcGetBlock(data.cl.blocks[ChunkSize-1][y][z]).isTransparent) )) || (!data.hasLeft && x == 0); bool blockFreeRight = (x < ChunkSize-1 && ( data.mstore.blocks[x+1][y][z] == 0 || (!blockTr && fcGetBlock(data.mstore.blocks[x+1][y][z]).isTransparent) )) || (x == ChunkSize-1 && data.hasRight && ( data.cr.blocks[0][y][z] == 0 || (!blockTr && fcGetBlock(data.cr.blocks[0][y][z]).isTransparent) )) || (!data.hasRight && x == ChunkSize-1); bool blockFreeBack = (z > 0 && ( data.mstore.blocks[x][y][z-1] == 0 || (!blockTr && fcGetBlock(data.mstore.blocks[x][y][z-1]).isTransparent) )) || (z == 0 && data.hasBack && ( data.cb.blocks[x][y][ChunkSize-1] == 0 || (!blockTr && fcGetBlock(data.cb.blocks[x][y][ChunkSize-1]).isTransparent) )) || (!data.hasBack && z == 0); bool blockFreeFront = (z < ChunkSize-1 && ( data.mstore.blocks[x][y][z+1] == 0 || (!blockTr && fcGetBlock(data.mstore.blocks[x][y][z+1]).isTransparent) )) || (z == ChunkSize-1 && data.hasFront && ( data.cf.blocks[x][y][0] == 0 || (!blockTr && fcGetBlock(data.cf.blocks[x][y][0]).isTransparent) )) || (!data.hasFront && z == ChunkSize-1); bool blockFreeBottom = (y > 0 && ( data.mstore.blocks[x][y-1][z] == 0 || (!blockTr && fcGetBlock(data.mstore.blocks[x][y-1][z]).isTransparent) )) || y == 0; bool blockFreeTop = (y < ChunkHeight-1 && ( data.mstore.blocks[x][y+1][z] == 0 || (!blockTr && fcGetBlock(data.mstore.blocks[x][y+1][z]).isTransparent) )) || y == ChunkHeight-1; vec3 cpos = vec3(x, y, z); // Top cap if (blockFreeTop) { vec4 uvs = fcAtlasGet(block.textures[2]); if (blockTr) tbufferToWrite ~= ([ CMData(cpos+voxelVerts[0], vec2(uvs.x, uvs.y), 1.0), CMData(cpos+voxelVerts[1], vec2(uvs.x, uvs.w), 1.0), CMData(cpos+voxelVerts[2], vec2(uvs.z, uvs.y), 1.0), CMData(cpos+voxelVerts[3], vec2(uvs.z, uvs.y), 1.0), CMData(cpos+voxelVerts[4], vec2(uvs.x, uvs.w), 1.0), CMData(cpos+voxelVerts[5], vec2(uvs.z, uvs.w), 1.0), ]); else bufferToWrite ~= ([ CMData(cpos+voxelVerts[0], vec2(uvs.x, uvs.y), 1.0), CMData(cpos+voxelVerts[1], vec2(uvs.x, uvs.w), 1.0), CMData(cpos+voxelVerts[2], vec2(uvs.z, uvs.y), 1.0), CMData(cpos+voxelVerts[3], vec2(uvs.z, uvs.y), 1.0), CMData(cpos+voxelVerts[4], vec2(uvs.x, uvs.w), 1.0), CMData(cpos+voxelVerts[5], vec2(uvs.z, uvs.w), 1.0), ]); } // Bottom cap if (blockFreeBottom) { vec4 uvs = fcAtlasGet(block.textures[3]); if (blockTr) tbufferToWrite ~= ([ CMData(cpos+voxelVerts[6], vec2(uvs.x, uvs.y), 0.3), CMData(cpos+voxelVerts[7], vec2(uvs.x, uvs.w), 0.3), CMData(cpos+voxelVerts[8], vec2(uvs.z, uvs.y), 0.3), CMData(cpos+voxelVerts[9], vec2(uvs.z, uvs.y), 0.3), CMData(cpos+voxelVerts[10], vec2(uvs.x, uvs.w), 0.3), CMData(cpos+voxelVerts[11], vec2(uvs.z, uvs.w), 0.3), ]); else bufferToWrite ~= ([ CMData(cpos+voxelVerts[6], vec2(uvs.x, uvs.y), 0.3), CMData(cpos+voxelVerts[7], vec2(uvs.x, uvs.w), 0.3), CMData(cpos+voxelVerts[8], vec2(uvs.z, uvs.y), 0.3), CMData(cpos+voxelVerts[9], vec2(uvs.z, uvs.y), 0.3), CMData(cpos+voxelVerts[10], vec2(uvs.x, uvs.w), 0.3), CMData(cpos+voxelVerts[11], vec2(uvs.z, uvs.w), 0.3), ]); } // Back cap if (blockFreeBack) { vec4 uvs = fcAtlasGet(block.textures[1]); if (blockTr) tbufferToWrite ~= ([ CMData(cpos+voxelVerts[18], vec2(uvs.x, uvs.y), 0.5), CMData(cpos+voxelVerts[19], vec2(uvs.z, uvs.y), 0.5), CMData(cpos+voxelVerts[20], vec2(uvs.x, uvs.w), 0.5), CMData(cpos+voxelVerts[21], vec2(uvs.x, uvs.w), 0.5), CMData(cpos+voxelVerts[22], vec2(uvs.z, uvs.y), 0.5), CMData(cpos+voxelVerts[23], vec2(uvs.z, uvs.w), 0.5), ]); else bufferToWrite ~= ([ CMData(cpos+voxelVerts[18], vec2(uvs.x, uvs.y), 0.5), CMData(cpos+voxelVerts[19], vec2(uvs.z, uvs.y), 0.5), CMData(cpos+voxelVerts[20], vec2(uvs.x, uvs.w), 0.5), CMData(cpos+voxelVerts[21], vec2(uvs.x, uvs.w), 0.5), CMData(cpos+voxelVerts[22], vec2(uvs.z, uvs.y), 0.5), CMData(cpos+voxelVerts[23], vec2(uvs.z, uvs.w), 0.5), ]); } // Front cap if (blockFreeFront) { vec4 uvs = fcAtlasGet(block.textures[0]); if (blockTr) tbufferToWrite ~= ([ CMData(cpos+voxelVerts[12], vec2(uvs.x, uvs.y), 0.5), CMData(cpos+voxelVerts[13], vec2(uvs.x, uvs.w), 0.5), CMData(cpos+voxelVerts[14], vec2(uvs.z, uvs.y), 0.5), CMData(cpos+voxelVerts[15], vec2(uvs.z, uvs.y), 0.5), CMData(cpos+voxelVerts[16], vec2(uvs.x, uvs.w), 0.5), CMData(cpos+voxelVerts[17], vec2(uvs.z, uvs.w), 0.5), ]); else bufferToWrite ~= ([ CMData(cpos+voxelVerts[12], vec2(uvs.x, uvs.y), 0.5), CMData(cpos+voxelVerts[13], vec2(uvs.x, uvs.w), 0.5), CMData(cpos+voxelVerts[14], vec2(uvs.z, uvs.y), 0.5), CMData(cpos+voxelVerts[15], vec2(uvs.z, uvs.y), 0.5), CMData(cpos+voxelVerts[16], vec2(uvs.x, uvs.w), 0.5), CMData(cpos+voxelVerts[17], vec2(uvs.z, uvs.w), 0.5), ]); } // Right cap if (blockFreeRight) { vec4 uvs = fcAtlasGet(block.textures[5]); if (blockTr) tbufferToWrite ~= ([ CMData(cpos+voxelVerts[24], vec2(uvs.x, uvs.y), 0.5), CMData(cpos+voxelVerts[25], vec2(uvs.z, uvs.y), 0.5), CMData(cpos+voxelVerts[26], vec2(uvs.x, uvs.w), 0.5), CMData(cpos+voxelVerts[27], vec2(uvs.x, uvs.w), 0.5), CMData(cpos+voxelVerts[28], vec2(uvs.z, uvs.y), 0.5), CMData(cpos+voxelVerts[29], vec2(uvs.z, uvs.w), 0.5), ]); else bufferToWrite ~= ([ CMData(cpos+voxelVerts[24], vec2(uvs.x, uvs.y), 0.5), CMData(cpos+voxelVerts[25], vec2(uvs.z, uvs.y), 0.5), CMData(cpos+voxelVerts[26], vec2(uvs.x, uvs.w), 0.5), CMData(cpos+voxelVerts[27], vec2(uvs.x, uvs.w), 0.5), CMData(cpos+voxelVerts[28], vec2(uvs.z, uvs.y), 0.5), CMData(cpos+voxelVerts[29], vec2(uvs.z, uvs.w), 0.5), ]); } // Left cap if (blockFreeLeft) { vec4 uvs = fcAtlasGet(block.textures[4]); if (blockTr) tbufferToWrite ~= ([ CMData(cpos+voxelVerts[30], vec2(uvs.x, uvs.y), 0.5), CMData(cpos+voxelVerts[31], vec2(uvs.x, uvs.w), 0.5), CMData(cpos+voxelVerts[32], vec2(uvs.z, uvs.y), 0.5), CMData(cpos+voxelVerts[33], vec2(uvs.z, uvs.y), 0.5), CMData(cpos+voxelVerts[34], vec2(uvs.x, uvs.w), 0.5), CMData(cpos+voxelVerts[35], vec2(uvs.z, uvs.w), 0.5), ]); else bufferToWrite ~= ([ CMData(cpos+voxelVerts[30], vec2(uvs.x, uvs.y), 0.5), CMData(cpos+voxelVerts[31], vec2(uvs.x, uvs.w), 0.5), CMData(cpos+voxelVerts[32], vec2(uvs.z, uvs.y), 0.5), CMData(cpos+voxelVerts[33], vec2(uvs.z, uvs.y), 0.5), CMData(cpos+voxelVerts[34], vec2(uvs.x, uvs.w), 0.5), CMData(cpos+voxelVerts[35], vec2(uvs.z, uvs.w), 0.5), ]); } } } } return [bufferToWrite, tbufferToWrite]; } __gshared bool shouldRun; void meshGenThreadFunc() { import std.stdio : writeln; import core.memory : GC; setMaxMailboxSize(thisTid, 0, OnCrowding.ignore); auto owner = ownerTid; MeshGenTask*[] taskQueue; while (atomicLoad(shouldRun)) { try { while (atomicLoad(shouldRun) && receiveTimeout(100.msecs, (immutable(MeshGenTask)* task) { taskQueue ~= cast(MeshGenTask*)task; })) { } if (taskQueue.length > 0) { // import std.math : cmp; // taskQueue.sort!((a, b) => cmp(a.distanceToPlayer(), b.distanceToPlayer()) < 0); import std.parallelism : parallel; // TODO: This is using a lot of memory, make it not do that //for (size_t i; i < taskQueue.length; i++) { foreach(ctask; parallel(taskQueue)) { if (!atomicLoad(shouldRun)) continue; // Generate a mesh for the task auto mesh = generateMesh(ctask.data); // Send it back to our main thread so that it can be sent on to OpenGL send( owner, cast(immutable(MeshGenResponse)*)new MeshGenResponse( ctask.buffer, ctask.trbuffer, cast(immutable(CMData[]))mesh[0], cast(immutable(CMData[]))mesh[1] ) ); } taskQueue.length = 0; } } catch(Exception ex) { import std.stdio : writeln; writeln("[ERROR] ChunkMesher: ", ex.msg); } } } Tid meshGeneratorThread; public static: void start() { if (!atomicLoad(shouldRun)) { atomicStore(shouldRun, true); setMaxMailboxSize(thisTid(), 0, OnCrowding.ignore); meshGeneratorThread = spawn({ MeshGenerator.meshGenThreadFunc(); }); } } void stop() { atomicStore(shouldRun, false); } size_t totalCounter; void update() { size_t counter = 0; enum COUNTER_MAX_FRAME = 1024; while(counter < COUNTER_MAX_FRAME && receiveTimeout(-1.msecs, (immutable(MeshGenResponse)* response) { // Return if buffer is null if (response.buffer is null) return; (cast(ChunkVertexBuffer)*response.buffer).upload(response.data); (cast(ChunkVertexBuffer)*response.trbuffer).upload(response.trdata); })) counter++; } /** enqueues the specificed mesh generator task */ void enqueue(immutable(MeshGenTask)* task, bool highPriority = false) { if (task.buffer is null) return; // Can't enqueue a dead buffer if (highPriority) prioritySend(meshGeneratorThread, task); else send(meshGeneratorThread, task); } }
D
/** * Utility subroutines * * Only used for DMD * * Compiler implementation of the * $(LINK2 https://www.dlang.org, D programming language). * * Copyright: Copyright (C) 1984-1998 by Symantec * Copyright (C) 2000-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/backend/util2.d, backend/util2.d) */ module dmd.backend.util2; import core.stdc.stdio; import core.stdc.stdlib; import core.stdc.string; import dmd.backend.cc; import dmd.backend.cdef; import dmd.backend.global; import dmd.backend.mem; extern (C++): nothrow: @safe: void *ph_malloc(size_t nbytes); void *ph_calloc(size_t nbytes); void ph_free(void *p); void *ph_realloc(void *p , size_t nbytes); void file_progress() { } /**************************** * Clean up and exit program. */ void err_exit() { util_exit(EXIT_FAILURE); } /******************************** * Clean up and exit program. */ void err_break() { util_exit(255); } /**************************** * Clean up and exit program. */ @trusted void util_exit(int exitcode) { exit(exitcode); /* terminate abnormally */ } version (CRuntime_DigitalMars) { extern (C) extern __gshared int controlc_saw; /******************************** * Control C interrupts go here. */ @trusted private extern (C) void controlc_handler() { //printf("saw controlc\n"); controlc_saw = 1; } /********************************* * Trap control C interrupts. */ version (MARS) { } else { extern (C) { void controlc_open(); void controlc_close(); alias _controlc_handler_t = void function(); extern __gshared _controlc_handler_t _controlc_handler; void _STI_controlc() { //printf("_STI_controlc()\n"); _controlc_handler = &controlc_handler; controlc_open(); /* trap control C */ } void _STD_controlc() { //printf("_STD_controlc()\n"); controlc_close(); } } } } /*********************************** * Send progress report. */ void util_progress() { version (MARS) { } else { version (CRuntime_DigitalMars) { if (controlc_saw) err_break(); } } } void util_progress(int linnum) { version (MARS) { } else { version (CRuntime_DigitalMars) { if (controlc_saw) err_break(); } } } /********************************** * Binary string search. * Input: * p . string of characters * tab array of pointers to strings * n = number of pointers in the array * Returns: * index (0..n-1) into tab[] if we found a string match * else -1 */ version (X86) version (CRuntime_DigitalMars) version = X86asm; @trusted int binary(const(char)* p, const(char)* *table,int high) { version (X86asm) { alias len = high; // reuse parameter storage asm nothrow { // First find the length of the identifier. xor EAX,EAX ; // Scan for a 0. mov EDI,p ; mov ECX,EAX ; dec ECX ; // Longest possible string. repne ; scasb ; mov EDX,high ; // EDX = high not ECX ; // length of the id including '/0', stays in ECX dec EDX ; // high-- js short Lnotfound ; dec EAX ; // EAX = -1, so that eventually EBX = low (0) mov len,ECX ; even ; L4D: lea EBX,[EAX + 1] ; // low = mid + 1 cmp EBX,EDX ; jg Lnotfound ; even ; L15: lea EAX,[EBX + EDX] ; // EAX = low + high // Do the string compare. mov EDI,table ; sar EAX,1 ; // mid = (low + high) >> 1 mov ESI,p ; mov EDI,[4*EAX+EDI] ; // Load table[mid] mov ECX,len ; // length of id repe ; cmpsb ; je short L63 ; // return mid if equal jns short L4D ; // if (cond < 0) lea EDX,-1[EAX] ; // high = mid - 1 cmp EBX,EDX ; jle L15 ; Lnotfound: mov EAX,-1 ; // Return -1. even ; L63: ; } } else { int low = 0; char cp = *p; high--; p++; while (low <= high) { int mid = low + ((high - low) >> 1); int cond = table[mid][0] - cp; if (cond == 0) cond = strcmp(table[mid] + 1,p); if (cond > 0) high = mid - 1; else if (cond < 0) low = mid + 1; else return mid; /* match index */ } return -1; } } // search table[0 .. high] for p[0 .. len] (where p.length not necessairily equal to len) @trusted int binary(const(char)* p, size_t len, const(char)** table, int high) { int low = 0; char cp = *p; high--; p++; len--; while (low <= high) { int mid = low + ((high - low) >> 1); int cond = table[mid][0] - cp; if (cond == 0) { cond = strncmp(table[mid] + 1, p, len); if (cond == 0) cond = table[mid][len+1]; // same as: if (table[mid][len+1] != '\0') cond = 1; } if (cond > 0) high = mid - 1; else if (cond < 0) low = mid + 1; else return mid; /* match index */ } return -1; } /********************** * If c is a power of 2, return that power else -1. */ int ispow2(ulong c) { int i; if (c == 0 || (c & (c - 1))) i = -1; else for (i = 0; c >>= 1; i++) { } return i; } /*************************** */ enum UTIL_PH = true; version (MEM_DEBUG) enum MEM_DEBUG = false; //true; else enum MEM_DEBUG = false; version (Windows) { void *util_malloc(uint n,uint size) { static if (MEM_DEBUG) { void *p; p = mem_malloc(n * size); //dbg_printf("util_calloc(%d) = %p\n",n * size,p); return p; } else static if (UTIL_PH) { return ph_malloc(n * size); } else { size_t nbytes = cast(size_t)n * cast(size_t)size; void *p = malloc(nbytes); if (!p && nbytes) err_nomem(); return p; } } } /*************************** */ version (Windows) { void *util_calloc(uint n,uint size) { static if (MEM_DEBUG) { void *p; p = mem_calloc(n * size); //dbg_printf("util_calloc(%d) = %p\n",n * size,p); return p; } else static if (UTIL_PH) { return ph_calloc(n * size); } else { size_t nbytes = cast(size_t) n * cast(size_t) size; void *p = calloc(n,size); if (!p && nbytes) err_nomem(); return p; } } } /*************************** */ version (Windows) { void util_free(void *p) { //dbg_printf("util_free(%p)\n",p); static if (MEM_DEBUG) { mem_free(p); } else static if (UTIL_PH) { ph_free(p); } else { free(p); } } } /*************************** */ version (Windows) { void *util_realloc(void *oldp,size_t n,size_t size) { static if (MEM_DEBUG) { //dbg_printf("util_realloc(%p,%d)\n",oldp,n * size); return mem_realloc(oldp,n * size); } else static if (UTIL_PH) { return ph_realloc(oldp,n * size); } else { const nbytes = n * size; void *p = realloc(oldp,nbytes); if (!p && nbytes) err_nomem(); return p; } } } /***************************** */ void *mem_malloc2(uint size) { return mem_malloc(size); }
D
/home/carl/embedded system/e7020e_2019/target/thumbv7em-none-eabihf/debug/deps/libnb-b6de6b45a406c41f.rlib: /home/carl/.cargo/registry/src/github.com-1ecc6299db9ec823/nb-0.1.1/src/lib.rs /home/carl/embedded system/e7020e_2019/target/thumbv7em-none-eabihf/debug/deps/nb-b6de6b45a406c41f.d: /home/carl/.cargo/registry/src/github.com-1ecc6299db9ec823/nb-0.1.1/src/lib.rs /home/carl/.cargo/registry/src/github.com-1ecc6299db9ec823/nb-0.1.1/src/lib.rs:
D
/Users/leonardo15043/Documents/GitHub/AddDataTableView/build/AddDataTableView.build/Debug-iphonesimulator/AddDataTableView.build/Objects-normal/x86_64/AppDelegate.o : /Users/leonardo15043/Documents/GitHub/AddDataTableView/AddDataTableView/AppDelegate.swift /Users/leonardo15043/Documents/GitHub/AddDataTableView/AddDataTableView/CarListViewController.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 /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/leonardo15043/Documents/GitHub/AddDataTableView/build/AddDataTableView.build/Debug-iphonesimulator/AddDataTableView.build/Objects-normal/x86_64/AppDelegate~partial.swiftmodule : /Users/leonardo15043/Documents/GitHub/AddDataTableView/AddDataTableView/AppDelegate.swift /Users/leonardo15043/Documents/GitHub/AddDataTableView/AddDataTableView/CarListViewController.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 /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/leonardo15043/Documents/GitHub/AddDataTableView/build/AddDataTableView.build/Debug-iphonesimulator/AddDataTableView.build/Objects-normal/x86_64/AppDelegate~partial.swiftdoc : /Users/leonardo15043/Documents/GitHub/AddDataTableView/AddDataTableView/AppDelegate.swift /Users/leonardo15043/Documents/GitHub/AddDataTableView/AddDataTableView/CarListViewController.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 /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
/* Copyright (c) 2015-2023 Timur Gafarov 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. */ /** * Dynamic (expandable) array with random access * * Copyright: Timur Gafarov 2015-2023. * License: $(LINK2 boost.org/LICENSE_1_0.txt, Boost License 1.0). * Authors: Timur Gafarov, Roman Vlasov, Andrey Penechko, Eugene Wissner, Roman Chistokhodov, aferust, ijet */ module dlib.container.array; import std.traits; import dlib.core.memory; /** * GC-free dynamic array implementation. * Very efficient for small-sized arrays. */ struct Array(T, size_t chunkSize = 32) { private: T[chunkSize] staticStorage; T[] dynamicStorage; uint numChunks = 0; uint pos = 0; /** * Get pointer to stored data */ private T* storage() nothrow { if (numChunks == 0) return staticStorage.ptr; else return dynamicStorage.ptr; } private const(T)* readOnlyStorage() const nothrow { if (numChunks == 0) return staticStorage.ptr; else return dynamicStorage.ptr; } private void addChunk() { if (numChunks == 0) { dynamicStorage = New!(T[])(chunkSize); } else { reallocateArray( dynamicStorage, dynamicStorage.length + chunkSize); } numChunks++; } /// unittest { Array!int arr; scope(exit) arr.free(); assert(arr.length == 0); arr.addChunk(); assert(arr.length == 0); } public: /** * Returns true if the array uses dynamic memory. */ @property bool isDynamic() const { return dynamicStorage.length > 0; } /** * Preallocate memory without resizing. */ void reserve(const(size_t) amount) { if (amount > pos && amount > staticStorage.length) { if (numChunks == 0) { dynamicStorage = New!(T[])(amount); foreach(i, v; staticStorage) dynamicStorage[i] = v; } else { reallocateArray(dynamicStorage, amount); } numChunks = cast(uint)(amount / 32 + amount % 32); } } /// unittest { Array!int arr; arr.reserve(100); assert(arr.length == 0); assert(arr.dynamicStorage.length == 100); } /** * Resize array and initialize newly added elements with initValue. */ void resize(const(size_t) newLen, T initValue) { if (newLen > pos) { reserve(newLen); for(size_t i = pos; i < newLen; i++) { storage[i] = initValue; } } pos = cast(uint)newLen; } /// unittest { Array!int arr; arr.resize(100, 1); assert(arr.length == 100); assert(arr[50] == 1); } /** * Shift contents of array to the right. * It inreases the size of array by 1. * The first element becomes default initialized. */ void shiftRight() { insertBack(T.init); for(uint i = pos-1; i > 0; i--) { storage[i] = storage[i-1]; } } /// unittest { Array!int arr; scope(exit) arr.free(); arr.shiftRight(); assert(arr.length == 1); assert(arr[0] == int.init); arr[0] = 1; arr.insertBack([2,3]); arr.shiftRight(); assert(arr.length == 4); assert(arr[0] == 1); assert(arr[1] == 1); assert(arr[2] == 2); assert(arr[3] == 3); } /** * Shift contents of array to the left by n positions. * Does not change the size of array. * n of last elements becomes default initialized. */ void shiftLeft(const(uint) n) { for(uint i = 0; i < pos; i++) { if (n + i < pos) storage[i] = storage[n + i]; else storage[i] = T.init; } } /// unittest { Array!int arr; scope(exit) arr.free(); arr.shiftLeft(1); assert(arr.length == 0); arr.insertBack([1,2,3,4,5]); arr.shiftLeft(2); assert(arr.length == 5); assert(arr[0] == 3); assert(arr[1] == 4); assert(arr[2] == 5); assert(arr[3] == int.init); assert(arr[4] == int.init); } /** * Append single element c to the end. */ void insertBack(T c) { if (numChunks == 0) { staticStorage[pos] = c; pos++; if (pos == chunkSize) { addChunk(); foreach(i, ref v; dynamicStorage) v = staticStorage[i]; } } else { if (pos == dynamicStorage.length) addChunk(); dynamicStorage[pos] = c; pos++; } } /// unittest { Array!int arr; scope(exit) arr.free(); foreach(i; 0..16) { arr.insertBack(i); } assert(arr.length == 16); arr.insertBack(16); assert(arr.length == 17); assert(arr[16] == 16); } /** * Append element to the start. */ void insertFront(T c) { shiftRight(); storage[0] = c; } /// unittest { Array!int arr; scope(exit) arr.free(); arr.insertFront(1); arr.insertBack(2); arr.insertFront(0); assert(arr.data == [0,1,2]); } /** * Append all elements of slice s to the end. */ void insertBack(const(T)[] s) { foreach(c; s) insertBack(cast(T)c); } /// unittest { Array!int arr; scope(exit) arr.free(); arr.insertBack([1,2,3,4]); assert(arr.data == [1,2,3,4]); arr.insertBack([5,6,7,8]); assert(arr.data == [1,2,3,4,5,6,7,8]); } /** * Append all elements of slice s to the start. */ void insertFront(const(T)[] s) { foreach_reverse(c; s) insertFront(cast(T)c); } /// unittest { Array!int arr; scope(exit) arr.free(); arr.insertFront([5,6,7,8]); assert(arr.data == [5,6,7,8]); arr.insertFront([1,2,3,4]); assert(arr.data == [1,2,3,4,5,6,7,8]); } /** * Same as insertBack, but in operator form. */ auto opOpAssign(string op)(T c) if (op == "~") { insertBack(c); return this; } /// unittest { Array!int arr; scope(exit) arr.free(); arr ~= 1; arr ~= 2; assert(arr.data == [1,2]); } /** * Same as insertBack, but in operator form. */ auto opOpAssign(string op)(const(T)[] s) if (op == "~") { insertBack(s); return this; } /// unittest { Array!int arr; scope(exit) arr.free(); arr ~= [1,2,3]; assert(arr.data == [1,2,3]); } /** * Remove n of elements from the end. * Returns: number of removed elements. */ uint removeBack(const(uint) n) { if (pos == n) { pos = 0; return n; } else if (pos >= n) { pos -= n; return n; } else { uint res = pos; pos = 0; return res; } } /// unittest { Array!int arr; scope(exit) arr.free(); arr.insertBack([1,2,3]); assert(arr.removeBack(3) == 3); assert(arr.length == 0); arr.insertBack([1,2,3,4]); assert(arr.removeBack(2) == 2); assert(arr.data == [1,2]); assert(arr.removeBack(3) == 2); assert(arr.length == 0); } /** * Remove n of elements from the start. * Returns: number of removed elements. */ uint removeFront(const(uint) n) { if (pos == n) { pos = 0; return n; } else if (pos > n) { shiftLeft(n); pos -= n; return n; } else { uint res = pos; pos = 0; return res; } } /// unittest { Array!int arr; scope(exit) arr.free(); arr.insertBack([1,2,3]); assert(arr.removeFront(3) == 3); arr.insertBack([1,2,3,4]); assert(arr.removeFront(2) == 2); assert(arr.data == [3,4]); assert(arr.removeFront(3) == 2); assert(arr.length == 0); } /** * Inserts an element by a given index * (resizing an array and shifting elements). */ void insertKey(const(size_t) i, T v) { if (i < pos) { T* s = storage(); insertBack(T.init); for (size_t p = pos-1; p > i; p--) { s[p] = s[p-1]; } s[i] = v; } } unittest { Array!int arr; scope(exit) arr.free(); arr.insertBack([1, 4, 5]); arr.insertKey(1, 7); assert(arr.length == 4); assert(arr.data == [1, 7, 4, 5]); } /** * Removes an element by a given index. */ void removeKey(const(size_t) i) { if (i < pos) { T* s = storage(); for (size_t p = i+1; p <= pos; p++) { s[p-1] = s[p]; } pos--; } } unittest { Array!int arr; scope(exit) arr.free(); arr.insertBack([1, 4, 5]); arr.removeKey(1); assert(arr.length == 2); assert(arr.data == [1, 5]); } alias insertAt = insertKey; alias removeAt = removeKey; /** * If obj is in array, remove its first occurence and return true. * Otherwise do nothing and return false. */ bool removeFirst(T obj) { size_t index; bool found = false; for (size_t i = 0; i < data.length; i++) { T o = data[i]; static if (isArray!T) { if (o[] == obj[]) { index = i; found = true; break; } } else { if (o is obj) { index = i; found = true; break; } } } if (found) { removeKey(index); return true; } return false; } // For backward compatibility alias append = insertBack; alias appendLeft = insertFront; alias remove = removeBack; alias removeLeft = removeFront; /** * Get number of elements in array. */ size_t length() const nothrow { return pos; } alias opDollar = length; /// unittest { Array!int arr; scope(exit) arr.free(); arr.insertBack([1,2,3]); assert(arr.length == 3); } /** * Get slice of data */ T[] data() nothrow { return storage[0..pos]; } const(T)[] readOnlyData() const nothrow { return readOnlyStorage[0..pos]; } /// unittest { Array!(int,4) arr; scope(exit) arr.free(); foreach(i; 0..6) { arr.insertBack(i); } assert(arr.data == [0,1,2,3,4,5]); } /** * Access element by index. */ T opIndex(const(size_t) index) { return data[index]; } /** * Access by slice. */ T[] opSlice(const(size_t) start, const(size_t) end) { return data[start..end]; } /** * Set element t for index. */ T opIndexAssign(T t, const(size_t) index) { data[index] = t; return t; } /** * Iterating over array via foreach. */ int opApply(scope int delegate(size_t i, ref T) dg) { int result = 0; foreach(i, ref v; data) { result = dg(i, v); if (result) break; } return result; } /** * Iterating over array via foreach_reverse. */ int opApplyReverse(scope int delegate(size_t i, ref T) dg) { int result = 0; for(size_t i = length; i-- > 0; ) { result = dg(i, data[i]); if (result) break; } return result; } /// unittest { Array!(int,4) arr; scope(exit) arr.free(); int[4] values; arr.insertBack([1,2,3,4]); foreach(i, ref val; arr) { values[i] = val; if(values[i] == 4) { break; } } assert(values[] == arr.data); } /** * Iterating over array via foreach. */ int opApply(scope int delegate(ref T) dg) { int result = 0; foreach(i, ref v; data) { result = dg(v); if (result) break; } return 0; } /** * Iterating over array via foreach_reverse. */ int opApplyReverse(scope int delegate(ref T) dg) { int result = 0; for(size_t i = length; i-- > 0; ) { result = dg(data[i]); if (result) break; } return result; } /// unittest { Array!(int,4) arr; scope(exit) arr.free(); int[] values; arr.insertBack([1,2,3,4]); foreach(ref val; arr) { values ~= val; } assert(values[] == arr.data); } /** * Free dynamically allocated memory used by array. */ void free() { if (dynamicStorage.length) Delete(dynamicStorage); numChunks = 0; pos = 0; } } void reallocateArray(T)(ref T[] buffer, const(size_t) len) { T[] buffer2 = New!(T[])(len); for(uint i = 0; i < buffer2.length; i++) if (i < buffer.length) buffer2[i] = buffer[i]; Delete(buffer); buffer = buffer2; } /// unittest { auto arr = New!(int[])(3); arr[0] = 1; arr[1] = 2; arr[2] = 3; reallocateArray(arr, 2); assert(arr.length == 2); assert(arr[0] == 1); assert(arr[1] == 2); reallocateArray(arr, 4); assert(arr.length == 4); assert(arr[0] == 1); assert(arr[1] == 2); }
D
module distributed.DistributedHelpers; import misc.BitstreamDestination; import serialisation.BitstreamWriter; ubyte[] composeMessageWithLengthPrefix(BitstreamDestination payloadBitstream, out bool successChained) { BitstreamDestination bitstreamDestinationForMessage = new BitstreamDestination(); BitstreamWriter!BitstreamDestination bitstreamWriterForMessage = new BitstreamWriter!BitstreamDestination(bitstreamDestinationForMessage); successChained = true; bitstreamWriterForMessage.addArray__16(payloadBitstream.dataAsUbyte, successChained); ubyte[] message = bitstreamDestinationForMessage.dataAsUbyte; return message; }
D
import std.stdio; import std.random; import std.conv; void main() { int x_dimension; int y_dimension; write(">> "); readf(" %s", &x_dimension); write(">> "); readf(" %s", &y_dimension); writeln(); bool[][] puzzle_board; for(int x = 0; x < x_dimension; ++x) { bool[] puzzle_line; for(int y = 0; y < y_dimension; ++y) { auto random_num = uniform(0, 720); puzzle_line ~= (random_num % 2 == 0); } puzzle_board ~= puzzle_line; } int[][] x_sequences; int max_x_hints = 0; for(int x = 0; x < x_dimension; ++x) { int[] slice_sequences; int single_sequence = 0; bool should_add_end = true; for(int y = 0; y < y_dimension; ++y) { if(puzzle_board[x][y] == true) { ++single_sequence; should_add_end = true; } else { if(single_sequence > 0) { slice_sequences ~= single_sequence; single_sequence = 0; should_add_end = false; } } } if(should_add_end) { slice_sequences ~= single_sequence; } if(to!int(slice_sequences.length) > max_x_hints) { max_x_hints = to!int(slice_sequences.length); } x_sequences ~= slice_sequences; } int[][] y_sequences; int max_y_hints; for(int y = 0; y < y_dimension; ++y) { int[] slice_sequences; int single_sequence = 0; bool should_add_end = true; for(int x = 0; x < x_dimension; x++) { if(puzzle_board[x][y] == true) { ++single_sequence; should_add_end = true; } else { if(single_sequence > 0) { slice_sequences ~= single_sequence; single_sequence = 0; should_add_end = false; } } } if(should_add_end) { slice_sequences ~= single_sequence; } if(to!int(slice_sequences.length) > max_y_hints) { max_y_hints = to!int(slice_sequences.length); } y_sequences ~= slice_sequences; } writeln(); writeln("******"); for(int x = 0; x < x_dimension; ++x) { writeln(puzzle_board[x]); } write(" "); for(int y = max_y_hints; y >= 0; --y) { for(int x = 0; x < max_x_hints; ++x) { write(" "); } write(" "); for(int col = 0; col < y_dimension; ++col) { if(to!int(y_sequences[col].length) > y) { write(y_sequences[col][(to!int(y_sequences[col].length) - 1) - y]); } else { if(y < max_y_hints) { write(" "); } } write(" "); } writeln(); } writeln(); for(int row = 0; row < x_dimension; ++row) { for(int x = max_x_hints; x >= 0; --x) { if(x < max_x_hints) { write(" "); } if(to!int(x_sequences[row].length) > x) { write(x_sequences[row][(to!int(x_sequences[row].length) - 1) - x]); } else { if(x < max_x_hints) { write(" "); } } } for(int y = 0; y < y_dimension; ++y) { write(" "); write(puzzle_board[row][y] ? "o" : "x"); } writeln(); writeln(); } }
D
/home/mailboxhead/Documents/Practice/rust/itemRestAPI/target/rls/debug/deps/rand_chacha-a0b3ded2a365c8b6.rmeta: /home/mailboxhead/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_chacha-0.1.1/src/lib.rs /home/mailboxhead/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_chacha-0.1.1/src/chacha.rs /home/mailboxhead/Documents/Practice/rust/itemRestAPI/target/rls/debug/deps/rand_chacha-a0b3ded2a365c8b6.d: /home/mailboxhead/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_chacha-0.1.1/src/lib.rs /home/mailboxhead/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_chacha-0.1.1/src/chacha.rs /home/mailboxhead/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_chacha-0.1.1/src/lib.rs: /home/mailboxhead/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_chacha-0.1.1/src/chacha.rs:
D
module UnrealScript.UnrealEd.FindAssetReferencersCommandlet; import ScriptClasses; import UnrealScript.Helpers; import UnrealScript.Core.Commandlet; extern(C++) interface FindAssetReferencersCommandlet : Commandlet { public extern(D): private static __gshared ScriptClass mStaticClass; @property final static ScriptClass StaticClass() { mixin(MGSCC("Class UnrealEd.FindAssetReferencersCommandlet")); } private static __gshared FindAssetReferencersCommandlet mDefaultProperties; @property final static FindAssetReferencersCommandlet DefaultProperties() { mixin(MGDPC("FindAssetReferencersCommandlet", "FindAssetReferencersCommandlet UnrealEd.Default__FindAssetReferencersCommandlet")); } }
D
module android.java.android.net.IpPrefix; public import android.java.android.net.IpPrefix_d_interface; import arsd.jni : ImportExportImpl; mixin ImportExportImpl!IpPrefix; import import0 = android.java.java.net.InetAddress; import import2 = android.java.java.lang.Class;
D
module reactived.observable.operators.utility; import std.conv; import std.datetime; import std.functional; import std.traits; import core.thread; import reactived.observable; import reactived.observer; import reactived.disposable; import reactived.scheduler; import disposable = reactived.disposable; /** Forwards calls on a subscriber to the given observer. */ Observable!T doOnEach(T)(Observable!T observable, Observer!T observer) pure @safe nothrow { Disposable subscribe(Observer!T subscriber) { void onNextImpl(T value) { observer.onNext(value); subscriber.onNext(value); } void onCompletedImpl() { observer.onCompleted(); subscriber.onCompleted(); } void onErrorImpl(Throwable error) { observer.onError(error); subscriber.onError(error); } return observable.subscribe(&onNextImpl, &onCompletedImpl, &onErrorImpl); } return create(&subscribe); } /** Forwards calls on a subscriber to the given `onNext`, `onCompleted`, and `onError` handlers. */ Observable!T doOnEach(T)(Observable!T observable, void delegate(T) onNext, void delegate() onCompleted, void delegate(Throwable) onError) pure @safe nothrow { Disposable subscribe(Observer!T observer) { void onNextImpl(T value) { onNext(value); observer.onNext(value); } void onCompletedImpl() { onCompleted(); observer.onCompleted(); } void onErrorImpl(Throwable error) { onError(error); observer.onError(error); } return observable.subscribe(&onNextImpl, &onCompletedImpl, &onErrorImpl); } return create(&subscribe); } /// unittest { import reactived.util : dump; int count; bool completed; bool threw; range(1, 10).doOnEach((int) { ++count; }, () { completed = true; }, (Throwable) { threw = true; }).dump("doOnEach()"); assert(count == 10); assert(completed); assert(!threw); error!(int)(new Exception("Failed")).doOnError!int((Throwable) { threw = true; }).dump("error"); assert(threw); } /** Forwards calls on a subscriber to the given `onNext` handler. */ Observable!T doOnNext(T)(Observable!T observable, void delegate(T) onNext) pure @safe nothrow { return doOnEach(observable, onNext, delegate() { }, delegate(Throwable) { }); } /** Forwards calls on a subscriber to the given `onCompleted` handler. */ Observable!T doOnCompleted(T)(Observable!T observable, void delegate() onCompleted) pure @safe nothrow { return doOnEach(observable, delegate(T) { }, onCompleted, delegate(Throwable) { }); } /** Forwards calls on a subscriber to the given `onError` handler. */ Observable!T doOnError(T)(Observable!T observable, void delegate(Throwable) onError) pure @safe nothrow { return doOnEach!T(observable, delegate(T) { }, delegate() { }, onError); } /** Forwards subscription events to the given `onSubscribe` and `onUnsubscribe` handlers. */ Observable!T doOnSubscription(T)(Observable!T observable, void delegate(Observer!T) onSubscribe, void delegate(Observer!T) @nogc onUnsubscribe) pure @safe nothrow { Disposable subscribe(Observer!T observer) { onSubscribe(observer); return new CompositeDisposable(createDisposable(() @nogc{ onUnsubscribe(observer); }), observable.subscribe(observer)); } return create(&subscribe); } /// unittest { import reactived.util : dump; int subscribes; int unsubscribes; Observable!int o = just(1).doOnSubscription((Observer!int) { ++subscribes; }, (Observer!int) { ++unsubscribes; }); Disposable sub1 = o.dump("doOnSubscription1"); assert(subscribes == 1); assert(unsubscribes == 0); sub1.dispose(); assert(unsubscribes == 1); Disposable sub2 = o.dump("doOnSubscription2"); assert(subscribes == 2); assert(unsubscribes == 1); sub2.dispose(); assert(subscribes == unsubscribes); } /** Forwards subscription events to the given `onSubscribe` handler. */ Observable!T doOnSubscribe(T)(Observable!T observable, void delegate(Observer!T) onSubscribe) { return doOnSubscription(observable, onSubscribe, (Observer!T) { }); } /** Forwards unsubscription events to the given `onUnsubscribe` handler. */ Observable!T doOnUnsubscribe(T)(Observable!T observable, void delegate(Observer!T) onUnsubscribe) { return doOnSubscription(observable, (Observer!T) { }, onUnsubscribe); } Observable!(Notification!T) materialize(T)(Observable!T source) @safe pure nothrow { Disposable subscribe(Observer!(Notification!T) observer) { void onNext(T value) { observer.onNext(new OnNextNotification!T(value)); } void onCompleted() { observer.onNext(new OnCompletedNotification!T()); observer.onCompleted(); } void onError(Throwable error) { observer.onNext(new OnErrorNotification!T(error)); observer.onError(error); } return source.subscribe(&onNext, &onCompleted, &onError); } return create(&subscribe); } Observable!T dematerialize(T)(Observable!(Notification!T) source) { Disposable subscribe(Observer!T observer) { void onNext(Notification!T value) { switch (value.kind) with (NotificationKind) { case onNext: observer.onNext(value.value); break; case onCompleted: observer.onCompleted(); break; case onError: observer.onError(value.error); break; default: assert(0); } } return source.subscribe(&onNext, { }, (Throwable) { }); } return create(&subscribe); } unittest { // dfmt off range(0, 10).materialize() .dematerialize() .sequenceEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) .subscribe(x => assert(x)); // dfmt on } Observable!(Timestamp!T) timestamp(T)(Observable!T source) { return source.map!(x => Timestamp!T(Clock.currTime(), x)); } template delay(alias fun) { Observable!T delay(T)(Observable!T source) { // dfmt off return source.materialize() .doOnNext((Notification!T x) { Thread.sleep(unaryFun!fun(x.value)); }) .dematerialize(); // dfmt on } } Observable!T delay(T)(Observable!T source, Duration delay) { return source.delay!((T) => delay); } unittest { import reactived.util : transparentDump; struct Diff { SysTime first, second; int value; } // dfmt off range(0, 10).timestamp() .delay(dur!"msecs"(100)) .transparentDump("delay") .timestamp() .map!(x => Diff(x.value.timestamp, x.timestamp, x.value.value)) .subscribe(x => assert((x.first - x.second).total!"msecs"() <= 150)); // dfmt on } Observable!(TimeInterval!T) timeInterval(T)(Observable!T source) { Disposable subscribe(Observer!(TimeInterval!T) observer) { StopWatch sw = StopWatch(); sw.start(); void onNext(T value) { sw.stop(); observer.onNext(TimeInterval!T(sw.peek().to!Duration(), value)); sw.reset(); sw.start(); } void onCompleted() { sw.stop(); observer.onCompleted(); } void onError(Throwable error) { sw.stop(); observer.onError(error); } return source.subscribe(&onNext, &onCompleted, &onError); } return create(&subscribe); } unittest { import reactived.util : transparentDump; // dfmt off range(0, 10).delay(dur!"msecs"(100)) .timeInterval() .transparentDump("timeInterval") .subscribe(x => assert(x.duration.total!"msecs"() >= 100)); // dfmt on } Observable!T timeout(T)(Observable!T source, Duration duration, lazy Exception exception = new Exception("Timed Out!"), Scheduler scheduler = taskScheduler) pure @safe nothrow { Disposable subscribe(Observer!T observer) { auto window = assignmentDisposable!BooleanDisposable(); void onCompleted() { window.dispose(); observer.onCompleted(); } void onError(Throwable error) { window.dispose(); observer.onError(error); } void runTimeout() { auto disposable = new BooleanDisposable(); window.disposable = disposable; scheduler.run(() { Thread.sleep(duration); if (!disposable.isDisposed) { onError(exception()); } }); } void onNext(T value) { observer.onNext(value); runTimeout(); } runTimeout(); return source.subscribe(&onNext, &onCompleted, &onError); } return create(&subscribe); } unittest { import std.exception : assertThrown, assertNotThrown; // dfmt off assertThrown(just!int(1).delay(dur!"msecs"(200)) .timeout(dur!"msecs"(100)) .wait()); assertNotThrown(just!int(1).timeout(dur!"msecs"(100)) .wait()); // dfmt on } Observable!T using(T)(Disposable delegate() getResource, Observable!T delegate(Disposable) getObservable) { Disposable subscribe(Observer!T observer) { Disposable resource = getResource(); Observable!T x = getObservable(resource); void onCompleted() { resource.dispose(); observer.onCompleted(); } void onError(Throwable error) { resource.dispose(); observer.onError(error); } Disposable subscription = x.subscribe(&observer.onNext, &onCompleted, &onError); return new CompositeDisposable(resource, subscription); } return create(&subscribe); } unittest { import reactived : Subject, sequenceEqual; bool disposed; void dispose() { disposed = true; } // dfmt off using(() => createDisposable(&dispose), (Disposable) => range(0, 3)) .sequenceEqual([0, 1, 2]).subscribe(x => assert(x)); // dfmt on assert(disposed); } Observable!T encapsulate(T)(Observable!T source) { Disposable subscribe(Observer!T observer) { return source.subscribe(observer); } return create(&subscribe); }
D
import d2d; import std.datetime.stopwatch; import std.concurrency : spawn; import gpu; import cpu; shared Chip8 chip; void main() { chip = new shared Chip8(); chip.loadRom("roms/brix.rom"); spawn(&graphicsThread); spawn(&cpuThread); } void graphicsThread() { immutable width = 64 * 30; Display display = new Display(width, width / 2, SDL_WINDOW_SHOWN, 0, "Chip-8 Emulator", null); display.screen = new RenderScreen(display, width / 64, chip); display.run(); } void cpuThread() { StopWatch sw; sw.start(); ulong count60; // do every 16667 useconds ulong count540; // do every 1852 useconds while (true) { if (sw.peek().total!"usecs" > count60 * 16667) { count60++; chip.cycle60hz(); } if (sw.peek().total!"usecs" > count540 * 1852) { count540++; chip.cycle540hz(); } } }
D
/** * Define `enum` declarations and `enum` members. * * Specification: $(LINK2 https://dlang.org/spec/enum.html, Enums) * * Copyright: Copyright (C) 1999-2021 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/denum.d, _denum.d) * Documentation: https://dlang.org/phobos/dmd_denum.html * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/denum.d * References: https://dlang.org/spec/enum.html */ module dmd.denum; import core.stdc.stdio; import dmd.attrib; import dmd.gluelayer; import dmd.declaration; import dmd.dscope; import dmd.dsymbol; import dmd.dsymbolsem; import dmd.expression; import dmd.expressionsem; import dmd.globals; import dmd.id; import dmd.identifier; import dmd.init; import dmd.mtype; import dmd.tokens; import dmd.typesem; import dmd.visitor; /*********************************************************** * AST node for `EnumDeclaration` * https://dlang.org/spec/enum.html#EnumDeclaration */ extern (C++) final class EnumDeclaration : ScopeDsymbol { /* The separate, and distinct, cases are: * 1. enum { ... } * 2. enum : memtype { ... } * 3. enum id { ... } * 4. enum id : memtype { ... } * 5. enum id : memtype; * 6. enum id; */ Type type; // the TypeEnum Type memtype; // type of the members Visibility visibility; Expression maxval; Expression minval; Expression defaultval; // default initializer bool isdeprecated; bool added; int inuse; extern (D) this(const ref Loc loc, Identifier ident, Type memtype) { super(loc, ident); //printf("EnumDeclaration() %s\n", toChars()); type = new TypeEnum(this); this.memtype = memtype; visibility = Visibility(Visibility.Kind.undefined); } override EnumDeclaration syntaxCopy(Dsymbol s) { assert(!s); auto ed = new EnumDeclaration(loc, ident, memtype ? memtype.syntaxCopy() : null); ScopeDsymbol.syntaxCopy(ed); return ed; } override void addMember(Scope* sc, ScopeDsymbol sds) { version (none) { printf("EnumDeclaration::addMember() %s\n", toChars()); for (size_t i = 0; i < members.dim; i++) { EnumMember em = (*members)[i].isEnumMember(); printf(" member %s\n", em.toChars()); } } /* Anonymous enum members get added to enclosing scope. */ ScopeDsymbol scopesym = isAnonymous() ? sds : this; if (!isAnonymous()) { ScopeDsymbol.addMember(sc, sds); if (!symtab) symtab = new DsymbolTable(); } if (members) { for (size_t i = 0; i < members.dim; i++) { EnumMember em = (*members)[i].isEnumMember(); em.ed = this; //printf("add %s to scope %s\n", em.toChars(), scopesym.toChars()); em.addMember(sc, isAnonymous() ? scopesym : this); } } added = true; } override void setScope(Scope* sc) { if (semanticRun > PASS.init) return; ScopeDsymbol.setScope(sc); } override bool oneMember(Dsymbol* ps, Identifier ident) { if (isAnonymous()) return Dsymbol.oneMembers(members, ps, ident); return Dsymbol.oneMember(ps, ident); } override Type getType() { return type; } override const(char)* kind() const { return "enum"; } override Dsymbol search(const ref Loc loc, Identifier ident, int flags = SearchLocalsOnly) { //printf("%s.EnumDeclaration::search('%s')\n", toChars(), ident.toChars()); if (_scope) { // Try one last time to resolve this enum dsymbolSemantic(this, _scope); } if (!isSpecial() && (!members || !symtab || _scope)) { error("is forward referenced when looking for `%s`", ident.toChars()); //*(char*)0=0; return null; } Dsymbol s = ScopeDsymbol.search(loc, ident, flags); return s; } // is Dsymbol deprecated? override bool isDeprecated() const { return isdeprecated; } override Visibility visible() pure nothrow @nogc @safe { return visibility; } /****************************** * Get the value of the .max/.min property as an Expression. * Lazily computes the value and caches it in maxval/minval. * Reports any errors. * Params: * loc = location to use for error messages * id = Id::max or Id::min * Returns: * corresponding value of .max/.min */ Expression getMaxMinValue(const ref Loc loc, Identifier id) { //printf("EnumDeclaration::getMaxValue()\n"); static Expression pvalToResult(Expression e, const ref Loc loc) { if (e.op != TOK.error) { e = e.copy(); e.loc = loc; } return e; } Expression* pval = (id == Id.max) ? &maxval : &minval; Expression errorReturn() { *pval = ErrorExp.get(); return *pval; } if (inuse) { error(loc, "recursive definition of `.%s` property", id.toChars()); return errorReturn(); } if (*pval) return pvalToResult(*pval, loc); if (_scope) dsymbolSemantic(this, _scope); if (errors) return errorReturn(); if (semanticRun == PASS.init || !members) { if (isSpecial()) { /* Allow these special enums to not need a member list */ return memtype.getProperty(_scope, loc, id, 0); } error("is forward referenced looking for `.%s`", id.toChars()); return errorReturn(); } if (!(memtype && memtype.isintegral())) { error(loc, "has no `.%s` property because base type `%s` is not an integral type", id.toChars(), memtype ? memtype.toChars() : ""); return errorReturn(); } bool first = true; for (size_t i = 0; i < members.dim; i++) { EnumMember em = (*members)[i].isEnumMember(); if (!em) continue; if (em.errors) { errors = true; continue; } if (first) { *pval = em.value; first = false; } else { /* In order to work successfully with UDTs, * build expressions to do the comparisons, * and let the semantic analyzer and constant * folder give us the result. */ /* Compute: * if (e > maxval) * maxval = e; */ Expression e = em.value; Expression ec = new CmpExp(id == Id.max ? TOK.greaterThan : TOK.lessThan, em.loc, e, *pval); inuse++; ec = ec.expressionSemantic(em._scope); inuse--; ec = ec.ctfeInterpret(); if (ec.op == TOK.error) { errors = true; continue; } if (ec.toInteger()) *pval = e; } } return errors ? errorReturn() : pvalToResult(*pval, loc); } /**************** * Determine if enum is a special one. * Returns: * `true` if special */ bool isSpecial() const nothrow @nogc { return isSpecialEnumIdent(ident) && memtype; } Expression getDefaultValue(const ref Loc loc) { Expression handleErrors(){ defaultval = ErrorExp.get(); return defaultval; } //printf("EnumDeclaration::getDefaultValue() %p %s\n", this, toChars()); if (defaultval) return defaultval; if (_scope) dsymbolSemantic(this, _scope); if (errors) return handleErrors(); if (semanticRun == PASS.init || !members) { if (isSpecial()) { /* Allow these special enums to not need a member list */ return memtype.defaultInit(loc); } error(loc, "forward reference of `%s.init`", toChars()); return handleErrors(); } foreach (const i; 0 .. members.dim) { EnumMember em = (*members)[i].isEnumMember(); if (em) { defaultval = em.value; return defaultval; } } return handleErrors(); } Type getMemtype(const ref Loc loc) { if (_scope) { /* Enum is forward referenced. We don't need to resolve the whole thing, * just the base type */ if (memtype) { Loc locx = loc.isValid() ? loc : this.loc; memtype = memtype.typeSemantic(locx, _scope); } else { if (!isAnonymous() && members) memtype = Type.tint32; } } if (!memtype) { if (!isAnonymous() && members) memtype = Type.tint32; else { Loc locx = loc.isValid() ? loc : this.loc; error(locx, "is forward referenced looking for base type"); return Type.terror; } } return memtype; } override inout(EnumDeclaration) isEnumDeclaration() inout { return this; } Symbol* sinit; override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * AST node representing a member of an enum. * https://dlang.org/spec/enum.html#EnumMember * https://dlang.org/spec/enum.html#AnonymousEnumMember */ extern (C++) final class EnumMember : VarDeclaration { /* Can take the following forms: * 1. id * 2. id = value * 3. type id = value */ @property ref value() { return (cast(ExpInitializer)_init).exp; } // A cast() is injected to 'value' after dsymbolSemantic(), // but 'origValue' will preserve the original value, // or previous value + 1 if none was specified. Expression origValue; Type origType; EnumDeclaration ed; extern (D) this(const ref Loc loc, Identifier id, Expression value, Type origType) { super(loc, null, id ? id : Id.empty, new ExpInitializer(loc, value)); this.origValue = value; this.origType = origType; } extern(D) this(Loc loc, Identifier id, Expression value, Type memtype, StorageClass stc, UserAttributeDeclaration uad, DeprecatedDeclaration dd) { this(loc, id, value, memtype); storage_class = stc; userAttribDecl = uad; depdecl = dd; } override EnumMember syntaxCopy(Dsymbol s) { assert(!s); return new EnumMember( loc, ident, value ? value.syntaxCopy() : null, origType ? origType.syntaxCopy() : null, storage_class, userAttribDecl ? userAttribDecl.syntaxCopy(s) : null, depdecl ? depdecl.syntaxCopy(s) : null); } override const(char)* kind() const { return "enum member"; } Expression getVarExp(const ref Loc loc, Scope* sc) { dsymbolSemantic(this, sc); if (errors) return ErrorExp.get(); checkDisabled(loc, sc); if (depdecl && !depdecl._scope) depdecl._scope = sc; checkDeprecated(loc, sc); if (errors) return ErrorExp.get(); Expression e = new VarExp(loc, this); return e.expressionSemantic(sc); } override inout(EnumMember) isEnumMember() inout { return this; } override void accept(Visitor v) { v.visit(this); } } /****************************************** * Check for special enum names. * * Special enum names are used by the C++ name mangler to represent * C++ types that are not basic D types. * Params: * ident = identifier to check for specialness * Returns: * `true` if it is special */ bool isSpecialEnumIdent(const Identifier ident) @nogc nothrow { return ident == Id.__c_long || ident == Id.__c_ulong || ident == Id.__c_longlong || ident == Id.__c_ulonglong || ident == Id.__c_long_double || ident == Id.__c_wchar_t || ident == Id.__c_complex_float || ident == Id.__c_complex_double || ident == Id.__c_complex_real; }
D
module elasticsearch.api.actions.indices; import elasticsearch.api.base; alias createIndex = elasticsearch.api.actions.indices.create; /** Create an index. * * Creates a new index * * Params: * arguments = A Parameters dictionary list with the following * index: The index name (required) * body: Optional json string configuration for the index (`settings` and `mappings`) * timeout: Explicit operation timeout * * Returns: Response object with the server response. * * Throws: ArgumentError * * See_Also: http://www.elasticsearch.org/guide/reference/api/admin-indices-create-index/ * */ Response create(Client client, Parameters arguments = Parameters()) { arguments.enforceParameter("index"); auto index = arguments["index"]; auto params = arguments.validateAndExtract("timeout"); auto requestBody = arguments["body"]; return client.performRequest(RequestMethod.PUT, esPathify(index), params, requestBody); } Response create(Client client, string indexName, string indexBody, Parameters params = Parameters()) { params["index"] = indexName; params["body"] = indexBody; return create(client, params); } alias deleteIndex = elasticsearch.api.actions.indices.delete_; Response delete_(Client client, string[] indexes, Parameters arguments = Parameters()) { auto params = arguments.validateAndExtract("timeout"); return client.performRequest(RequestMethod.DELETE, esPathify(esListify(indexes)), params); } Response delete_(Client client, string index, Parameters params = Parameters()) { return delete_(client, [index], params); } alias indexExists = elasticsearch.api.actions.indices.exists; bool exists(Client client, Parameters arguments) { arguments.enforceParameter("index"); auto params = arguments.validateAndExtract( "ignore_indices", "ignore_unavailable", "allow_no_indices", "expand_wildcards", "local" ); try { Response response = client.performRequest(RequestMethod.HEAD, esPathify(arguments["index"]), params); return (response.status == 200); } catch (RequestException e) { return false; } } bool exists(Client client, string indexName, Parameters params = Parameters()) { params["index"] = indexName; return exists(client, params); }
D
instance DIA_BDT_1020_WEGELAGERER_EXIT(C_INFO) { npc = bdt_1020_bandit_l; nr = 999; condition = dia_wegelagerer_exit_condition; information = dia_wegelagerer_exit_info; permanent = TRUE; description = DIALOG_ENDE; }; func int dia_wegelagerer_exit_condition() { return TRUE; }; func void dia_wegelagerer_exit_info() { AI_StopProcessInfos(self); }; const string BDT_1020_WEGELAGERER_CHECKPOINT = "NW_TROLLAREA_PATH_46"; instance DIA_BDT_1020_WEGELAGERER_FIRSTWARN(C_INFO) { npc = bdt_1020_bandit_l; nr = 1; condition = dia_bdt_1020_wegelagerer_firstwarn_condition; information = dia_bdt_1020_wegelagerer_firstwarn_info; permanent = TRUE; important = TRUE; }; func int dia_bdt_1020_wegelagerer_firstwarn_condition() { if((other.aivar[AIV_GUARDPASSAGE_STATUS] == GP_NONE) && (self.aivar[AIV_PASSGATE] == FALSE) && (Hlp_StrCmp(Npc_GetNearestWP(self),self.wp) == TRUE)) { return TRUE; }; }; func void dia_bdt_1020_wegelagerer_firstwarn_info() { AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_FirstWarn_06_00"); //Hej ty, stůj! AI_Output(other,self,"DIA_BDT_1020_Wegelagerer_FirstWarn_15_01"); //Co chceš? AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_FirstWarn_06_02"); //Jestli nechceš, abych ti nějakou natáhnul, měl bys několik mincí ze svojí kapsy přesunout do tý mý. A pronto! other.aivar[AIV_LASTDISTTOWP] = Npc_GetDistToWP(other,BDT_1020_WEGELAGERER_CHECKPOINT); self.aivar[AIV_GUARDPASSAGE_STATUS] = GP_FIRSTWARNGIVEN; Info_ClearChoices(dia_bdt_1020_wegelagerer_firstwarn); Info_AddChoice(dia_bdt_1020_wegelagerer_firstwarn,"Kolik chceš?",dia_bdt_1020_wegelagerer_firstwarn_howmuch); Info_AddChoice(dia_bdt_1020_wegelagerer_firstwarn,"To si děláš srandu?",dia_bdt_1020_wegelagerer_firstwarn_joke); Info_AddChoice(dia_bdt_1020_wegelagerer_firstwarn,"Z cesty!",dia_bdt_1020_wegelagerer_pissoff); if(MIS_SCHNITZELJAGD == LOG_RUNNING) { Info_AddChoice(dia_bdt_1020_wegelagerer_firstwarn,"Řekni, neviděl jsi novice?",dia_bdt_1020_wegelagerer_agon); }; }; func void dia_bdt_1020_wegelagerer_agon() { AI_Output(other,self,"DIA_BDT_1020_Wegelagerer_AGON_15_00"); //Řekni, neviděl jsi novice? AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_AGON_06_01"); //(zmateně) Ehm - co? Hmm... (přemýšlí) Jo, to by mohlo být. AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_AGON_06_02"); //Dej mi 20 zlatých a já ti to povím! WEGELAGERER_SURPRISE = TRUE; if(Npc_HasItems(other,itmi_gold) >= 20) { Info_AddChoice(dia_bdt_1020_wegelagerer_firstwarn,"Dobrá, dobrá, tady jsou ty prachy.",dia_bdt_1020_wegelagerer_firstwarn_givemoney); }; Info_AddChoice(dia_bdt_1020_wegelagerer_firstwarn,"Promiň, nemám žádné peníze.",dia_bdt_1020_wegelagerer_firstwarn_nomoney); Info_AddChoice(dia_bdt_1020_wegelagerer_firstwarn,"Jdi mi z cesty.",dia_bdt_1020_wegelagerer_firstwarn_never); }; func void dia_bdt_1020_wegelagerer_firstwarn_howmuch() { AI_Output(other,self,"DIA_BDT_1020_Wegelagerer_FirstWarn_HowMuch_15_00"); //Kolik chceš? AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_FirstWarn_HowMuch_06_01"); //(směje se) 20 zlatých a můžeme bejt kámoši. Info_ClearChoices(dia_bdt_1020_wegelagerer_firstwarn); if(Npc_HasItems(other,itmi_gold) >= 20) { Info_AddChoice(dia_bdt_1020_wegelagerer_firstwarn,"Dobrá, dobrá, tady jsou ty prachy.",dia_bdt_1020_wegelagerer_firstwarn_givemoney); }; Info_AddChoice(dia_bdt_1020_wegelagerer_firstwarn,"Promiň, nemám žádné peníze.",dia_bdt_1020_wegelagerer_firstwarn_nomoney); Info_AddChoice(dia_bdt_1020_wegelagerer_firstwarn,"Jdi mi z cesty.",dia_bdt_1020_wegelagerer_firstwarn_never); }; func void dia_bdt_1020_wegelagerer_firstwarn_joke() { AI_Output(other,self,"DIA_BDT_1020_Wegelagerer_FirstWarn_Joke_15_00"); //To si děláš srandu. AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_FirstWarn_Joke_06_01"); //Vypadám na to? AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_FirstWarn_Joke_06_02"); //Pokud neuvidím 20 zlatých, stačí udělat jedinej krok navíc a... AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_FirstWarn_Joke_06_03"); //V tom případě tě sejmu. Tak už ty prachy naval. self.aivar[AIV_GUARDPASSAGE_STATUS] = GP_SECONDWARNGIVEN; Info_ClearChoices(dia_bdt_1020_wegelagerer_firstwarn); if(Npc_HasItems(other,itmi_gold) >= 20) { Info_AddChoice(dia_bdt_1020_wegelagerer_firstwarn,"Dobrá, dobrá, tady jsou ty prachy.",dia_bdt_1020_wegelagerer_firstwarn_givemoney); }; Info_AddChoice(dia_bdt_1020_wegelagerer_firstwarn,"Promiň, nemám žádné peníze.",dia_bdt_1020_wegelagerer_firstwarn_nomoney); Info_AddChoice(dia_bdt_1020_wegelagerer_firstwarn,"Jdi mi z cesty.",dia_bdt_1020_wegelagerer_firstwarn_never); }; func void dia_bdt_1020_wegelagerer_pissoff() { AI_Output(other,self,"DIA_BDT_1020_Wegelagerer_PissOff_15_00"); //Z cesty! AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_PissOff_06_01"); //Ty máš ale velkou hubu na tak vychrtlýho zaprcatělýho chlápka. AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_PissOff_06_02"); //Už je načase, abych ti ji zavřel. AI_StopProcessInfos(self); b_attack(self,other,AR_NONE,1); }; func void dia_bdt_1020_wegelagerer_firstwarn_givemoney() { AI_Output(other,self,"DIA_BDT_1020_Wegelagerer_FirstWarn_GiveMoney_15_00"); //Dobrá, dobrá, tady jsou ty prachy. if(WEGELAGERER_SURPRISE == FALSE) { AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_FirstWarn_GiveMoney_06_01"); //(jízlivě) Říkal jsem si, že 20 zlatých není tak velká cena za tvůj život. Můžeš projít. }; if(WEGELAGERER_SURPRISE == TRUE) { AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_FirstWarn_GiveMoney_06_02"); //Fajn, tak ten novic tudy prošel před necelou hodinou. AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_FirstWarn_GiveMoney_06_03"); //Měl docela naspěch. Celou dobu se ohlížel. A teď se zdejchni. }; b_giveinvitems(other,self,itmi_gold,20); self.aivar[AIV_PASSGATE] = TRUE; AI_StopProcessInfos(self); }; func void dia_bdt_1020_wegelagerer_firstwarn_nomoney() { AI_Output(other,self,"DIA_BDT_1020_Wegelagerer_FirstWarn_NoMoney_15_00"); //Promiň, nemám žádné peníze. AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_FirstWarn_NoMoney_06_01"); //Jo, jsou to teď zlý časy, co. if(Npc_HasEquippedMeleeWeapon(other)) { AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_FirstWarn_NoMoney_06_02"); //Ale něco ti povím - dej mi svou zbraň. Pak tě nechám projít. Info_ClearChoices(dia_bdt_1020_wegelagerer_firstwarn); Info_AddChoice(dia_bdt_1020_wegelagerer_firstwarn,"Zapomeň na to.",dia_bdt_1020_wegelagerer_firstwarn_noweapon); Info_AddChoice(dia_bdt_1020_wegelagerer_firstwarn,"Tady, vezmi si mou zbraň.",dia_bdt_1020_wegelagerer_firstwarn_giveweapon); } else { AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_FirstWarn_NoMoney_06_03"); //Já ti řeknu co: vrať se, až budeš mít nějaký peníze. Žádný prachy, žádnej most. self.aivar[AIV_GUARDPASSAGE_STATUS] = GP_FIRSTWARNGIVEN; AI_StopProcessInfos(self); }; }; func void dia_bdt_1020_wegelagerer_firstwarn_never() { AI_Output(other,self,"DIA_BDT_1020_Wegelagerer_FirstWarn_Never_15_00"); //Jdi mi z cesty. AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_FirstWarn_Never_06_01"); //Takže ty na to jdeš tvrdě? AI_StopProcessInfos(self); b_attack(self,other,AR_NONE,1); }; func void dia_bdt_1020_wegelagerer_firstwarn_noweapon() { AI_Output(other,self,"DIA_BDT_1020_Wegelagerer_FirstWarn_NoWeapon_15_00"); //Zapomeň na to. AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_FirstWarn_NoWeapon_06_01"); //Dobrá, tak teda tvrdě. AI_StopProcessInfos(self); b_attack(self,other,AR_NONE,1); }; func void dia_bdt_1020_wegelagerer_firstwarn_giveweapon() { AI_Output(other,self,"DIA_BDT_1020_Wegelagerer_FirstWarn_GiveWeapon_15_00"); //Tady, vezmi si mou zbraň. AI_DrawWeapon(other); AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_FirstWarn_GiveWeapon_06_01"); //Nech tu zbraň na pokoji. Jen počkej! AI_StopProcessInfos(self); b_attack(self,other,AR_GUARDSTOPSINTRUDER,1); }; instance DIA_BDT_1020_WEGELAGERER_SECONDWARN(C_INFO) { npc = bdt_1020_bandit_l; nr = 2; condition = dia_bdt_1020_wegelagerer_secondwarn_condition; information = dia_bdt_1020_wegelagerer_secondwarn_info; permanent = TRUE; important = TRUE; }; func int dia_bdt_1020_wegelagerer_secondwarn_condition() { if((self.aivar[AIV_GUARDPASSAGE_STATUS] == GP_FIRSTWARNGIVEN) && (self.aivar[AIV_PASSGATE] == FALSE) && (Hlp_StrCmp(Npc_GetNearestWP(self),self.wp) == TRUE) && (Npc_GetDistToWP(other,BDT_1020_WEGELAGERER_CHECKPOINT) < (other.aivar[AIV_LASTDISTTOWP] - 50))) { return TRUE; }; }; func void dia_bdt_1020_wegelagerer_secondwarn_info() { AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_SecondWarn_06_00"); //Vážně chceš ještě dostat šanci? Je to tvoje právo. Info_ClearChoices(dia_bdt_1020_wegelagerer_secondwarn); if(Npc_HasItems(other,itmi_gold) >= 20) { Info_AddChoice(dia_bdt_1020_wegelagerer_secondwarn,"Tady jsou peníze.",dia_bdt_1020_wegelagerer_secondwarn_givemoney); }; Info_AddChoice(dia_bdt_1020_wegelagerer_secondwarn,"Nedám ti ani měďák.",dia_bdt_1020_wegelagerer_secondwarn_nomoney); other.aivar[AIV_LASTDISTTOWP] = Npc_GetDistToWP(other,BDT_1020_WEGELAGERER_CHECKPOINT); self.aivar[AIV_GUARDPASSAGE_STATUS] = GP_SECONDWARNGIVEN; }; func void dia_bdt_1020_wegelagerer_secondwarn_givemoney() { AI_Output(other,self,"DIA_BDT_1020_Wegelagerer_SecondWarn_GiveMoney_15_00"); //Tady jsou peníze. AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_SecondWarn_GiveMoney_06_01"); //Á, ono už se s tebou dá mluvit. b_giveinvitems(other,self,itmi_gold,20); self.aivar[AIV_PASSGATE] = TRUE; AI_StopProcessInfos(self); }; func void dia_bdt_1020_wegelagerer_secondwarn_nomoney() { AI_Output(other,self,"DIA_BDT_1020_Wegelagerer_SecondWarn_NoMoney_15_00"); //Nedám ti ani měďák. AI_Output(self,other,"DIA_BDT_1020_Wegelagerer_SecondWarn_NoMoney_06_01"); //Tak si ho vezmu sám. AI_StopProcessInfos(self); b_attack(self,other,AR_NONE,1); }; instance DIA_BDT_1020_WEGELAGERER_ATTACK(C_INFO) { npc = bdt_1020_bandit_l; nr = 3; condition = dia_bdt_1020_wegelagerer_attack_condition; information = dia_bdt_1020_wegelagerer_attack_info; permanent = TRUE; important = TRUE; }; func int dia_bdt_1020_wegelagerer_attack_condition() { if((self.aivar[AIV_GUARDPASSAGE_STATUS] == GP_SECONDWARNGIVEN) && (self.aivar[AIV_PASSGATE] == FALSE) && (Hlp_StrCmp(Npc_GetNearestWP(self),self.wp) == TRUE) && (Npc_GetDistToWP(other,BDT_1020_WEGELAGERER_CHECKPOINT) < (other.aivar[AIV_LASTDISTTOWP] - 50))) { return TRUE; }; }; func void dia_bdt_1020_wegelagerer_attack_info() { other.aivar[AIV_LASTDISTTOWP] = 0; self.aivar[AIV_GUARDPASSAGE_STATUS] = GP_NONE; AI_StopProcessInfos(self); b_attack(self,other,AR_NONE,1); };
D
module ex3.mod; import glued.application.stereotypes; interface I1 {} interface I2 {} interface I3 : I1 {} interface I4: I3 {} interface I5: I2 {} @Component class C1 {} @Tracked class C2: I2 {} @Component class C3 : C2 {} @Component class C4: C3, I4 {} @Component class C5: C3, I5 {} unittest { import std.traits; //BaseTypeTuple and BaseClassesTuple are not really well defined in the docs, //so here's a little sanity check import std.meta; //basically, BaseTypeTuple shows whats in type declaration code // and Object in case of classes that don't explicitly inherit from // other classes //while BaseClassesTuple shows class hierarchy path to Object static assert(BaseTypeTuple!I1.length ==0); static assert(BaseTypeTuple!I2.length ==0); static assert(is(BaseTypeTuple!I3 == AliasSeq!(I1))); static assert(is(BaseTypeTuple!I4 == AliasSeq!(I3))); static assert(is(BaseTypeTuple!I5 == AliasSeq!(I2))); static assert(is(BaseTypeTuple!C1 == AliasSeq!(Object))); static assert(is(BaseClassesTuple!C1 == AliasSeq!(Object))); static assert(is(BaseTypeTuple!C2 == AliasSeq!(Object, I2))); static assert(is(BaseClassesTuple!C2 == AliasSeq!(Object))); static assert(is(BaseTypeTuple!C3 == AliasSeq!(C2))); static assert(is(BaseClassesTuple!C3 == AliasSeq!(C2, Object))); static assert(is(BaseTypeTuple!C4 == AliasSeq!(C3, I4))); static assert(is(BaseClassesTuple!C4 == AliasSeq!(C3, C2, Object))); static assert(is(BaseTypeTuple!C5 == AliasSeq!(C3, I5))); static assert(is(BaseClassesTuple!C5 == AliasSeq!(C3, C2, Object))); }
D
/* Copyright 2006, 2007 Kirk McDonald Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * This module used to contain some more or less dirty hacks for converting * between function and delegate types. As of DMD 0.174, the language has * built-in support for hacking apart delegates like this. Hooray! */ module pyd.dg_convert; import pyd.lib_abstract : ParameterTypeTuple, ReturnType ; //import std.traits; template fn_to_dgT(Fn) { alias ParameterTypeTuple!(Fn) T; alias ReturnType!(Fn) Ret; alias Ret delegate(T) type; } /** * This template converts a function type into an equivalent delegate type. */ template fn_to_dg(Fn) { alias fn_to_dgT!(Fn).type fn_to_dg; } // Breaking out the old hack again for GDC support... struct dg_struct { void* ptr; void* funcptr; } union dg_hack(T) { dg_struct fake_dg; T real_dg; } /** * This template function converts a pointer to a member function into a * delegate. */ fn_to_dg!(Fn) dg_wrapper(T, Fn) (T t, Fn fn) { //fn_to_dg!(Fn) dg; //dg.ptr = t; //dg.funcptr = fn; //return dg; dg_hack!(fn_to_dg!(Fn)) dg; dg.fake_dg.ptr = cast(void*)t; dg.fake_dg.funcptr = fn; return dg.real_dg; }
D
// Copyright Gushcha Anton 2012. // 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) // written in D programming language /** * Module provides many usefull functions to work with C-style strings, degree and radian angles, text parsing and generic programming. * * Authors: Gushcha Anton (NCrashed) * * $(BOOKTABLE , * $(TR * $(TH Category) * $(TH Functions) * ) * $(TR * $(TDNW Strings) * $(TD * $(MYREF fromStringz) * ) * ) * $(TR * $(TDNW Angles) * $(TD * $(MYREF Degree) * $(MYREF Radian) * $(MYREF trimAng) * $(MYREF deg2rad) * $(MYREF rad2deg) * ) * ) * $(TR * $(TDNW Parsing) * $(TD * $(MYREF removeAfter) * $(MYREF commutateByKey) * $(MYREF findPos) * $(MYREF findPosEscaped) * $(MYREF findLastPos) * $(MYREF countUntilEscaped) * ) * ) * $(TR * $(TDNW Generic) * $(TD * $(MYREF getMemberType) * $(MYREF getMemberType) * $(MYREF FieldNameTuple) * $(MYREF SatisfyFieldTuple) * $(MYREF StaticFind) * $(MYREF AssociativeArrayKeyType) * $(MYREF AssociativeArrayValueType) * $(MYREF ArrayElementType) * ) * ) * ) * * Macros: * MYREF = <font face='Consolas, "Bitstream Vera Sans Mono", "Andale Mono", Monaco, "DejaVu Sans Mono", "Lucida Console", monospace'><a href="#$1">$1</a>&nbsp;</font> */ module util.common; import std.math; import std.traits; import std.algorithm : countUntil; import std.typetuple; /// fromStringz /** * Returns new string formed from C-style (null-terminated) string $(D msg). Usefull * when interfacing with C libraries. For D-style to C-style convertion use std.string.toStringz * * Example: * ---------- * char[] cstring = "some string".dup ~ cast(char)0; * * assert(fromStringz(cstring.ptr) == "some string"); * ---------- */ string fromStringz(const char* msg) nothrow { try { if(msg is null) return ""; auto buff = new char[0]; uint i = 0; while(msg[i]!=cast(char)0) buff ~= msg[i++]; return buff.idup; } catch(Exception e) { return ""; } } unittest { char[] cstring = "some string".dup ~ cast(char)0; assert(fromStringz(cstring.ptr) == "some string"); } /// Degree /** * Degree is 1/360 part of full angle. */ alias double Degree; /// Radian /** * Radian is central angle of circle sector with arc length equal to the circle radius. */ alias double Radian; /// trimAng /** * Сuts radian angle in range (-2*PI..2*PI). * * Example: * -------- * assert(approxEqual(trimAng(PI/6), PI/6)); * assert(approxEqual(trimAng(-PI/3), -PI/3)); * assert(approxEqual(trimAng(4*PI), 0)); * assert(approxEqual(trimAng(-6*PI), 0)); * assert(approxEqual(trimAng(8*PI/3), 2*PI/3)); * assert(approxEqual(trimAng(-13*PI/6), -PI/6)); * -------- */ Radian trimAng(Radian angle) { while( angle > 2*PI || approxEqual(angle, 2*PI)) angle -= 2*PI; while( angle < -2*PI || approxEqual(angle, -2*PI)) angle += 2*PI; return angle; } unittest { assert(approxEqual(trimAng(PI/6), PI/6)); assert(approxEqual(trimAng(-PI/3), -PI/3)); assert(approxEqual(trimAng(4*PI), 0)); assert(approxEqual(trimAng(-6*PI), 0)); assert(approxEqual(trimAng(8*PI/3), 2*PI/3)); assert(approxEqual(trimAng(-13*PI/6), -PI/6)); } /// Degree -> Radian /** * Converts $(D angle) measured in degrees to radian angle. * * Example: * ---------- * assert(approxEqual(deg2rad(90.), cast(Radian)(PI/2))); * assert(approxEqual(deg2rad(60.), cast(Radian)(PI/3))); * assert(approxEqual(deg2rad(30.), cast(Radian)(PI/6))); * ---------- */ Radian deg2rad(Degree angle) { return angle * (2*PI/360); } unittest { assert(approxEqual(deg2rad(90.), cast(Radian)(PI/2))); assert(approxEqual(deg2rad(60.), cast(Radian)(PI/3))); assert(approxEqual(deg2rad(30.), cast(Radian)(PI/6))); } /// Radian -> Degree /** * Converts $(D angle) measured in radians to degree angle. * * Example: * --------- * assert(approxEqual(rad2deg(PI/2), cast(Degree)90.)); * assert(approxEqual(rad2deg(PI/3), cast(Degree)60.)); * assert(approxEqual(rad2deg(PI/6), cast(Degree)30.)); * --------- */ Degree rad2deg(Radian angle) { return angle * (360/(2*PI)); } unittest { assert(approxEqual(rad2deg(PI/2), cast(Degree)90.)); assert(approxEqual(rad2deg(PI/3), cast(Degree)60.)); assert(approxEqual(rad2deg(PI/6), cast(Degree)30.)); } /// removeAfter /** * Returns string $(D s) with removed symbols after first substring $(D key) including $(D key). * * Example: * --------- * assert(removeAfter("My string # comment", "#") == "My string "); * assert(removeAfter("My string// comment", "//") == "My string"); * assert(removeAfter("My string// comment", "?") == "My string// comment"); * assert(removeAfter("// comment", "//") == ""); * --------- */ string removeAfter(string s, string key) { bool isEqual(string a, string b) { return a[0..b.length] == b; } for(uint i = 0; i<s.length; i++) if(isEqual(s[i..$], key)) return s[0..i]; return s; } unittest { import std.stdio; assert(removeAfter("My string # comment", "#") == "My string ", "Failed: "~removeAfter("My string # comment", "#")); assert(removeAfter("My string// comment", "//") == "My string", "Failed: "~removeAfter("My string// comment", "//")); assert(removeAfter("My string// comment", "?") == "My string// comment", "Failed: "~removeAfter("My string// comment", "?")); assert(removeAfter("// comment", "//") == "", "Failed: "~removeAfter("// comment", "//")); } /// commutateByKey /** * Simplifies writing huge switches for text parsing. Function passed keys list $(D keys), * key $(D key), some string values $(D args) and lambdas list $(D ops) wich length must be * equal $(D keys) one. If $(D key) is located in $(D keys), then corresponding lambda from * $(D ops) is called with argument $(D args). Lambdas have to be $(D int function(string[])) * format. Returns one of lamda output, or -1 if no lamda wasn't called. * * Example: * ---------- * auto keys = ["a","b","c"]; * auto key = "b"; * auto pargs = ["arg1", "arg2"]; * * assert( * commutateByKey(key, keys, pargs, * (string[] args) //a * { * return 0; * }, * (string[] args) //b * { * return 1; * }, * (string[] args) //c * { * return 2; * } * ) == 1 * ); * ---------- */ int commutateByKey(T...)(string key, string[] keys, string[] args, T ops) in { assert(keys.length == ops.length, "Keys count and operators count must be equal"); } body { import std.stdio; foreach( i, t1; T ) { static assert( isFunctionPointer!t1 || isDelegate!t1, "Operator type must be delegate or function! "~t1.stringof~" doesn't suit!"); alias ParameterTypeTuple!(t1) al; alias ReturnType!(t1) r1; static assert( al.length==1 && is(al[0] == string[]), "Operator "~t1.stringof~" must get only string[] argument type!"); static assert( is(r1 == int), "Operator "~T.stringof~" must return int!"); if( key == keys[i] ) { return ops[i](args); } } return -1; } unittest { import std.stdio; assert( __traits( compiles, `commutateByKey("test", ["test","notest"], ["arg1","arg2"], (string[] args){return 0;}, (string[] args){return 1;})` ), "Testing commutateByKey failed!"); assert( commutateByKey("test", ["test","notest"], ["arg1","arg2"], (string[] args){return 0;}, (string[] args){return 1;}) == 0, "Testing commutateByKey failed!"); auto keys = ["a","b","c"]; auto key = "b"; auto pargs = ["arg1", "arg2"]; assert( commutateByKey(key, keys, pargs, (string[] args) //a { return 0; }, (string[] args) //b { return 1; }, (string[] args) //c { return 2; } ) == 1 ); } // countUntilEscaped /** * Same as countUntil, but don't track escaped strings with '\'. * * Example: * ---------- * auto s = `word1 word2\[\] word3[]`; * assert(countUntilEscaped(s, " ") == 5); * assert(countUntilEscaped(s, "[") == 21); * assert(countUntilEscaped(s, "[]") == -1); * ---------- */ sizediff_t countUntilEscaped(string s, string what) { import std.stdio; for(sizediff_t i = 0; i<s.length-what.length+1; i++) { if(s[i..i+what.length] == what) if(i == 0) return 0; else if(s[i-1] == '\\') continue; else return i; } return -1; } unittest { auto s = `word1 word2\[\]\ word3[]`; assert(countUntilEscaped(s, " ") == 5); assert(countUntilEscaped(s[6..$], " ") == -1); assert(countUntilEscaped(s, "[") == 22); assert(countUntilEscaped(s, "[]") == 22); assert(countUntilEscaped(`\word2\ word3`, " ") == -1); } /// findPos /** * Search of substring $(D what) in string $(D s), begining at symbol * position $(D pos). It is port from STL. Returns substring begining * position or -1 if not found. * * Example: * ---- * auto s = "word1 word2 word3"; * assert(findPos(s, 0, " ") == 5); * assert(findPos(s, 6, " ") == 11); * assert(findPos(s, 0, "word2") == 6); * assert(findPos(s, 7, "word") == 12); * ---- */ sizediff_t findPos(string s, size_t pos, string what) { auto temp = countUntil(s[pos..$], what); if( temp == -1) return -1; return temp+pos; } unittest { auto s = "word1 word2 word3"; assert(findPos(s, 0, " ") == 5); assert(findPos(s, 6, " ") == 11); assert(findPos(s, 0, "word2") == 6); assert(findPos(s, 7, "word") == 12); } /// findPosEscaped /** * Search of substring $(D what) in string $(D s), begining at symbol * position $(D pos). Returns substring begining position or -1 if not * found. If substring followed after '\', doesn't track as match. * * Example: * ---- * auto s = `word1 \word2\ word3`; * assert(findPos(s, 0, " ") == 5); * assert(findPos(s, 6, " ") == -1); * assert(findPos(s, 0, "word2") == -1); * assert(findPos(s, 2, "word") == 14); * ---- */ sizediff_t findPosEscaped(string s, size_t pos, string what) { auto temp = countUntilEscaped(s[pos..$], what); if( temp == -1) return -1; return temp+pos; } unittest { auto s = `word1 \word2\ word3`; assert(findPosEscaped(s, 0, " ") == 5); assert(findPosEscaped(s, 6, " ") == -1); assert(findPosEscaped(s, 0, "word2") == -1); assert(findPosEscaped(s, 2, "word") == 14); } /// findLastPos /** * Search of last substring $(D what) in string $(D s), begining at * sympol position $(D pos). It is port from STL find_last. Returns * substring begining position or -1 if not found. * * Example: * ---- * assert(findLastPos("word1 word2 word3", 0, " ") == 11); * assert(findLastPos("hello World!"), 0, "World") == 6); * assert(findLastPos("hello World!"), 7, "World") == -1); * ---- */ sizediff_t findLastPos(string s, size_t pos, string what) { for(size_t i = s.length-1-what.length; i>pos; --i) if(s[i..i+what.length] == what) return i; return -1; } unittest { assert(findLastPos("word1 word2 word3", 0, " ") == 11); assert(findLastPos("hello World!", 0, "World") == 6); assert(findLastPos("hello World!", 7, "World") == -1); } /// getMemberType /** * Retrieves member type with $(D name) of class $(D Class). If member is agregate * type declaration or simply doesn't exist, retrieves no type. You can check it with * $(D is) operator. * * Example: * ----------- * class A * { * int aField; * string b; * bool c; * * class B {} * struct C {} * union D {} * interface E {} * } * * static assert(is(getMemberType!(A, "aField") == int)); * static assert(is(getMemberType!(A, "b") == string)); * static assert(is(getMemberType!(A, "c") == bool)); * * static assert(!is(getMemberType!(A, "B"))); * static assert(!is(getMemberType!(A, "C"))); * static assert(!is(getMemberType!(A, "D"))); * static assert(!is(getMemberType!(A, "E"))); * ----------- */ template getMemberType(Class, string name) { static if(hasMember!(Class, name)) alias typeof(__traits(getMember, Class, name)) getMemberType; } unittest { class A { int a; string b; bool c; class B {} struct C {} union D {} interface E {} } static assert(is(getMemberType!(A, "a") == int)); static assert(is(getMemberType!(A, "b") == string)); static assert(is(getMemberType!(A, "c") == bool)); static assert(!is(getMemberType!(A, "B"))); static assert(!is(getMemberType!(A, "C"))); static assert(!is(getMemberType!(A, "D"))); static assert(!is(getMemberType!(A, "E"))); } /// FieldNameTuple /** * Retrieves names of all class/struct/union $(D Class) fields excluding technical ones like this, Monitor. * * Example: * --------- * class A * { * int aField; * * void func1() {} * static void func2() {} * * string b; * * final func3() {} * abstract void func4(); * * bool c; * } * * static assert(FieldNameTuple!A == ["aField","b","c"]); * --------- */ template FieldNameTuple(Class) { template removeFuncs(funcs...) { static if(funcs.length > 0) { // if member is class/struct/interface declaration second part getMemberType returns no type static if( is(getMemberType!(Class, funcs[0]) == function) || !is(getMemberType!(Class, funcs[0])) || funcs[0] == "this" || funcs[0] == "Monitor" ) { enum removeFuncs = removeFuncs!(funcs[1..$]); } else enum removeFuncs = [funcs[0]]~removeFuncs!(funcs[1..$]); } else enum removeFuncs = []; } enum temp = removeFuncs!(__traits(allMembers, Class)); static if(temp.length > 0) enum FieldNameTuple = temp[0..$-1]; else enum FieldNameTuple = []; } // ddoc example unittest { class A { int a; void func1() {} static void func2() {} string b; final func3() {} abstract void func4(); bool c; } static assert(FieldNameTuple!A == ["a","b","c"]); } unittest { class P { void foo() {} real p; } class A : P { int aField; void func1() {} static void func2() {} string b; final void func3() {} abstract void func4(); bool c; void function(int,int) da; void delegate(int, int) db; class B {} B mB; struct C {} C mC; interface D {} } static assert(FieldNameTuple!A == ["aField","b","c","da","db","mB","mC","p"]); static assert(is(getMemberType!(A, "aField") == int)); static assert(is(getMemberType!(A, "b") == string)); static assert(is(getMemberType!(A, "c") == bool)); struct S1 { int a; bool b; void foo() {} real c; } static assert(FieldNameTuple!S1 == ["a","b","c"]); union S2 { size_t index; void* pointer; } static assert(FieldNameTuple!S2 == ["index", "pointer"]); class S3 { } static assert(FieldNameTuple!S3 == []); // Properties detected as field. To fix. struct S4 { @property S4 dup() { return S4(); } } static assert(FieldNameTuple!S4 == ["dup"]); } /// SatisfyFieldTuple /** * Returns array of aggragate type $(D Class) field names which types satisfy predecate $(D Predicate). * * Example: * ---------- * class A * { * bool a; * string b; * int c; * double d; * * class B {} * B mB; * A mA; * * struct C {} * C mC; * * union D {} * D mD; * } * * static assert(SatisfyFieldTuple!(A, isAggregateType) == ["mB","mA","mC","mD"]); * static assert(SatisfyFieldTuple!(A, isBasicType) == ["a","c","d"]); * static assert(SatisfyFieldTuple!(A, isArray) == ["b"]); * ---------- */ template SatisfyFieldTuple(Class, alias Predicate) { enum clfields = FieldNameTuple!Class; template Shrink(pfields...) { enum fields = pfields[0]; static if(fields.length > 0) { static if(Predicate!(getMemberType!(Class, fields[0]))) enum Shrink = [fields[0]]~Shrink!(fields[1..$]); else enum Shrink = Shrink!(fields[1..$]); } else enum Shrink = ""; } enum temp = Shrink!(clfields); static if(temp.length>0) enum SatisfyFieldTuple = temp[0..$-1]; else enum SatisfyFieldTuple = []; } unittest { class A { bool a; string b; int c; double d; class B {} B mB; A mA; struct C {} C mC; union D {} D mD; } static assert(SatisfyFieldTuple!(A, isAggregateType) == ["mB","mA","mC","mD"]); static assert(SatisfyFieldTuple!(A, isBasicType) == ["a","c","d"]); static assert(SatisfyFieldTuple!(A, isArray) == ["b"]); class S1 { bool a; } static assert(SatisfyFieldTuple!(S1, isAggregateType) == []); } template TypeTupleFrom(Class, names...) { template innerLoop(tms...) { enum ms = tms[0]; static if(ms.length > 0) { alias TypeTuple!(getMemberType!(Class, ms[0]), innerLoop!(ms[1..$])) innerLoop; } else alias TypeTuple!() innerLoop; } alias innerLoop!(names) TypeTupleFrom; } unittest { class A { bool a; string b; int c; double d; class B {} B mB; A mA; struct C {} C mC; union D {} D mD; } alias FieldNameTuple!(A) fields; alias TypeTupleFrom!(A, fields) types; static assert(is( types == TypeTuple!(bool, string, int, double, A.B, A, A.C, A.D))); } /// StaticFind /** * Finds first occurrence position of string $(D what) in string $(D where). If cannot find substring * returns -1. * * Example: * ---------- * static assert(StaticFind!("some string", "str") == 5); * static assert(StaticFind!("some string", "world") == -1); * static assert(StaticFind!("str", "string") == -1); * static assert(StaticFind!("string", "string") == 0); * ---------- */ template StaticFind(string where, string what) { template innerLoop(string s) { static if(s.length < what.length || s.length == 0) { enum innerLoop = -1; } else static if(s[0..what.length] == what) { enum innerLoop = 0; } else { enum temp = innerLoop!(s[1..$]); static if(temp == -1) enum innerLoop = -1; else enum innerLoop = 1+temp; } } enum StaticFind = innerLoop!(where); } unittest { static assert(StaticFind!("some string", "str") == 5); static assert(StaticFind!("some string", "world") == -1); static assert(StaticFind!("str", "string") == -1); static assert(StaticFind!("string", "string") == 0); } /// AssociativeArrayKeyType /** * Retrieves associative array $(D T) key type. If T is not associative array, retrieves nothing, which can be * checked with $(D is) operator. * * Example: * --------- * static assert(is(AssociativeArrayKeyType!(string[float]) == float)); * static assert(is(AssociativeArrayKeyType!(shared bool[double]) == double)); * static assert(is(AssociativeArrayKeyType!(bool[shared double]) == shared double)); * --------- */ template AssociativeArrayKeyType(T) { static if(isAssociativeArray!T) { enum obraket = StaticFind!(T.stringof, "["); enum cbraket = StaticFind!(T.stringof, "]"); static if(obraket > 0 && cbraket > 0 && cbraket > obraket) mixin("alias "~T.stringof[obraket+1..cbraket]~" AssociativeArrayKeyType;"); } } unittest { static assert(is(AssociativeArrayKeyType!(string[float]) == float)); static assert(is(AssociativeArrayKeyType!(shared bool[double]) == double)); static assert(is(AssociativeArrayKeyType!(bool[shared double]) == shared double)); } /// AssociativeArrayValueType /** * Retrieves associative array $(D T) value type. If T is not associative array, retrieves nothing, which can be * checked with $(D is) operator. * * Example: * --------- * static assert(is(AssociativeArrayValueType!(string[float]) == string)); * static assert(is(AssociativeArrayValueType!(shared bool[double]) == shared bool)); * static assert(is(AssociativeArrayValueType!(bool[shared double]) == bool)); * --------- */ template AssociativeArrayValueType(T) { static if(isAssociativeArray!T) { enum obraket = StaticFind!(T.stringof, "["); enum cbraket = StaticFind!(T.stringof, "]"); static if(obraket > 0 && cbraket > 0 && cbraket > obraket) mixin("alias "~T.stringof[0..obraket]~T.stringof[cbraket+1..$]~" AssociativeArrayValueType;"); } } unittest { static assert(is(AssociativeArrayValueType!(string[float]) == string)); static assert(is(AssociativeArrayValueType!(shared bool[double]) == shared bool)); static assert(is(AssociativeArrayValueType!(bool[shared double]) == bool)); } /// ArrayElementType /** * Retrieves array $(D T) element type.f T is not array, retrieves nothing, which can be * checked with $(D is) operator. * * Example: * --------- * static assert(is(AssociativeArrayValueType!(string[]) == string)); * static assert(is(AssociativeArrayValueType!(shared bool[]) == shared bool)); * static assert(is(AssociativeArrayValueType!(bool[]) == bool)); * --------- */ template ArrayElementType(T) { static if(isArray!T) { /*enum obraket = StaticFind!(T.stringof, "["); enum cbraket = StaticFind!(T.stringof, "]"); static if(obraket > 0 && cbraket > 0 && cbraket > obraket) mixin("alias "~T.stringof[0..obraket]~T.stringof[cbraket+1..$]~" ArrayElementType;");*/ static if(is(T U: U[])) { alias U ArrayElementType; } } } unittest { static assert(is(ArrayElementType!(string[]) == string)); static assert(is(ArrayElementType!(shared bool[]) == shared bool)); static assert(is(ArrayElementType!(bool[]) == bool)); }
D
module levelrenderer; private { import std.stdio; import std.utf; import std.math : sqrt; import material; import sofu = Sofu.Sofu; import engine; import derelict.sdl.sdl; import derelict.opengl.gl; import derelict.opengl.glu; import pipeline; import vector; import util; import interfaces; import dataset; import gobject; import party; import level; import dlisp.dlisp; import dlisp.bind; import dlisp.predefs.all; } class LevelRenderer : Renderer { private: matrix4 projMatrix; matrix4 viewMatrix; GObject _trackedObject; public: Level level; float zoom = 5.0; float look_x = 0.0; float look_y = 0.0; this() { super("level"); } void sceneMode() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-40.0f, 40.0f, -30.0f, 30.0f, -200.0f, 200.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRotatef(-45.0f, 1.0f, 0.0f, 0.0f); glRotatef(45.0f, 0.0f, 0.0f, 1.0f); glScalef(zoom, zoom, zoom); glEnable(GL_TEXTURE_2D); glTranslatef(-look_x,-look_y,0); glGetFloatv(GL_PROJECTION_MATRIX,&projMatrix.a00); glGetFloatv(GL_MODELVIEW_MATRIX,&viewMatrix.a00); invert(&projMatrix); invert(&viewMatrix); } void trackObject(GObject gobject) { _trackedObject = gobject; } void lookAt(float x,float y) { look_x = x; look_y = y; } void toLevelCoords(int* x, int* y) { vector4 screenCoords; long w_ = Engine.instance.xResolution; long h_ = Engine.instance.yResolution; float fx = 2*(cast(float)*x/w_ - 0.5); float fy = 4*(.5-cast(float)*y/h_); set(&screenCoords,fx,fy,0.0f,1.0); mul(&screenCoords,&projMatrix); mul(&screenCoords,&viewMatrix); *x = cast(int)screenCoords.x; *y = cast(int)screenCoords.y; } void drawHighlight(int x, int y) { float z_offset = 0.01; glColor4f(1,0,0,1); glBegin(GL_LINE_LOOP); glVertex3f( x+1, y+1, z_offset ); /* NE */ glVertex3f( x, y+1, z_offset ); /* NW */ glVertex3f( x, y, z_offset ); /* SW */ glVertex3f( x+1, y, z_offset ); glEnd(); glBegin(GL_LINE_LOOP); glVertex3f( x+1, y+1, z_offset+1 ); /* NE */ glVertex3f( x, y+1, z_offset+1 ); /* NW */ glVertex3f( x, y, z_offset+1 ); /* SW */ glVertex3f( x+1, y, z_offset+1 ); glEnd(); glColor4f(0,1,0,1); glBegin(GL_LINES); glVertex3f( x, y, z_offset ); /* NE */ glVertex3f( x, y, z_offset+1 ); /* NW */ glVertex3f( x+1, y, z_offset ); /* SW */ glVertex3f( x+1, y, z_offset+1 ); glVertex3f( x, y+1, z_offset ); /* NE */ glVertex3f( x, y+1, z_offset+1 ); /* NW */ glVertex3f( x+1, y+1, z_offset ); /* SW */ glVertex3f( x+1, y+1, z_offset+1 ); glEnd(); } void render() { if( _trackedObject !is null ) { float dx = look_x - _trackedObject.real_x; float dy = look_y - _trackedObject.real_y; float len = sqrt(dx*dx+dy*dy); if( len > 1.0 ) { lookAt( look_x - dx/len, look_y - dy/len ); } if( len <= 1.0 ) { lookAt( look_x - dx, look_y - dy ); } } sceneMode(); if( level is null ) return; for(int x = 0; x < level.width; ++x) for(int y = 0; y < level.height; ++y) level.getTile(x,y).draw(); foreach(GObject gobject; level.getAllObjects()) { gobject.draw(); } } }
D
/** Defines the behavior of the DUB command line client. Copyright: © 2012-2013 Matthias Dondorff, Copyright © 2012-2014 Sönke Ludwig License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. Authors: Matthias Dondorff, Sönke Ludwig */ module dub.commandline; import dub.compilers.compiler; import dub.dependency; import dub.dub; import dub.generators.generator; import dub.internal.vibecompat.core.file; import dub.internal.vibecompat.core.log; import dub.internal.vibecompat.inet.url; import dub.package_; import dub.packagemanager; import dub.packagesupplier; import dub.platform : determineCompiler; import dub.project; import dub.internal.utils : getDUBVersion, getClosestMatch; import std.algorithm; import std.array; import std.conv; import std.encoding; import std.exception; import std.file; import std.getopt; import std.process; import std.stdio; import std.string; import std.typecons : Tuple, tuple; import std.variant; int runDubCommandLine(string[] args) { logDiagnostic("DUB version %s", getDUBVersion()); version(Windows){ // rdmd uses $TEMP to compute a temporary path. since cygwin substitutes backslashes // with slashes, this causes OPTLINK to fail (it thinks path segments are options) // we substitute the other way around here to fix this. environment["TEMP"] = environment["TEMP"].replace("/", "\\"); } // split application arguments from DUB arguments string[] app_args; auto app_args_idx = args.countUntil("--"); if (app_args_idx >= 0) { app_args = args[app_args_idx+1 .. $]; args = args[0 .. app_args_idx]; } args = args[1 .. $]; // strip the application name // parse general options bool verbose, vverbose, quiet, vquiet; bool help, annotate; LogLevel loglevel = LogLevel.info; string[] registry_urls; string root_path = getcwd(); auto common_args = new CommandArgs(args); try { common_args.getopt("h|help", &help, ["Display general or command specific help"]); common_args.getopt("root", &root_path, ["Path to operate in instead of the current working dir"]); common_args.getopt("registry", &registry_urls, ["Search the given DUB registry URL first when resolving dependencies. Can be specified multiple times."]); common_args.getopt("annotate", &annotate, ["Do not perform any action, just print what would be done"]); common_args.getopt("v|verbose", &verbose, ["Print diagnostic output"]); common_args.getopt("vverbose", &vverbose, ["Print debug output"]); common_args.getopt("q|quiet", &quiet, ["Only print warnings and errors"]); common_args.getopt("vquiet", &vquiet, ["Print no messages"]); common_args.getopt("cache", &defaultPlacementLocation, ["Puts any fetched packages in the specified location [local|system|user]."]); if( vverbose ) loglevel = LogLevel.debug_; else if( verbose ) loglevel = LogLevel.diagnostic; else if( vquiet ) loglevel = LogLevel.none; else if( quiet ) loglevel = LogLevel.warn; setLogLevel(loglevel); } catch (Throwable e) { logError("Error processing arguments: %s", e.msg); logDiagnostic("Full exception: %s", e.toString().sanitize); logInfo("Run 'dub help' for usage information."); return 1; } // create the list of all supported commands CommandGroup[] commands = [ CommandGroup("Package creation", new InitCommand ), CommandGroup("Build, test and run", new RunCommand, new BuildCommand, new TestCommand, new GenerateCommand, new DescribeCommand, new CleanCommand, new DustmiteCommand ), CommandGroup("Package management", new FetchCommand, new InstallCommand, new RemoveCommand, new UninstallCommand, new UpgradeCommand, new AddPathCommand, new RemovePathCommand, new AddLocalCommand, new RemoveLocalCommand, new ListCommand, new ListInstalledCommand, new AddOverrideCommand, new RemoveOverrideCommand, new ListOverridesCommand, new CleanCachesCommand, ) ]; // extract the command string cmdname; args = common_args.extractRemainingArgs(); if (args.length >= 1 && !args[0].startsWith("-")) { cmdname = args[0]; args = args[1 .. $]; } else { if (help) { showHelp(commands, common_args); return 0; } cmdname = "run"; } auto command_args = new CommandArgs(args); if (cmdname == "help") { showHelp(commands, common_args); return 0; } // find the selected command Command cmd; foreach (grp; commands) foreach (c; grp.commands) if (c.name == cmdname) { cmd = c; break; } if (!cmd) { logError("Unknown command: %s", cmdname); writeln(); showHelp(commands, common_args); return 1; } // process command line options for the selected command try { cmd.prepare(command_args); enforceUsage(cmd.acceptsAppArgs || app_args.length == 0, cmd.name ~ " doesn't accept application arguments."); } catch (Throwable e) { logError("Error processing arguments: %s", e.msg); logDiagnostic("Full exception: %s", e.toString().sanitize); logInfo("Run 'dub help' for usage information."); return 1; } if (help) { showCommandHelp(cmd, command_args, common_args); return 0; } auto remaining_args = command_args.extractRemainingArgs(); if (remaining_args.any!(a => a.startsWith("-"))) { logError("Unknown command line flags: %s", remaining_args.filter!(a => a.startsWith("-")).array.join(" ")); logError(`Type "dub %s -h" to get a list of all supported flags.`, cmdname); return 1; } Dub dub; // initialize the root package if (!cmd.skipDubInitialization) { // initialize DUB auto package_suppliers = registry_urls.map!(url => cast(PackageSupplier)new RegistryPackageSupplier(URL(url))).array; dub = new Dub(package_suppliers, root_path); dub.dryRun = annotate; // make the CWD package available so that for example sub packages can reference their // parent package. try dub.packageManager.getOrLoadPackage(Path(root_path)); catch (Exception e) { logDiagnostic("No package found in current working directory."); } } // execute the command int rc; try { rc = cmd.execute(dub, remaining_args, app_args); } catch (UsageException e) { logError("%s", e.msg); logDebug("Full exception: %s", e.toString().sanitize); logInfo(`Run "dub %s -h" for more information about the "%s" command.`, cmdname, cmdname); return 1; } catch (Throwable e) { logError("Error executing command %s:", cmd.name); logError("%s", e.msg); logDebug("Full exception: %s", e.toString().sanitize); return 2; } if (!cmd.skipDubInitialization) dub.shutdown(); return rc; } class CommandArgs { struct Arg { Variant defaultValue; Variant value; string names; string[] helpText; } private { string[] m_args; Arg[] m_recognizedArgs; } this(string[] args) { m_args = "dummy" ~ args; } @property const(Arg)[] recognizedArgs() { return m_recognizedArgs; } void getopt(T)(string names, T* var, string[] help_text = null) { foreach (ref arg; m_recognizedArgs) if (names == arg.names) { assert(help_text is null); *var = arg.value.get!T; return; } assert(help_text.length > 0); Arg arg; arg.defaultValue = *var; arg.names = names; arg.helpText = help_text; m_args.getopt(config.passThrough, names, var); arg.value = *var; m_recognizedArgs ~= arg; } void dropAllArgs() { m_args = null; } string[] extractRemainingArgs() { auto ret = m_args[1 .. $]; m_args = null; return ret; } } class Command { string name; string argumentsPattern; string description; string[] helpText; bool acceptsAppArgs; bool hidden = false; // used for deprecated commands bool skipDubInitialization = false; abstract void prepare(scope CommandArgs args); abstract int execute(Dub dub, string[] free_args, string[] app_args); } struct CommandGroup { string caption; Command[] commands; this(string caption, Command[] commands...) { this.caption = caption; this.commands = commands.dup; } } /******************************************************************************/ /* INIT */ /******************************************************************************/ class InitCommand : Command { private{ string m_buildType = "minimal"; } this() { this.name = "init"; this.argumentsPattern = "[<directory> [<dependency>...]]"; this.description = "Initializes an empty package skeleton"; this.helpText = [ "Initializes an empty package of the specified type in the given directory. By default, the current working dirctory is used." ]; } override void prepare(scope CommandArgs args) { args.getopt("t|type", &m_buildType, [ "Set the type of project to generate. Available types:", "", "minimal - simple \"hello world\" project (default)", "vibe.d - minimal HTTP server based on vibe.d", "deimos - skeleton for C header bindings", ]); } override int execute(Dub dub, string[] free_args, string[] app_args) { string dir; enforceUsage(app_args.empty, "Unexpected application arguments."); if (free_args.length) { dir = free_args[0]; free_args = free_args[1 .. $]; } //TODO: Remove this block in next version // Checks if argument uses current method of specifying project type. if (free_args.length) { if (["vibe.d", "deimos", "minimal"].canFind(free_args[0])) { m_buildType = free_args[0]; free_args = free_args[1 .. $]; logInfo("Deprecated use of init type. Use --type=[vibe.d | deimos | minimal] in future."); } } dub.createEmptyPackage(Path(dir), free_args, m_buildType); return 0; } } /******************************************************************************/ /* GENERATE / BUILD / RUN / TEST / DESCRIBE */ /******************************************************************************/ abstract class PackageBuildCommand : Command { protected { string m_buildType; BuildMode m_buildMode; string m_buildConfig; string m_compilerName; string m_arch; string[] m_debugVersions; Compiler m_compiler; BuildPlatform m_buildPlatform; BuildSettings m_buildSettings; string m_defaultConfig; bool m_nodeps; bool m_forceRemove = false; } this() { m_compilerName = defaultCompiler(); } override void prepare(scope CommandArgs args) { args.getopt("b|build", &m_buildType, [ "Specifies the type of build to perform. Note that setting the DFLAGS environment variable will override the build type with custom flags.", "Possible names:", " debug (default), plain, release, release-nobounds, unittest, profile, docs, ddox, cov, unittest-cov and custom types" ]); args.getopt("c|config", &m_buildConfig, [ "Builds the specified configuration. Configurations can be defined in dub.json" ]); args.getopt("compiler", &m_compilerName, [ "Specifies the compiler binary to use (can be a path).", "Arbitrary pre- and suffixes to the identifiers below are recognized (e.g. ldc2 or dmd-2.063) and matched to the proper compiler type:", " "~["dmd", "gdc", "ldc", "gdmd", "ldmd"].join(", "), "Default value: "~m_compilerName, ]); args.getopt("a|arch", &m_arch, [ "Force a different architecture (e.g. x86 or x86_64)" ]); args.getopt("d|debug", &m_debugVersions, [ "Define the specified debug version identifier when building - can be used multiple times" ]); args.getopt("nodeps", &m_nodeps, [ "Do not check/update dependencies before building" ]); args.getopt("force-remove", &m_forceRemove, [ "Force deletion of fetched packages with untracked files when upgrading" ]); args.getopt("build-mode", &m_buildMode, [ "Specifies the way the compiler and linker are invoked. Valid values:", " separate (default), allAtOnce, singleFile" ]); } protected void setupPackage(Dub dub, string package_name) { m_compiler = getCompiler(m_compilerName); m_buildPlatform = m_compiler.determinePlatform(m_buildSettings, m_compilerName, m_arch); m_buildSettings.addDebugVersions(m_debugVersions); m_defaultConfig = null; enforce (loadSpecificPackage(dub, package_name), "Failed to load package."); if (m_buildConfig.length != 0 && !dub.configurations.canFind(m_buildConfig)) { string msg = "Unknown build configuration: "~m_buildConfig; enum distance = 3; if (auto match = dub.configurations.getClosestMatch(m_buildConfig, distance)) msg ~= ". Did you mean '" ~ match ~ "'?"; enforce(0, msg); } if (m_buildType.length == 0) { if (environment.get("DFLAGS")) m_buildType = "$DFLAGS"; else m_buildType = "debug"; } if (!m_nodeps) { // TODO: only upgrade(select) if necessary, only upgrade(upgrade) every now and then // retrieve missing packages logDiagnostic("Checking for missing dependencies."); dub.upgrade(UpgradeOptions.select); // check for updates logDiagnostic("Checking for upgrades."); dub.upgrade(UpgradeOptions.upgrade|UpgradeOptions.printUpgradesOnly|UpgradeOptions.useCachedResult); } dub.project.validate(); } private bool loadSpecificPackage(Dub dub, string package_name) { Package pack; if (!package_name.empty) { // load package in root_path to enable searching for sub packages if (loadCwdPackage(dub, null, false)) { if (package_name.startsWith(":")) package_name = dub.projectName ~ package_name; } pack = dub.packageManager.getFirstPackage(package_name); enforce(pack, "Failed to find a package named '"~package_name~"'."); logInfo("Building package %s in %s", pack.name, pack.path.toNativeString()); dub.rootPath = pack.path; } if (!loadCwdPackage(dub, pack, true)) return false; return true; } private bool loadCwdPackage(Dub dub, Package pack, bool warn_missing_package) { if (warn_missing_package) { bool found = existsFile(dub.rootPath ~ "source/app.d"); if (!found) foreach (f; packageInfoFiles) if (existsFile(dub.rootPath ~ f.filename)) { found = true; break; } if (!found) { logInfo(""); logInfo("Neither a package description file, nor source/app.d was found in"); logInfo(dub.rootPath.toNativeString()); logInfo("Please run DUB from the root directory of an existing package, or run"); logInfo("\"dub init --help\" to get information on creating a new package."); logInfo(""); return false; } } if (pack) dub.loadPackage(pack); else dub.loadPackageFromCwd(); return true; } } class GenerateCommand : PackageBuildCommand { protected { string m_generator; bool m_rdmd = false; bool m_tempBuild = false; bool m_run = false; bool m_force = false; bool m_combined = false; bool m_printPlatform, m_printBuilds, m_printConfigs; } this() { this.name = "generate"; this.argumentsPattern = "<generator> [<package>]"; this.description = "Generates project files using the specified generator"; this.helpText = [ "Generates project files using one of the supported generators:", "", "visuald - VisualD project files", "sublimetext - SublimeText project file", "build - Builds the package directly", "", "An optional package name can be given to generate a different package than the root/CWD package." ]; } override void prepare(scope CommandArgs args) { super.prepare(args); args.getopt("combined", &m_combined, [ "Tries to build the whole project in a single compiler run." ]); args.getopt("print-builds", &m_printBuilds, [ "Prints the list of available build types" ]); args.getopt("print-configs", &m_printConfigs, [ "Prints the list of available configurations" ]); args.getopt("print-platform", &m_printPlatform, [ "Prints the identifiers for the current build platform as used for the build fields in dub.json" ]); } override int execute(Dub dub, string[] free_args, string[] app_args) { string package_name; if (!m_generator.length) { enforceUsage(free_args.length >= 1 && free_args.length <= 2, "Expected one or two arguments."); m_generator = free_args[0]; if (free_args.length >= 2) package_name = free_args[1]; } else { enforceUsage(free_args.length <= 1, "Expected one or zero arguments."); if (free_args.length >= 1) package_name = free_args[0]; } setupPackage(dub, package_name); if (m_printBuilds) { // FIXME: use actual package data logInfo("Available build types:"); foreach (tp; ["debug", "release", "unittest", "profile"]) logInfo(" %s", tp); logInfo(""); } m_defaultConfig = dub.project.getDefaultConfiguration(m_buildPlatform); if (m_printConfigs) { logInfo("Available configurations:"); foreach (tp; dub.configurations) logInfo(" %s%s", tp, tp == m_defaultConfig ? " [default]" : null); logInfo(""); } GeneratorSettings gensettings; gensettings.platform = m_buildPlatform; gensettings.config = m_buildConfig.length ? m_buildConfig : m_defaultConfig; gensettings.buildType = m_buildType; gensettings.buildMode = m_buildMode; gensettings.compiler = m_compiler; gensettings.buildSettings = m_buildSettings; gensettings.combined = m_combined; gensettings.run = m_run; gensettings.runArgs = app_args; gensettings.force = m_force; gensettings.rdmd = m_rdmd; gensettings.tempBuild = m_tempBuild; logDiagnostic("Generating using %s", m_generator); if (m_generator == "visuald-combined") { gensettings.combined = true; m_generator = "visuald"; logWarn(`The generator "visuald-combined" is deprecated, please use the --combined switch instead.`); } dub.generateProject(m_generator, gensettings); if (m_buildType == "ddox") dub.runDdox(gensettings.run); return 0; } } class BuildCommand : GenerateCommand { this() { this.name = "build"; this.argumentsPattern = "[<package>]"; this.description = "Builds a package (uses the main package in the current working directory by default)"; this.helpText = [ "Builds a package (uses the main package in the current working directory by default)" ]; } override void prepare(scope CommandArgs args) { args.getopt("rdmd", &m_rdmd, [ "Use rdmd instead of directly invoking the compiler" ]); args.getopt("f|force", &m_force, [ "Forces a recompilation even if the target is up to date" ]); super.prepare(args); m_generator = "build"; } override int execute(Dub dub, string[] free_args, string[] app_args) { return super.execute(dub, free_args, app_args); } } class RunCommand : BuildCommand { this() { this.name = "run"; this.argumentsPattern = "[<package>]"; this.description = "Builds and runs a package (default command)"; this.helpText = [ "Builds and runs a package (uses the main package in the current working directory by default)" ]; this.acceptsAppArgs = true; } override void prepare(scope CommandArgs args) { args.getopt("temp-build", &m_tempBuild, [ "Builds the project in the temp folder if possible." ]); super.prepare(args); m_run = true; } override int execute(Dub dub, string[] free_args, string[] app_args) { return super.execute(dub, free_args, app_args); } } class TestCommand : PackageBuildCommand { private { string m_mainFile; bool m_combined = false; bool m_force = false; } this() { this.name = "test"; this.argumentsPattern = "[<package>]"; this.description = "Executes the tests of the selected package"; this.helpText = [ `Builds the package and executes all contained unit tests.`, ``, `If no explicit configuration is given, an existing "unittest" ` ~ `configuration will be preferred for testing. If none exists, the ` ~ `first library type configuration will be used, and if that doesn't ` ~ `exist either, the first executable configuration is chosen.`, ``, `When a custom main file (--main-file) is specified, only library ` ~ `configurations can be used. Otherwise, depending on the type of ` ~ `the selected configuration, either an existing main file will be ` ~ `used (and needs to be properly adjusted to just run the unit ` ~ `tests for 'version(unittest)'), or DUB will generate one for ` ~ `library type configurations.`, ``, `Finally, if the package contains a dependency to the "tested" ` ~ `package, the automatically generated main file will use it to ` ~ `run the unit tests.` ]; this.acceptsAppArgs = true; m_buildType = "unittest"; } override void prepare(scope CommandArgs args) { args.getopt("main-file", &m_mainFile, [ "Specifies a custom file containing the main() function to use for running the tests." ]); args.getopt("combined", &m_combined, [ "Tries to build the whole project in a single compiler run." ]); args.getopt("f|force", &m_force, [ "Forces a recompilation even if the target is up to date" ]); bool coverage = false; args.getopt("coverage", &coverage, [ "Enables code coverage statistics to be generated." ]); if (coverage) m_buildType = "unittest-cov"; super.prepare(args); } override int execute(Dub dub, string[] free_args, string[] app_args) { string package_name; enforceUsage(free_args.length <= 1, "Expected one or zero arguments."); if (free_args.length >= 1) package_name = free_args[0]; setupPackage(dub, package_name); GeneratorSettings settings; settings.platform = m_buildPlatform; settings.compiler = getCompiler(m_buildPlatform.compilerBinary); settings.buildType = m_buildType; settings.buildMode = m_buildMode; settings.buildSettings = m_buildSettings; settings.combined = m_combined; settings.force = m_force; settings.run = true; settings.runArgs = app_args; dub.testProject(settings, m_buildConfig, Path(m_mainFile)); return 0; } } class DescribeCommand : PackageBuildCommand { this() { this.name = "describe"; this.argumentsPattern = "[<package>]"; this.description = "Prints a JSON description of the project and its dependencies"; this.helpText = [ "Prints a JSON build description for the root package an all of their dependencies in a format similar to a JSON package description file. This is useful mostly for IDEs.", "All usual options that are also used for build/run/generate apply." ]; } override void prepare(scope CommandArgs args) { super.prepare(args); } override int execute(Dub dub, string[] free_args, string[] app_args) { // disable all log output and use "writeln" to output the JSON description auto ll = getLogLevel(); setLogLevel(LogLevel.none); scope (exit) setLogLevel(ll); string package_name; enforceUsage(free_args.length <= 1, "Expected one or zero arguments."); if (free_args.length >= 1) package_name = free_args[0]; setupPackage(dub, package_name); m_defaultConfig = dub.project.getDefaultConfiguration(m_buildPlatform); dub.describeProject(m_buildPlatform, m_buildConfig.length ? m_buildConfig : m_defaultConfig); return 0; } } class CleanCommand : Command { private { bool m_allPackages; } this() { this.name = "clean"; this.argumentsPattern = "[<package>]"; this.description = "Removes intermediate build files and cached build results"; this.helpText = [ "This command removes any cached build files of the given package(s). The final target file, as well as any copyFiles are currently not removed.", "Without arguments, the package in the current working directory will be cleaned." ]; } override void prepare(scope CommandArgs args) { args.getopt("all-packages", &m_allPackages, [ "Cleans up *all* known packages (dub list)" ]); } override int execute(Dub dub, string[] free_args, string[] app_args) { enforceUsage(free_args.length <= 1, "Expected one or zero arguments."); enforceUsage(app_args.length == 0, "Application arguments are not supported for the clean command."); enforceUsage(!m_allPackages || !free_args.length, "The --all-packages flag may not be used together with an explicit package name."); enforce(free_args.length == 0, "Cleaning a specific package isn't possible right now."); if (m_allPackages) { foreach (p; dub.packageManager.getPackageIterator()) dub.cleanPackage(p.path); } else { dub.cleanPackage(dub.rootPath); } return 0; } } /******************************************************************************/ /* FETCH / REMOVE / UPGRADE */ /******************************************************************************/ class UpgradeCommand : Command { private { bool m_prerelease = false; bool m_forceRemove = false; bool m_missingOnly = false; bool m_verify = false; } this() { this.name = "upgrade"; this.argumentsPattern = "[<package>]"; this.description = "Forces an upgrade of all dependencies"; this.helpText = [ "Upgrades all dependencies of the package by querying the package registry(ies) for new versions.", "", "This will also update the versions stored in the selections file ("~SelectedVersions.defaultFile~") accordingly.", "", "If a package specified, (only) that package will be upgraded. Otherwise all direct and indirect dependencies of the current package will get upgraded." ]; } override void prepare(scope CommandArgs args) { args.getopt("prerelease", &m_prerelease, [ "Uses the latest pre-release version, even if release versions are available" ]); args.getopt("force-remove", &m_forceRemove, [ "Force deletion of fetched packages with untracked files" ]); args.getopt("verify", &m_verify, [ "Updates the project and performs a build. If successfull, rewrites the selected versions file <to be implemeted>." ]); args.getopt("missing-only", &m_missingOnly, [ "Performs an upgrade only for dependencies that don't yet have a version selected. This is also done automatically before each build." ]); } override int execute(Dub dub, string[] free_args, string[] app_args) { enforceUsage(free_args.length <= 1, "Unexpected arguments."); enforceUsage(app_args.length == 0, "Unexpected application arguments."); enforceUsage(!m_verify, "--verify is not yet implemented."); dub.loadPackageFromCwd(); logInfo("Upgrading project in %s", dub.projectPath.toNativeString()); auto options = UpgradeOptions.upgrade|UpgradeOptions.select; if (m_missingOnly) options &= ~UpgradeOptions.upgrade; if (m_prerelease) options |= UpgradeOptions.preRelease; if (m_forceRemove) options |= UpgradeOptions.forceRemove; enforceUsage(app_args.length == 0, "Upgrading a specific package is not yet implemented."); dub.upgrade(options); return 0; } } class FetchRemoveCommand : Command { protected { string m_version; bool m_forceRemove = false; bool m_system = false; bool m_local = false; } override void prepare(scope CommandArgs args) { args.getopt("version", &m_version, [ "Use the specified version/branch instead of the latest available match", "The remove command also accepts \"*\" here as a wildcard to remove all versions of the package from the specified location" ]); args.getopt("system", &m_system, ["Deprecated: Puts the package into the system wide package cache instead of the user local one."]); args.getopt("local", &m_local, ["Deprecated: Puts the package into a sub folder of the current working directory. Cannot be mixed with --system."]); args.getopt("force-remove", &m_forceRemove, [ "Force deletion of fetched packages with untracked files" ]); } abstract override int execute(Dub dub, string[] free_args, string[] app_args); } class FetchCommand : FetchRemoveCommand { this() { this.name = "fetch"; this.argumentsPattern = "<name>"; this.description = "Manually retrieves and caches a package"; this.helpText = [ "Note: Use the \"dependencies\" field in the package description file (e.g. dub.json) if you just want to use a certain package as a dependency, you don't have to explicitly fetch packages.", "", "Explicit retrieval/removal of packages is only needed when you want to put packages to a place where several applications can share these. If you just have an dependency to a package, just add it to your dub.json, dub will do the rest for you.", "", "Without specified options, placement/removal will default to a user wide shared location.", "", "Complete applications can be retrieved and run easily by e.g.", "$ dub fetch vibelog --local", "$ cd vibelog", "$ dub", "", "This will grab all needed dependencies and compile and run the application.", "", "Note: DUB does not do a system installation of packages. Packages are instead only registered within DUB's internal ecosystem. Generation of native system packages/installers may be added later as a separate feature." ]; } override void prepare(scope CommandArgs args) { super.prepare(args); } override int execute(Dub dub, string[] free_args, string[] app_args) { enforceUsage(!m_local || !m_system, "--local and --system are exclusive to each other."); enforceUsage(free_args.length == 1, "Expecting exactly one argument."); enforceUsage(app_args.length == 0, "Unexpected application arguments."); auto location = defaultPlacementLocation; if (m_local) { logWarn("--local is deprecated. Use --cache=local instead."); location = PlacementLocation.local; } else if (m_system) { logWarn("--system is deprecated. Use --cache=system instead."); location = PlacementLocation.system; } auto name = free_args[0]; FetchOptions fetchOpts; fetchOpts |= FetchOptions.forceBranchUpgrade; fetchOpts |= m_forceRemove ? FetchOptions.forceRemove : FetchOptions.none; if (m_version.length) dub.fetch(name, Dependency(m_version), location, fetchOpts); else { try { dub.fetch(name, Dependency(">=0.0.0"), location, fetchOpts); logInfo( "Please note that you need to use `dub run <pkgname>` " ~ "or add it to dependencies of your package to actually use/run it. " ~ "dub does not do actual installation of packages outside of its own ecosystem."); } catch(Exception e){ logInfo("Getting a release version failed: %s", e.msg); logInfo("Retry with ~master..."); dub.fetch(name, Dependency("~master"), location, fetchOpts); } } return 0; } } class InstallCommand : FetchCommand { this() { this.name = "install"; hidden = true; } override void prepare(scope CommandArgs args) { super.prepare(args); } override int execute(Dub dub, string[] free_args, string[] app_args) { warnRenamed("install", "fetch"); return super.execute(dub, free_args, app_args); } } class RemoveCommand : FetchRemoveCommand { this() { this.name = "remove"; this.argumentsPattern = "<name>"; this.description = "Removes a cached package"; this.helpText = [ "Removes a package that is cached on the local system." ]; } override void prepare(scope CommandArgs args) { super.prepare(args); } override int execute(Dub dub, string[] free_args, string[] app_args) { enforceUsage(free_args.length == 1, "Expecting exactly one argument."); enforceUsage(app_args.length == 0, "Unexpected application arguments."); auto package_id = free_args[0]; auto location = defaultPlacementLocation; if (m_local) { logWarn("--local is deprecated. Use --cache=local instead."); location = PlacementLocation.local; } else if (m_system) { logWarn("--system is deprecated. Use --cache=system instead."); location = PlacementLocation.system; } dub.remove(package_id, m_version, location, m_forceRemove); return 0; } } class UninstallCommand : RemoveCommand { this() { this.name = "uninstall"; hidden = true; } override void prepare(scope CommandArgs args) { super.prepare(args); } override int execute(Dub dub, string[] free_args, string[] app_args) { warnRenamed("uninstall", "remove"); return super.execute(dub, free_args, app_args); } } /******************************************************************************/ /* ADD/REMOVE PATH/LOCAL */ /******************************************************************************/ abstract class RegistrationCommand : Command { private { bool m_system; } override void prepare(scope CommandArgs args) { args.getopt("system", &m_system, [ "Register system-wide instead of user-wide" ]); } abstract override int execute(Dub dub, string[] free_args, string[] app_args); } class AddPathCommand : RegistrationCommand { this() { this.name = "add-path"; this.argumentsPattern = "<path>"; this.description = "Adds a default package search path"; this.helpText = ["Adds a default package search path"]; } override int execute(Dub dub, string[] free_args, string[] app_args) { enforceUsage(free_args.length == 1, "Missing search path."); dub.addSearchPath(free_args[0], m_system); return 0; } } class RemovePathCommand : RegistrationCommand { this() { this.name = "remove-path"; this.argumentsPattern = "<path>"; this.description = "Removes a package search path"; this.helpText = ["Removes a package search path"]; } override int execute(Dub dub, string[] free_args, string[] app_args) { enforceUsage(free_args.length == 1, "Expected one argument."); dub.removeSearchPath(free_args[0], m_system); return 0; } } class AddLocalCommand : RegistrationCommand { this() { this.name = "add-local"; this.argumentsPattern = "<path> [<version>]"; this.description = "Adds a local package directory (e.g. a git repository)"; this.helpText = ["Adds a local package directory (e.g. a git repository)"]; } override int execute(Dub dub, string[] free_args, string[] app_args) { enforceUsage(free_args.length == 1 || free_args.length == 2, "Expecting one or two arguments."); string ver = free_args.length == 2 ? free_args[1] : null; dub.addLocalPackage(free_args[0], ver, m_system); return 0; } } class RemoveLocalCommand : RegistrationCommand { this() { this.name = "remove-local"; this.argumentsPattern = "<path>"; this.description = "Removes a local package directory"; this.helpText = ["Removes a local package directory"]; } override int execute(Dub dub, string[] free_args, string[] app_args) { enforceUsage(free_args.length == 1, "Missing path to package."); dub.removeLocalPackage(free_args[0], m_system); return 0; } } class ListCommand : Command { this() { this.name = "list"; this.argumentsPattern = ""; this.description = "Prints a list of all local packages dub is aware of"; this.helpText = [ "Prints a list of all local packages. This includes all cached packages (user or system wide), all packages in the package search paths (\"dub add-path\") and all manually registered packages (\"dub add-local\")." ]; } override void prepare(scope CommandArgs args) {} override int execute(Dub dub, string[] free_args, string[] app_args) { logInfo("Packages present in the system and known to dub:"); foreach (p; dub.packageManager.getPackageIterator()) logInfo(" %s %s: %s", p.name, p.ver, p.path.toNativeString()); logInfo(""); return 0; } } class ListInstalledCommand : ListCommand { this() { this.name = "list-installed"; hidden = true; } override void prepare(scope CommandArgs args) { super.prepare(args); } override int execute(Dub dub, string[] free_args, string[] app_args) { warnRenamed("list-installed", "list"); return super.execute(dub, free_args, app_args); } } /******************************************************************************/ /* OVERRIDES */ /******************************************************************************/ class AddOverrideCommand : Command { private { bool m_system = false; } this() { this.name = "add-override"; this.argumentsPattern = "<package> <version-spec> <target-path/target-version>"; this.description = "Adds a new package override."; this.helpText = [ ]; } override void prepare(scope CommandArgs args) { args.getopt("system", &m_system, [ "Register system-wide instead of user-wide" ]); } override int execute(Dub dub, string[] free_args, string[] app_args) { enforceUsage(app_args.length == 0, "Unexpected application arguments."); enforceUsage(free_args.length == 3, "Expected three arguments, not "~free_args.length.to!string); auto scope_ = m_system ? LocalPackageType.system : LocalPackageType.user; auto pack = free_args[0]; auto ver = Dependency(free_args[1]); if (existsFile(Path(free_args[2]))) { auto target = Path(free_args[2]); dub.packageManager.addOverride(scope_, pack, ver, target); logInfo("Added override %s %s => %s", pack, ver, target); } else { auto target = Version(free_args[2]); dub.packageManager.addOverride(scope_, pack, ver, target); logInfo("Added override %s %s => %s", pack, ver, target); } return 0; } } class RemoveOverrideCommand : Command { private { bool m_system = false; } this() { this.name = "remove-override"; this.argumentsPattern = "<package> <version-spec>"; this.description = "Removes an existing package override."; this.helpText = [ ]; } override void prepare(scope CommandArgs args) { args.getopt("system", &m_system, [ "Register system-wide instead of user-wide" ]); } override int execute(Dub dub, string[] free_args, string[] app_args) { enforceUsage(app_args.length == 0, "Unexpected application arguments."); enforceUsage(free_args.length == 2, "Expected two arguments, not "~free_args.length.to!string); auto scope_ = m_system ? LocalPackageType.system : LocalPackageType.user; dub.packageManager.removeOverride(scope_, free_args[0], Dependency(free_args[1])); return 0; } } class ListOverridesCommand : Command { this() { this.name = "list-overrides"; this.argumentsPattern = ""; this.description = "Prints a list of all local package overrides"; this.helpText = [ "Prints a list of all overriden packages added via \"dub add-override\"." ]; } override void prepare(scope CommandArgs args) {} override int execute(Dub dub, string[] free_args, string[] app_args) { void printList(in PackageOverride[] overrides, string caption) { if (overrides.length == 0) return; logInfo("# %s", caption); foreach (ovr; overrides) { if (!ovr.targetPath.empty) logInfo("%s %s => %s", ovr.package_, ovr.version_, ovr.targetPath); else logInfo("%s %s => %s", ovr.package_, ovr.version_, ovr.targetVersion); } } printList(dub.packageManager.getOverrides(LocalPackageType.user), "User wide overrides"); printList(dub.packageManager.getOverrides(LocalPackageType.system), "System wide overrides"); return 0; } } /******************************************************************************/ /* Cache cleanup */ /******************************************************************************/ class CleanCachesCommand : Command { this() { this.name = "clean-caches"; this.argumentsPattern = ""; this.description = "Removes cached metadata"; this.helpText = [ "This command removes any cached metadata like the list of available packages and their latest version." ]; } override void prepare(scope CommandArgs args) {} override int execute(Dub dub, string[] free_args, string[] app_args) { dub.cleanCaches(); return 0; } } /******************************************************************************/ /* DUSTMITE */ /******************************************************************************/ class DustmiteCommand : PackageBuildCommand { private { int m_compilerStatusCode = int.min; int m_linkerStatusCode = int.min; int m_programStatusCode = int.min; string m_compilerRegex; string m_linkerRegex; string m_programRegex; string m_testPackage; bool m_combined; } this() { this.name = "dustmite"; this.argumentsPattern = "<destination-path>"; this.acceptsAppArgs = true; this.description = "Create reduced test cases for build errors"; this.helpText = [ "This command uses the Dustmite utility to isolate the cause of build errors in a DUB project.", "", "It will create a copy of all involved packages and run dustmite on this copy, leaving a reduced test case.", "", "Determining the desired error condition is done by checking the compiler/linker status code, as well as their output (stdout and stderr combined). If --program-status or --program-regex is given and the generated binary is an executable, it will be executed and its output will also be incorporated into the final decision." ]; } override void prepare(scope CommandArgs args) { args.getopt("compiler-status", &m_compilerStatusCode, ["The expected status code of the compiler run"]); args.getopt("compiler-regex", &m_compilerRegex, ["A regular expression used to match against the compiler output"]); args.getopt("linker-status", &m_linkerStatusCode, ["The expected status code of the liner run"]); args.getopt("linker-regex", &m_linkerRegex, ["A regular expression used to match against the linker output"]); args.getopt("program-status", &m_programStatusCode, ["The expected status code of the built executable"]); args.getopt("program-regex", &m_programRegex, ["A regular expression used to match against the program output"]); args.getopt("test-package", &m_testPackage, ["Perform a test run - usually only used internally"]); args.getopt("combined", &m_combined, ["Builds multiple packages with one compiler run"]); super.prepare(args); // speed up loading when in test mode if (m_testPackage.length) skipDubInitialization = true; } override int execute(Dub dub, string[] free_args, string[] app_args) { if (m_testPackage.length) { dub = new Dub(Path(getcwd())); setupPackage(dub, m_testPackage); m_defaultConfig = dub.project.getDefaultConfiguration(m_buildPlatform); GeneratorSettings gensettings; gensettings.platform = m_buildPlatform; gensettings.config = m_buildConfig.length ? m_buildConfig : m_defaultConfig; gensettings.buildType = m_buildType; gensettings.compiler = m_compiler; gensettings.buildSettings = m_buildSettings; gensettings.combined = m_combined; gensettings.run = m_programStatusCode != int.min || m_programRegex.length; gensettings.runArgs = app_args; gensettings.force = true; gensettings.compileCallback = check(m_compilerStatusCode, m_compilerRegex); gensettings.linkCallback = check(m_linkerStatusCode, m_linkerRegex); gensettings.runCallback = check(m_programStatusCode, m_programRegex); try dub.generateProject("build", gensettings); catch (DustmiteMismatchException) { logInfo("Dustmite test doesn't match."); return 3; } catch (DustmiteMatchException) { logInfo("Dustmite test matches."); return 0; } } else { enforceUsage(free_args.length == 1, "Expected destination path."); auto path = Path(free_args[0]); path.normalize(); enforceUsage(path.length > 0, "Destination path must not be empty."); if (!path.absolute) path = Path(getcwd()) ~ path; enforceUsage(!path.startsWith(dub.rootPath), "Destination path must not be a sub directory of the tested package!"); setupPackage(dub, null); auto prj = dub.project; if (m_buildConfig.empty) m_buildConfig = prj.getDefaultConfiguration(m_buildPlatform); void copyFolderRec(Path folder, Path dstfolder) { mkdirRecurse(dstfolder.toNativeString()); foreach (de; iterateDirectory(folder.toNativeString())) { if (de.name.startsWith(".")) continue; if (de.isDirectory) { copyFolderRec(folder ~ de.name, dstfolder ~ de.name); } else { if (de.name.endsWith(".o") || de.name.endsWith(".obj")) continue; if (de.name.endsWith(".exe")) continue; try copyFile(folder ~ de.name, dstfolder ~ de.name); catch (Exception e) { logWarn("Failed to copy file %s: %s", (folder ~ de.name).toNativeString(), e.msg); } } } } bool[string] visited; foreach (pack_; prj.getTopologicalPackageList()) { auto pack = pack_.basePackage; if (pack.name in visited) continue; visited[pack.name] = true; logInfo("Copy package '%s' to destination folder...", pack.name); copyFolderRec(pack.path, path ~ pack.name); } logInfo("Executing dustmite..."); auto testcmd = format("dub dustmite --vquiet --test-package=%s", prj.name); if (m_compilerStatusCode != int.min) testcmd ~= format(" --compiler-status=%s", m_compilerStatusCode); if (m_compilerRegex.length) testcmd ~= format(" \"--compiler-regex=%s\"", m_compilerRegex); if (m_linkerStatusCode != int.min) testcmd ~= format(" --linker-status=%s", m_linkerStatusCode); if (m_linkerRegex.length) testcmd ~= format(" \"--linker-regex=%s\"", m_linkerRegex); if (m_programStatusCode != int.min) testcmd ~= format(" --program-status=%s", m_programStatusCode); if (m_programRegex.length) testcmd ~= format(" \"--program-regex=%s\"", m_programRegex); if (m_combined) testcmd ~= " --combined"; // TODO: pass all original parameters auto dmpid = spawnProcess(["dustmite", path.toNativeString(), testcmd]); return dmpid.wait(); } return 0; } void delegate(int, string) check(int code_match, string regex_match) { return (code, output) { import std.encoding; import std.regex; if (code_match != int.min && code != code_match) { logInfo("Exit code %s doesn't match expected value %s", code, code_match); throw new DustmiteMismatchException; } if (regex_match.length > 0 && !match(output.sanitize, regex_match)) { logInfo("Output doesn't match regex:"); logInfo("%s", output); throw new DustmiteMismatchException; } if (code != 0 && code_match != int.min || regex_match.length > 0) { logInfo("Tool failed, but matched either exit code or output - counting as match."); throw new DustmiteMatchException; } }; } static class DustmiteMismatchException : Exception { this(string message = "", string file = __FILE__, int line = __LINE__, Throwable next = null) { super(message, file, line, next); } } static class DustmiteMatchException : Exception { this(string message = "", string file = __FILE__, int line = __LINE__, Throwable next = null) { super(message, file, line, next); } } } /******************************************************************************/ /* HELP */ /******************************************************************************/ private { enum shortArgColumn = 2; enum longArgColumn = 6; enum descColumn = 24; enum lineWidth = 80 - 1; } private void showHelp(in CommandGroup[] commands, CommandArgs common_args) { writeln( `USAGE: dub [<command>] [<options...>] [-- [<application arguments...>]] Manages the DUB project in the current directory. If the command is omitted, DUB will default to "run". When running an application, "--" can be used to separate DUB options from options passed to the application. Run "dub <command> --help" to get help for a specific command. You can use the "http_proxy" environment variable to configure a proxy server to be used for fetching packages. Available commands ==================`); foreach (grp; commands) { writeln(); writeWS(shortArgColumn); writeln(grp.caption); writeWS(shortArgColumn); writerep!'-'(grp.caption.length); writeln(); foreach (cmd; grp.commands) { if (cmd.hidden) continue; writeWS(shortArgColumn); writef("%s %s", cmd.name, cmd.argumentsPattern); auto chars_output = cmd.name.length + cmd.argumentsPattern.length + shortArgColumn + 1; if (chars_output < descColumn) { writeWS(descColumn - chars_output); } else { writeln(); writeWS(descColumn); } writeWrapped(cmd.description, descColumn, descColumn); } } writeln(); writeln(); writeln(`Common options`); writeln(`==============`); writeln(); writeOptions(common_args); writeln(); writefln("DUB version %s, built on %s", getDUBVersion(), __DATE__); } private void showCommandHelp(Command cmd, CommandArgs args, CommandArgs common_args) { writefln(`USAGE: dub %s %s [<options...>]%s`, cmd.name, cmd.argumentsPattern, cmd.acceptsAppArgs ? " [-- <application arguments...>]": null); writeln(); foreach (ln; cmd.helpText) ln.writeWrapped(); if (args.recognizedArgs.length) { writeln(); writeln(); writeln("Command specific options"); writeln("========================"); writeln(); writeOptions(args); } writeln(); writeln(); writeln("Common options"); writeln("=============="); writeln(); writeOptions(common_args); writeln(); writefln("DUB version %s, built on %s", getDUBVersion(), __DATE__); } private void writeOptions(CommandArgs args) { foreach (arg; args.recognizedArgs) { auto names = arg.names.split("|"); assert(names.length == 1 || names.length == 2); string sarg = names[0].length == 1 ? names[0] : null; string larg = names[0].length > 1 ? names[0] : names.length > 1 ? names[1] : null; if (sarg) { writeWS(shortArgColumn); writef("-%s", sarg); writeWS(longArgColumn - shortArgColumn - 2); } else writeWS(longArgColumn); size_t col = longArgColumn; if (larg) { if (arg.defaultValue.peek!bool) { writef("--%s", larg); col += larg.length + 2; } else { writef("--%s=VALUE", larg); col += larg.length + 8; } } if (col < descColumn) { writeWS(descColumn - col); } else { writeln(); writeWS(descColumn); } foreach (i, ln; arg.helpText) { if (i > 0) writeWS(descColumn); ln.writeWrapped(descColumn, descColumn); } } } private void writeWrapped(string string, size_t indent = 0, size_t first_line_pos = 0) { auto wrapped = string.wrap(lineWidth, getRepString!' '(first_line_pos), getRepString!' '(indent)); wrapped = wrapped[first_line_pos .. $]; foreach (ln; wrapped.splitLines()) writeln(ln); } private void writeWS(size_t num) { writerep!' '(num); } private void writerep(char ch)(size_t num) { write(getRepString!ch(num)); } private string getRepString(char ch)(size_t len) { static string buf; if (len > buf.length) buf ~= [ch].replicate(len-buf.length); return buf[0 .. len]; } /*** */ private void enforceUsage(bool cond, string text) { if (!cond) throw new UsageException(text); } private class UsageException : Exception { this(string message, string file = __FILE__, int line = __LINE__, Throwable next = null) { super(message, file, line, next); } } private void warnRenamed(string prev, string curr) { logWarn("The '%s' Command was renamed to '%s'. Please update your scripts.", prev, curr); }
D
module raydebugger.EasyPixbuf; import tango.util.log.Config; import raytracer.Colors; import gdk.Drawable; import gdk.Pixbuf; class EasyPixbuf: Pixbuf, ColorPixmap { public int width; public int height; ubyte[] pixels; int rowstride; int nChannels; public this(GdkPixbuf *gdkPixbuf) { super(gdkPixbuf); } public this(Drawable src, int srcX, int srcY, int width, int height) { super(src, srcX, srcY, width, height); this.width = super.getWidth(); this.height = super.getHeight(); rowstride = super.getRowstride(); ubyte *pixelsPtr = cast (ubyte*) super.getPixels(); pixels = pixelsPtr[0 .. height * rowstride]; nChannels = super.getNChannels(); assert(super.getBitsPerSample() == 8); } public this(int width, int height, bool hasAlpha = false) { super(GdkColorspace.RGB, hasAlpha, 8, width, height); this.width = width; this.height = height; rowstride = super.getRowstride(); ubyte *pixelsPtr = cast (ubyte*) super.getPixels(); pixels = pixelsPtr[0 .. height * rowstride]; nChannels = super.getNChannels(); } public override EasyPixbuf copy() { Pixbuf newPixbuf = super.copy(); return new EasyPixbuf(cast(GdkPixbuf*) newPixbuf.getObjectGStruct()); } public final int getWidth() { return width; } public final int getHeight() { return height; } public final Colors getPixelColor(int x, int y) { ubyte red, green, blue; getPixelColor(x, y, red, green, blue); return Colors(red / 255.0, green / 255.0, blue / 255.0, 0); } public final void getPixelColor(int x, int y, out ubyte red, out ubyte green, out ubyte blue) { int pos = y * rowstride + x * nChannels; ubyte[] pixel = pixels[pos .. pos+3]; red = pixel[0]; green = pixel[1]; blue = pixel[2]; } public final void setPixelColor(int x, int y, Colors color) { setPixelColor(x, y, cast (ubyte) (color.R * 255), cast (ubyte) (color.G * 255), cast (ubyte) (color.B * 255)); } public final void setPixelColor(int x, int y, ubyte red, ubyte green, ubyte blue) { int pos = y * rowstride + x * nChannels; ubyte[] pixel = pixels[pos .. pos+3]; pixel[0] = red; pixel[1] = green; pixel[2] = blue; } public final void setPixelAlpha(int x, int y, ubyte alpha) { int pos = y * rowstride + x * nChannels; ubyte[] pixel = pixels[pos .. pos+4]; pixel[3] = alpha; } public final void blendPixelColor(int x, int y, Colors color, double alpha) { blendPixelColor(x, y, cast (ubyte) (color.R * 255), cast (ubyte) (color.G * 255), cast (ubyte) (color.B * 255), cast (ubyte) (alpha * 255)); } public final void blendPixelColor(int x, int y, ubyte red, ubyte green, ubyte blue, ubyte alpha) { ubyte dstRed, dstGreen, dstBlue; double fAlpha = cast(double) alpha / 255; getPixelColor(x, y, dstRed, dstGreen, dstBlue); ubyte finalRed = cast(ubyte) (red * fAlpha + dstRed * (1 - fAlpha)); ubyte finalGreen = cast(ubyte) (green * fAlpha + dstGreen * (1 - fAlpha)); ubyte finalBlue = cast(ubyte) (blue * fAlpha + dstBlue * (1 - fAlpha)); setPixelColor(x, y, finalRed, finalGreen, finalBlue); } }
D
/Users/DanielChang/Documents/Vapor/Hello/.build/debug/Leaf.build/LeafComponent.swift.o : /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Argument.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Byte+Leaf.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Constants.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Context.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/HTMLEscape.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Leaf.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/LeafComponent.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/LeafError.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Link.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/List.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Node+Rendered.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/NSData+File.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Parameter.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Stem+Render.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Stem+Spawn.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Stem.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Buffer/Buffer+Leaf.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Buffer/Buffer.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Buffer/BufferProtocol.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/BasicTag.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Tag.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/TagTemplate.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Else.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Embed.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Equal.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Export.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Extend.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/If.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Import.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Index.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Loop.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Raw.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Uppercased.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Variable.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/DanielChang/Documents/Vapor/Hello/.build/debug/Core.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/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Users/DanielChang/Documents/Vapor/Hello/.build/debug/libc.swiftmodule /Users/DanielChang/Documents/Vapor/Hello/.build/debug/Node.swiftmodule /Users/DanielChang/Documents/Vapor/Hello/.build/debug/PathIndexable.swiftmodule /Users/DanielChang/Documents/Vapor/Hello/.build/debug/Polymorphic.swiftmodule /Users/DanielChang/Documents/Vapor/Hello/.build/debug/Leaf.build/LeafComponent~partial.swiftmodule : /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Argument.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Byte+Leaf.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Constants.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Context.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/HTMLEscape.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Leaf.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/LeafComponent.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/LeafError.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Link.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/List.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Node+Rendered.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/NSData+File.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Parameter.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Stem+Render.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Stem+Spawn.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Stem.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Buffer/Buffer+Leaf.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Buffer/Buffer.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Buffer/BufferProtocol.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/BasicTag.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Tag.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/TagTemplate.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Else.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Embed.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Equal.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Export.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Extend.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/If.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Import.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Index.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Loop.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Raw.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Uppercased.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Variable.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/DanielChang/Documents/Vapor/Hello/.build/debug/Core.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/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Users/DanielChang/Documents/Vapor/Hello/.build/debug/libc.swiftmodule /Users/DanielChang/Documents/Vapor/Hello/.build/debug/Node.swiftmodule /Users/DanielChang/Documents/Vapor/Hello/.build/debug/PathIndexable.swiftmodule /Users/DanielChang/Documents/Vapor/Hello/.build/debug/Polymorphic.swiftmodule /Users/DanielChang/Documents/Vapor/Hello/.build/debug/Leaf.build/LeafComponent~partial.swiftdoc : /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Argument.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Byte+Leaf.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Constants.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Context.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/HTMLEscape.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Leaf.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/LeafComponent.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/LeafError.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Link.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/List.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Node+Rendered.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/NSData+File.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Parameter.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Stem+Render.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Stem+Spawn.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Stem.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Buffer/Buffer+Leaf.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Buffer/Buffer.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Buffer/BufferProtocol.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/BasicTag.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Tag.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/TagTemplate.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Else.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Embed.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Equal.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Export.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Extend.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/If.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Import.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Index.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Loop.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Raw.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Uppercased.swift /Users/DanielChang/Documents/Vapor/Hello/Packages/Leaf-1.0.6/Sources/Leaf/Tag/Models/Variable.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/DanielChang/Documents/Vapor/Hello/.build/debug/Core.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/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Users/DanielChang/Documents/Vapor/Hello/.build/debug/libc.swiftmodule /Users/DanielChang/Documents/Vapor/Hello/.build/debug/Node.swiftmodule /Users/DanielChang/Documents/Vapor/Hello/.build/debug/PathIndexable.swiftmodule /Users/DanielChang/Documents/Vapor/Hello/.build/debug/Polymorphic.swiftmodule
D
/* 780.d ** ** Paradigm for Jeff's MT FEF experiment ** This paradigm includes: ** 1) asl calibration ** 2) passive fixation with (or without) a dots field ** ** created by jcl 3/16/08 */ #include "rexHdr.h" #include "paradigm_rec.h" #include "toys.h" #include "lcode.h" /* PRIVATE data structures */ /* GLOBAL VARIABLES */ static _PRrecord gl_rec = NULL; /* KA-HU-NA */ /* for now, allocate these here... */ MENU umenus[30]; RTVAR rtvars[15]; USER_FUNC ufuncs[15]; /* ROUTINES */ /* Macros */ #define PRV(n) pl_list_get_v(gl_rec->prefs_menu, (n)) #define TIMV(n) pl_list_get_v(gl_rec->trialP->task->task_menus->lists[0],(n)) #define TTMV(n) pl_list_get_v(gl_rec->trialP->task->task_menus->lists[1],(n)) /* **** INITIALIZATION routines */ /* ROUTINE: autoinit ** ** Initialize gl_rec. This will automatically ** set up the menus, etc. */ void autoinit(void) { printf("autoinit\n"); fflush(stdout); gl_rec = pr_initV(0, 0, umenus, NULL, rtvars, pl_list_initV("rtvars", 0, 1, "angle", 0, 1.0, NULL), ufuncs, "asl", 1, "fixd", 1, "ft", 1, NULL); } /* ROUTINE: rinitf ** ** initialize at first pass or at r s from keyboard */ void rinitf(void) { static int first_time = 1; printf("rinit\n"); fflush(stdout); /* This stuff needs to be done only once, but also ** needs to be done after the clock has started ** (so do NOT put it up in autoinit). */ if(first_time) { /* do this once */ first_time = 0; #define WIND0 0 #define WIND1 1 #define EYEH_SIG 0 #define EYEV_SIG 1 /* initialize interface (window) parameters */ wd_src_check(WIND0, WD_SIGNAL, EYEH_SIG, WD_SIGNAL, EYEV_SIG); wd_src_pos (WIND0, WD_DIRPOS, 0, WD_DIRPOS, 0); wd_cntrl (WIND0, WD_ON); wd_src_check(WIND1, WD_SIGNAL, EYEH_SIG, WD_SIGNAL, EYEV_SIG); wd_src_pos (WIND1, WD_DIRPOS, 0, WD_DIRPOS, 0); wd_cntrl (WIND1, WD_ON); /* init the screen */ pr_setup(); } } /* ROUTINE: start_trial ** */ int start_trial(void) { int task_index = pr_get_task_index(); /* No dynamic stimuli, so make draw_flag=3 the default. ** This draws each command ONCE */ dx_set_flags(DXF_D3); /* set rtvars and other things... */ if(task_index >= 3) { /* Task: countermand */ pr_set_rtvar("angle", PL_L2PV(gl_rec->trialP->list, 0)); } else if(task_index >= 1) { /* Task: ft */ pr_set_rtvar("angle", PL_L2PV(gl_rec->trialP->list, 0)); } else { /* Task: ASL */ pr_set_rtvar("angle", NULLI); } return(0); } /* ROUTINE: start_fixd ** set timing parameters for fixation+dots task */ int start_fixd(void) { return(0); } /* ROUTINE: set_fixtime ** set required fixation time for fixation task */ int set_fixtime(void) { timer_set1(0, 0, 0, 0, TTMV("fix_time"), 0); return(0); } /* ROUTINE: do_calibration ** ** Returns 1 if doing calibration (ASL task) */ int do_calibration(void) { return(pr_get_task_index() == 0 && pr_get_task_menu_value("setup", "Cal0/Val1", 0) == 0); } /* ROUTINE: show_error ** */ int show_error(long error_type) { if(error_type == 0) printf("Bad task index (%d)\n", pr_get_task_index()); return(0); } /* ROUTINE: set_reward int set_reward(void) { if (pr_get_task_index()==1) pr_set_reward(TTMV("#_reward"), PRV("Reward_on_time"), PRV("Reward_off_time"), TTMV("#_beep"), 58, 100); else pr_set_reward(1, PRV("Reward_on_time"), PRV("Reward_off_time"), 1, 58, 100); } */ /* THE STATE SET */ %% id 780 restart rinitf main_set { status ON begin first: to prewait /* ** First wait time, which can be used to add ** a delay after reset states (e.g., fixation break) */ prewait: do timer_set1(0,100,600,200,0,0) to loop on +MET % timer_check1 /* ** Start the loop! ** Note that the real workhorse here is pr_next_trial, ** called in go. It calls the task-specific ** "get trial" and "set trial" methods, ** and drops STARTCD and LISTDONECD, as ** appropriate. ** */ loop: do timer_set1(0,100,600,200,0,0) to pause on +PSTOP & softswitch to go on +MET % timer_check1 pause: to go on -PSTOP & softswitch go: do pr_toggle_file(1) to trstart_trial trstart_trial: to trstart on MET % pr_start_trial to loop trstart: do start_trial() to fpshow /* Show fixation point */ fpshow: do dx_show_fp(FPONCD, 0, 4, 4, 2, 2); to fpwinpos on DX_MSG % dx_check fpwinpos: time 20 /* takes time to settle window */ do dx_position_window(40, 40, 0, 0, 0) to calstart on 1 % do_calibration to fpwait /* CALIBRATION TASK ** Check for joystick button press indicating a correct fixation ** missed targets are scored as NC in order to be shown again later */ calstart: time 5000 to calacc on 0 % dio_check_joybut to calfpchange calfpchange: to calstart on 1 % dx_change_fp to ncerr calacc: do ec_send_code(ACCEPTCAL) to correct /* Wait for fixation */ fpwait: time 5000 to fpset on -WD0_XY & eyeflag to fpchange fpchange: to fpwait on 1 % dx_change_fp to fpnofix fpnofix: /* failed to attain fixation */ do pr_score_trial(kNoFix,0,1) to finish fpset: time 250 /* give gaze time to settle into place (fixation) */ to fpwait on +WD0_XY & eyeflag to fpwin2 fpwin2: time 20 /* again time to settle window */ do dx_position_window(20, 20, -1, 1, 0) to taskjmp /* Jump to task-specific statelists */ taskjmp: to t0fp on 0 % pr_get_task_index to t1fp on 1 % pr_get_task_index to t2fp on 2 % pr_get_task_index to badtask badtask: do show_error(0) to finish /* Task 0 is asl .. we get here in "validate" mode. ** Simple fixation only. */ t0fp: do dx_show_fp(FPONCD, 0, 6, 6, 2, 2); to t0wait1 on DX_MSG % dx_check t0wait1: do timer_set1(1000, 100, 600, 200, 0, 0) to t0winpos on MET % timer_check1 t0winpos: time 20 do dx_position_window(10,10,-1,0,0) to correct /* Task 1 is a simple fixation task: ** change fp to standard diameter/color ** wait ** check for broken fixation ** reward */ t1fp: do start_fixd() to t1showfp t1showfp: do dx_show_fp(FPONCD, 0, 6, 6, 2, 2); to t1wait1 on DX_MSG % dx_check t1wait1: do set_fixtime() to fixbreak on +WD0_XY & eyeflag to t1fpoff on MET % timer_check1 t1fpoff: do dx_toggle2(FPOFFCD, 0, 0, 1000, NULLI, NULLI); to t1fixdone on DX_MSG % dx_check t1fixdone: to correct /* Task 2 is visually-guided saccade: ** change fp to standard diameter/color ** wait1 ** show target (object 1) ** wait2 ** turn off fp ** STOP CHECKING FOR FIX BREAKS AND ** START CHECKING FOR SACCADES ** wait1 ** change f/t 1 ** wait2 */ t2fp: do dx_show_fp(FPONCD, 0, 4, 4, 2, 2); to t2wait1 on DX_MSG % dx_check t2wait1: do timer_set1(1000, 80, 200, 50, 100, 0) to t2targon on MET % timer_check1 t2targon: do dx_toggle2(TARGONCD, 1, 1, 1000, NULLI, NULLI); to t2twinpos1 on DX_MSG % dx_check t2twinpos1: time 20 do dx_position_window(50,50,1,0,1) to t2wait2 t2wait2: do timer_set1(0, 0, 0, 0, 1000, 0) to fixbreak on +WD0_XY & eyeflag to t2fpoff on MET % timer_check1 t2fpoff: do dx_toggle2(FPOFFCD, 0, 0, 1000, NULLI, NULLI); to t2twinpos2 on DX_MSG % dx_check t2twinpos2: time 20 do dx_position_window(40,40,1,0,1) to t2checksac1 t2checksac1: do timer_set1(0, 0, 0, 0, 500, 0) to t2checksac2 on -WD1_XY & eyeflag to t2ncerr on MET % timer_check1 t2checksac2: do timer_set1(0, 0, 0, 0, 50, 0) to t2ncerr on +WD1_XY & eyeflag to t2correct on MET % timer_check1 t2ncerr: do dx_toggle2(TARGOFFCD, 0, 1, 1000, NULLI, NULLI); to ncerr on DX_MSG % dx_check t2correct: do dx_toggle2(TARGOFFCD, 0, 1, 1000, NULLI, NULLI); to correct on DX_MSG % dx_check /* OUTCOME STATES ** NCERR (No-Choice Error) ** ERROR ** CORRECT */ /* broken fixaton */ fixbreak: time 800 do pr_score_trial(kBrFix, 0, 1) to finish /* no choice */ ncerr: time 800 do pr_score_trial(kNC, 0, 1) to finish /* error */ error: time 800 do pr_score_trial(kError, 0, 1) to finish /* pref -- reward! */ correct: do pr_score_trial(kCorrect, 0, 1) to reward reward: do pr_set_reward(1, 100, 50, -1, 50, 50); to finish on 0 % pr_beep_reward finish: do pr_finish_trial() to loop abort list: finish }
D
/* * This file is part of gtkD. * * gtkD is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * gtkD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with gtkD; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // generated automatically - do not change // find conversion definition on APILookup.txt // implement new conversion functionalities on the wrap.utils pakage /* * Conversion parameters: * inFile = gdk-Threads.html * outPack = gdk * outFile = Threads * strct = * realStrct= * ctorStrct= * clss = * interf = * class Code: No * interface Code: No * template for: * extend = * implements: * prefixes: * omit structs: * omit prefixes: * omit code: * omit signals: * imports: * structWrap: * module aliases: * local aliases: * overrides: */ module gtkD.gdk.Threads; public import gtkD.gtkc.gdktypes; private import gtkD.gtkc.gdk; private import gtkD.glib.ConstructionException; /** */ /** * Initializes GDK so that it can be used from multiple threads * in conjunction with gdk_threads_enter() and gdk_threads_leave(). * g_thread_init() must be called previous to this function. * This call must be made before any use of the main loop from * GTK+; to be safe, call it before gtk_init(). */ public static void gdkThreadsInit() { // void gdk_threads_init (void); gdk_threads_init(); } /** * This macro marks the beginning of a critical section in which GDK and * GTK+ functions can be called safely and without causing race * conditions. Only one thread at a time can be in such a critial * section. */ public static void gdkThreadsEnter() { // void gdk_threads_enter (void); gdk_threads_enter(); } /** * Leaves a critical region begun with gdk_threads_enter(). */ public static void gdkThreadsLeave() { // void gdk_threads_leave (void); gdk_threads_leave(); } /** * Allows the application to replace the standard method that * GDK uses to protect its data structures. Normally, GDK * creates a single GMutex that is locked by gdk_threads_enter(), * and released by gdk_threads_leave(); using this function an * application provides, instead, a function enter_fn that is * called by gdk_threads_enter() and a function leave_fn that is * called by gdk_threads_leave(). * The functions must provide at least same locking functionality * as the default implementation, but can also do extra application * specific processing. * As an example, consider an application that has its own recursive * lock that when held, holds the GTK+ lock as well. When GTK+ unlocks * the GTK+ lock when entering a recursive main loop, the application * must temporarily release its lock as well. * Most threaded GTK+ apps won't need to use this method. * This method must be called before gdk_threads_init(), and cannot * be called multiple times. * Since 2.4 * Params: * enterFn = function called to guard GDK * leaveFn = function called to release the guard */ public static void gdkThreadsSetLockFunctions(GCallback enterFn, GCallback leaveFn) { // void gdk_threads_set_lock_functions (GCallback enter_fn, GCallback leave_fn); gdk_threads_set_lock_functions(enterFn, leaveFn); } /** * A wrapper for the common usage of gdk_threads_add_idle_full() * assigning the default priority, G_PRIORITY_DEFAULT_IDLE. * See gdk_threads_add_idle_full(). * Since 2.12 * Params: * data = data to pass to function * Returns: the ID (greater than 0) of the event source. */ public static uint gdkThreadsAddIdle(GSourceFunc funct, void* data) { // guint gdk_threads_add_idle (GSourceFunc function, gpointer data); return gdk_threads_add_idle(funct, data); } /** * Adds a function to be called whenever there are no higher priority * events pending. If the function returns FALSE it is automatically * removed from the list of event sources and will not be called again. * This variant of g_idle_add_full() calls function with the GDK lock * held. It can be thought of a MT-safe version for GTK+ widgets for the * following use case, where you have to worry about idle_callback() * running in thread A and accessing self after it has been finalized * Since 2.12 * Params: * priority = the priority of the idle source. Typically this will be in the * range btweeen G_PRIORITY_DEFAULT_IDLE and G_PRIORITY_HIGH_IDLE * data = data to pass to function * notify = function to call when the idle is removed, or NULL * Returns: the ID (greater than 0) of the event source. */ public static uint gdkThreadsAddIdleFull(int priority, GSourceFunc funct, void* data, GDestroyNotify notify) { // guint gdk_threads_add_idle_full (gint priority, GSourceFunc function, gpointer data, GDestroyNotify notify); return gdk_threads_add_idle_full(priority, funct, data, notify); } /** * A wrapper for the common usage of gdk_threads_add_timeout_full() * assigning the default priority, G_PRIORITY_DEFAULT. * See gdk_threads_add_timeout_full(). * Since 2.12 * Params: * interval = the time between calls to the function, in milliseconds * (1/1000ths of a second) * data = data to pass to function * Returns: the ID (greater than 0) of the event source. */ public static uint gdkThreadsAddTimeout(uint interval, GSourceFunc funct, void* data) { // guint gdk_threads_add_timeout (guint interval, GSourceFunc function, gpointer data); return gdk_threads_add_timeout(interval, funct, data); } /** * Sets a function to be called at regular intervals holding the GDK lock, * with the given priority. The function is called repeatedly until it * returns FALSE, at which point the timeout is automatically destroyed * and the function will not be called again. The notify function is * called when the timeout is destroyed. The first call to the * function will be at the end of the first interval. * Note that timeout functions may be delayed, due to the processing of other * event sources. Thus they should not be relied on for precise timing. * After each call to the timeout function, the time of the next * timeout is recalculated based on the current time and the given interval * (it does not try to 'catch up' time lost in delays). * This variant of g_timeout_add_full() can be thought of a MT-safe version * Since 2.12 * Params: * priority = the priority of the timeout source. Typically this will be in the * range between G_PRIORITY_DEFAULT_IDLE and G_PRIORITY_HIGH_IDLE. * interval = the time between calls to the function, in milliseconds * (1/1000ths of a second) * data = data to pass to function * notify = function to call when the timeout is removed, or NULL * Returns: the ID (greater than 0) of the event source. */ public static uint gdkThreadsAddTimeoutFull(int priority, uint interval, GSourceFunc funct, void* data, GDestroyNotify notify) { // guint gdk_threads_add_timeout_full (gint priority, guint interval, GSourceFunc function, gpointer data, GDestroyNotify notify); return gdk_threads_add_timeout_full(priority, interval, funct, data, notify); } /** * A wrapper for the common usage of gdk_threads_add_timeout_seconds_full() * assigning the default priority, G_PRIORITY_DEFAULT. * For details, see gdk_threads_add_timeout_full(). * Since 2.14 * Params: * interval = the time between calls to the function, in seconds * data = data to pass to function * Returns: the ID (greater than 0) of the event source. */ public static uint gdkThreadsAddTimeoutSeconds(uint interval, GSourceFunc funct, void* data) { // guint gdk_threads_add_timeout_seconds (guint interval, GSourceFunc function, gpointer data); return gdk_threads_add_timeout_seconds(interval, funct, data); } /** * A variant of gdk_threads_add_timout_full() with second-granularity. * See g_timeout_add_seconds_full() for a discussion of why it is * a good idea to use this function if you don't need finer granularity. * Since 2.14 * Params: * priority = the priority of the timeout source. Typically this will be in the * range between G_PRIORITY_DEFAULT_IDLE and G_PRIORITY_HIGH_IDLE. * interval = the time between calls to the function, in seconds * data = data to pass to function * notify = function to call when the timeout is removed, or NULL * Returns: the ID (greater than 0) of the event source. */ public static uint gdkThreadsAddTimeoutSecondsFull(int priority, uint interval, GSourceFunc funct, void* data, GDestroyNotify notify) { // guint gdk_threads_add_timeout_seconds_full (gint priority, guint interval, GSourceFunc function, gpointer data, GDestroyNotify notify); return gdk_threads_add_timeout_seconds_full(priority, interval, funct, data, notify); }
D
/Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/build/Pods.build/Debug-iphonesimulator/RxSwift.build/Objects-normal/x86_64/VirtualTimeConverterType.o : /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Amb.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Deferred.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Deprecated.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Enumerated.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/Maybe.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Sequence.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Debounce.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Reduce.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Range.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Merge.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Take.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Cancelable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/Completable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/GroupedObservable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/Single.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/AsSingle.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Sample.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Throttle.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ObservableType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ConnectableObservableType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/SchedulerType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ObserverType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Create.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Generate.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/DataStructures/Queue.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Reactive.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Materialize.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/AddRef.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/DataStructures/Bag.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Using.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Debug.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Catch.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Date+Dispatch.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Switch.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/StartWith.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/Lock.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/RecursiveLock.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Sink.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Optional.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Scan.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/Platform.Darwin.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Do.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Map.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/CompactMap.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Zip.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Skip.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Producer.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Buffer.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Timer.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Filter.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Never.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/AnyObserver.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Error.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/Disposables.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Errors.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/ElementAt.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Concat.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Repeat.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/AtomicInt.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Event.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/TakeLast.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Multicast.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/First.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Just.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Timeout.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Window.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Rx.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/RxMutableBox.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/Platform.Linux.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/GroupBy.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Delay.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/ToArray.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Empty.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift /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/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/Target\ Support\ Files/RxSwift/RxSwift-umbrella.h /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/build/Pods.build/Debug-iphonesimulator/RxSwift.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/build/Pods.build/Debug-iphonesimulator/RxSwift.build/Objects-normal/x86_64/VirtualTimeConverterType~partial.swiftmodule : /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Amb.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Deferred.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Deprecated.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Enumerated.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/Maybe.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Sequence.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Debounce.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Reduce.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Range.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Merge.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Take.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Cancelable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/Completable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/GroupedObservable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/Single.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/AsSingle.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Sample.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Throttle.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ObservableType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ConnectableObservableType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/SchedulerType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ObserverType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Create.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Generate.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/DataStructures/Queue.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Reactive.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Materialize.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/AddRef.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/DataStructures/Bag.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Using.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Debug.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Catch.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Date+Dispatch.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Switch.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/StartWith.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/Lock.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/RecursiveLock.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Sink.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Optional.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Scan.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/Platform.Darwin.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Do.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Map.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/CompactMap.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Zip.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Skip.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Producer.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Buffer.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Timer.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Filter.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Never.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/AnyObserver.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Error.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/Disposables.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Errors.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/ElementAt.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Concat.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Repeat.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/AtomicInt.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Event.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/TakeLast.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Multicast.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/First.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Just.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Timeout.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Window.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Rx.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/RxMutableBox.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/Platform.Linux.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/GroupBy.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Delay.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/ToArray.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Empty.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift /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/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/Target\ Support\ Files/RxSwift/RxSwift-umbrella.h /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/build/Pods.build/Debug-iphonesimulator/RxSwift.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/build/Pods.build/Debug-iphonesimulator/RxSwift.build/Objects-normal/x86_64/VirtualTimeConverterType~partial.swiftdoc : /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Amb.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Deferred.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Deprecated.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Enumerated.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/Maybe.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Sequence.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Debounce.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Reduce.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Range.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Merge.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Take.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Cancelable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/Completable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/GroupedObservable.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/Single.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/AsSingle.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Sample.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Throttle.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ObservableType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ConnectableObservableType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/SchedulerType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ObserverType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Create.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Generate.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/DataStructures/Queue.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Reactive.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Materialize.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/AddRef.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/DataStructures/Bag.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Using.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Debug.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Catch.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Date+Dispatch.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Switch.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/StartWith.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/Lock.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/RecursiveLock.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Sink.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Optional.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Scan.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/Platform.Darwin.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Do.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Map.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/CompactMap.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Zip.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Skip.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Producer.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Buffer.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Timer.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Filter.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Never.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/AnyObserver.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Error.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Disposables/Disposables.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Errors.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/ElementAt.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Concat.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Repeat.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/AtomicInt.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Event.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/TakeLast.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Multicast.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/First.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Just.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Timeout.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Window.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Rx.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/RxMutableBox.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/Platform/Platform.Linux.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/GroupBy.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Delay.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/ToArray.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/Empty.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift /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/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/Pods/Target\ Support\ Files/RxSwift/RxSwift-umbrella.h /Users/ameeradamsika/Desktop/IOS/Demo/LoginWithRxSwift/build/Pods.build/Debug-iphonesimulator/RxSwift.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.4.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
D
//########################################################################## //## //## Hier stehen alle Buchständermobsiscripte //## //########################################################################## //************************************* // Buchständer in der Klosterbibliothek //************************************* FUNC VOID Use_Bookstand_01_S1() //Buchständer in der Magierbibliothek { var C_NPC her; her = Hlp_GetNpc(PC_Hero); if (Hlp_GetInstanceID(self) == Hlp_GetInstanceID(her)) { if (hero.guild == GIL_NOV) { KNOWS_FIRE_CONTEST = TRUE; //für die Prüfung des Feuers Log_CreateTopic (TOPIC_FireContest,LOG_MISSION); Log_SetTopicStatus (TOPIC_FireContest,LOG_RUNNING); B_LogEntry (TOPIC_FireContest,"Jakožto novic mám právo na Zkoušku ohnę. To znamená, že mi každý ze tâí mágů z Nejvyšší rady zadá nęjaký úkol. Pokud je splním, budu pâijat do Kruhu ohnę."); }; var int nDocID; nDocID = Doc_Create () ; Doc_SetPages ( nDocID, 2 ); Doc_SetPage ( nDocID, 0, "Book_Mage_L.tga", 0 ); Doc_SetPage ( nDocID, 1, "Book_Mage_R.tga", 0 ); Doc_SetFont ( nDocID, -1, FONT_Book ); Doc_SetMargins ( nDocID, 0, 275, 20, 30, 20, 1 ); Doc_PrintLine ( nDocID, 0, "Zkouška ohnę" ); Doc_PrintLine ( nDocID, 0, "" ); Doc_PrintLine ( nDocID, 0, "" ); Doc_PrintLines ( nDocID, 0, "I když novic může mít pocit, že je pâipraven podstoupit Zkoušku ohnę, neznamená to, že bude vybrán. Pokud ale na svém rozhodnutí stále trvá, má právo zkoušku požadovat a žádný mág mu v tom nesmí bránit. Ale nejenže musí projít zkouškou magie, musí také najít osvícení skrze oheŕ. Pâednese-li své rozhodnutí Nejvyšší radę, čeká ho ZKOUŠKA OHNĘ."); Doc_SetMargins ( nDocID, -1, 30, 20, 275, 20, 1 ); Doc_PrintLine ( nDocID, 1, "" ); Doc_PrintLine ( nDocID, 1, "" ); Doc_PrintLine ( nDocID, 1, "" ); Doc_PrintLines ( nDocID, 1, "Zkouška provęâí jak novicovu moudrost, tak i sílu a obratnost. Proto se skládá celkem ze tâí částí, z nichž každou mu zadá jeden mág Nejvyšší rady ještę pâedtím, než složí pâísahu ohnę a bude spjat s tímto živlem."); Doc_PrintLine ( nDocID, 1, "" ); Doc_PrintLine ( nDocID, 1, "" ); Doc_PrintLines ( nDocID, 1, "Taková je Innosova vůle a tak se i stane. " ); Doc_PrintLine ( nDocID, 1, "" ); Doc_PrintLine ( nDocID, 1, "" ); Doc_PrintLines ( nDocID, 1, "Nejvyšší rada" ); Doc_Show ( nDocID ); }; }; //************************************* // Buchständer in der Geheimen Bibliothek //************************************* //-------------------------------------- var int FinalDragonEquipment_Once; //-------------------------------------- FUNC VOID Use_FINALDRAGONEQUIPMENT_S1() //Buchständer in der geheimen Bibliothek { var C_NPC her; her = Hlp_GetNpc(PC_Hero); if (Hlp_GetInstanceID(self) == Hlp_GetInstanceID(her)) { var int nDocID; nDocID = Doc_Create () ; Doc_SetPages ( nDocID, 2 ); Doc_SetPage ( nDocID, 0, "Book_Mage_L.tga", 0); Doc_SetPage ( nDocID, 1, "Book_Mage_R.tga", 0); Doc_SetFont ( nDocID, -1, FONT_Book ); Doc_SetMargins ( nDocID, 0, 275, 20, 30, 20, 1); Doc_PrintLine ( nDocID, 0, ""); Doc_PrintLines ( nDocID, 0, "...Doufám, že kupole ochrání rudu pâed zlobou Beliarovou. Král je ve své naivitę schopen vęâit, že jsme ji postavili proto, aby žádný z vęzŕů neunikl. No, jestli tahle lest poslouží vyšším cílům, aă se tak stane. Mohu jen doufat, že nám ještę zbývá dost času pro pâípravy na boj. Jakmile kupole obklopí Hornické údolí, vynaložím všechnu svou moc, aby se boj už více nezdržoval. "); Doc_PrintLines ( nDocID, 0, ""); if (hero.guild == GIL_KDF) { PlayerGetsAmulettOfDeath = TRUE; PLAYER_TALENT_RUNES[SPL_MasterOfDisaster] = TRUE; B_LogEntry (TOPIC_TalentRunes,"K pâípravę runy 'Božský zásah' je tâeba: 1 svęcená voda, žádný svitek s kouzlem"); Doc_SetMargins ( nDocID, -1, 30, 20, 275, 20, 1); Doc_PrintLine ( nDocID, 1, ""); Doc_PrintLines ( nDocID, 1, "...postupoval jsem podle instrukcí a prostę jsem na čistý runový kámen na runové tabulce nalil Innosovu svęcenou vodu. Ta jej ale zcela zničila - počítám tedy, že tohle kouzlo může použít pouze Vyvolený."); Doc_PrintLines ( nDocID, 1, "Klášter jsem svęâil pod ochranu svaté Innosovy aury. Opat se už o nęj postará, dokud se nám nezjeví Vyvolený." ); Doc_PrintLines ( nDocID, 1, "Možná že v nadcházejícím boji sehrají klíčovou roli Innosovy slzy. Nemohu je ale držet na místę, kde je každý uvidí - je to pâíliš nebezpečné. Radši je nechám tady v knihovnę." ); Doc_Show ( nDocID ); } else if (hero.guild == GIL_PAL) { PAL_KnowsAbout_FINAL_BLESSING = TRUE; PLAYER_TALENT_RUNES[SPL_PalTeleportSecret] = TRUE; PrintScreen (PRINT_LearnPalTeleportSecret, -1, -1, FONT_Screen, 2); Log_CreateTopic (TOPIC_TalentRunes,LOG_NOTE); B_LogEntry (TOPIC_TalentRunes,"K výrobę každé runy potâebuji určité ingredience. Když je pak použiji na čistý runový kámen, mohu zvolenou runu vytvoâit podle runové tabulky."); B_LogEntry (TOPIC_TalentRunes,"Pâísady pro runu 'tajného teleportu' jsou: 1 Innosova slza"); Doc_SetMargins ( nDocID, -1, 30, 20, 275, 20, 1); Doc_PrintLine ( nDocID, 1, ""); Doc_PrintLines ( nDocID, 1, "Pro každé z tajných míst musíš pomocí prázdného runového kamene a lahvičky svęcené vody vytvoâit teleportační runu, která tę pak pâenese do zvolené místnosti."); Doc_PrintLine ( nDocID, 1, ""); Doc_PrintLines ( nDocID, 1, "Teë už jsem si skoro jist, že právę Innosovy slzy používali za dávných časů paladinové pâi dnes již zapomenutím rituálu svęcení meče. Takže tahle malá lahvička, co jsem našel, by męla posvęcené zbrani pâidat ještę další sílu." ); Doc_PrintLine ( nDocID, 1, ""); Doc_Show ( nDocID ); } else { PLAYER_TALENT_SMITH[WEAPON_1H_Special_04] = TRUE; PLAYER_TALENT_SMITH[WEAPON_2H_Special_04] = TRUE; PrintScreen (PRINT_LearnSmith, -1, -1, FONT_Screen, 2); Npc_SetTalentSkill (self, NPC_TALENT_SMITH, 1); Log_CreateTopic (TOPIC_TalentSmith,LOG_NOTE); B_LogEntry (TOPIC_TalentSmith,"K vykování takové zbranę potâebuji hlavnę kousek surové oceli. Tu pak doruda rozžhavím v kováâské výhni a pak ji budu kout na kovadlinę. U určitých zbraní je také často zapotâebí použít jisté substance, které jim pak propůjčí jedinečné vlastnosti."); B_LogEntry (TOPIC_TalentSmith,"Pâidám-li 4 kousky rudy a pętkrát dračí krev, mohu vykovat DRAKOBIJCE."); B_LogEntry (TOPIC_TalentSmith,"Když použiji 5 kousků rudy a pętkrát dračí krev, vykovám VELKÉHO DRAKOBIJCE."); PlayerGetsFinalDJGArmor = TRUE; Doc_SetMargins ( nDocID, -1, 30, 20, 275, 20, 1); Doc_PrintLine ( nDocID, 1, ""); Doc_PrintLines ( nDocID, 1, "Zdroj: Zbranę pána draků."); Doc_PrintLines ( nDocID, 1, "Chceš-li zbroj z dračích šupin co možná vytvrdit, musíš je potáhnout rudou, která se tęží v údolí na ostrovę Karynis." ); Doc_PrintLine ( nDocID, 1, ""); Doc_PrintLines ( nDocID, 1, "Má-li být meč hoden pána draků, pak musíš jeho čepel omočit v dračí krvi. Pouhých 5 ampulek s touto vzácnou tekutinou dodá oceli nebývalou ostrost a průraznost." ); Doc_PrintLine ( nDocID, 1, ""); Doc_PrintLines ( nDocID, 1, "Poznámka: 'Karynis' je pravdępodobnę místo dnes známé jako Khorinis."); Doc_Show ( nDocID ); }; if FinalDragonEquipment_Once == FALSE { B_GivePlayerXP (XP_FinalDragonEquipment); FinalDragonEquipment_Once = TRUE; }; }; };
D
module opencore.schema.uefi; import opencore.schema.common; struct UEFIAPFSFields { @PlistKey("MinVersion") ulong minVersion; @PlistKey("MinDate") ulong minDate; @PlistKey("EnableJumpstart") bool enableJumpstart; @PlistKey("HideVerbose") bool hideVerbose; @PlistKey("JumpstartHotPlug") bool jumpstartHotPlug; } struct UEFIAudioFields { @PlistKey("AudioDevice") string audioDevice; @PlistKey("VolumeAmplifier") ulong volumeAmplifier; @PlistKey("AudioSupport") bool audioSupport; @PlistKey("PlayChime") bool playChime; @PlistKey("AudioCodec") ulong audioCodec; @PlistKey("AudioOut") ulong audioOut; @PlistKey("MinimumVolume") ulong minimumVolume; } struct UEFIInputFields { @PlistKey("KeySupportMode") string keySupportMode; @PlistKey("PointerSupportMode") string pointerSupportMode; @PlistKey("TimerResolution") ulong timerResolution; @PlistKey("KeyForgetThreshold") ulong keyForgetThreshold; @PlistKey("KeyMergeThreshold") ulong keyMergeThreshold; @PlistKey("KeySupport") bool keySupport; @PlistKey("KeyFiltering") bool keyFiltering; @PlistKey("KeySwap") bool keySwap; @PlistKey("PointerSupport") bool pointerSupport; } struct UEFIOutputFields { @PlistKey("ConsoleMode") string consoleMode; @PlistKey("Resolution") string resolution; @PlistKey("TextRenderer") string textRenderer; @PlistKey("DirectGopCacheMode") string directGOPCacheMode; @PlistKey("IgnoreTextInGraphics") bool ignoreTextInGraphics; @PlistKey("ClearScreenOnModeSwitch") bool clearScreenOnModeSwitch; @PlistKey("ProvideConsoleGop") bool provideConsoleGOP; @PlistKey("ReplaceTabWithSpace") bool replaceTabWithSpace; @PlistKey("ReconnectOnResChange") bool reconnectOnResChange; @PlistKey("SanitiseClearScreen") bool sanitiseClearScreen; @PlistKey("DirectGopRendering") bool directGOPRendering; } struct UEFIProtocolFields { @PlistKey("AppleAudio") bool appleAudio; @PlistKey("AppleBootPolicy") bool appleBootPolicy; @PlistKey("AppleDebugLog") bool appleDebugLog; @PlistKey("AppleEvent") bool appleEvent; @PlistKey("AppleImageConversion") bool appleImageConversion; @PlistKey("AppleKeyMap") bool appleKeyMap; @PlistKey("AppleSmcIo") bool appleSMCIO; @PlistKey("AppleUserInterfaceTheme") bool appleUserInterfaceTheme; @PlistKey("DataHub") bool dataHub; @PlistKey("DeviceProperties") bool deviceProperties; @PlistKey("FirmwareVolume") bool firmwareVolume; @PlistKey("HashServices") bool hashServices; @PlistKey("OSInfo") bool osInfo; @PlistKey("UnicodeCollation") bool unicodeCollation; } struct UEFIQuirksFields { @PlistKey("ExitBootServicesDelay") ulong exitBootServicesDelay; @PlistKey("IgnoreInvalidFlexRatio") bool ignoreInvalidFlexRatio; @PlistKey("ReleaseUsbOwnership") bool releaseUSBOwnership; @PlistKey("RequestBootVarFallback") bool requestBootVarFallback; @PlistKey("RequestBootVarRouting") bool requestBootVarRouting; @PlistKey("UnblockFsConnect") bool unblockFSConnect; } struct UEFIConfig { @PlistKey("ConnectDrivers") bool connectDrivers; @PlistKey("APFS") UEFIAPFSFields apfs; @PlistKey("Audio") UEFIAudioFields audio; @PlistKey("Drivers") PlistElementArray drivers; @PlistKey("Input") UEFIInputFields input; @PlistKey("Output") UEFIOutputFields output; @PlistOptional @PlistKey("Protocols") UEFIProtocolFields protocols; @PlistOptional @PlistKey("ProtocolOverrides") UEFIProtocolFields protocolOverrides; @PlistKey("Quirks") UEFIQuirksFields quirks; }
D
/* Copyright (c) 2019-2020 Timur Gafarov 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 dagon.render.deferred; public { import dagon.render.deferred.backgroundstage; import dagon.render.deferred.clearstage; import dagon.render.deferred.debugoutputstage; import dagon.render.deferred.decalstage; import dagon.render.deferred.environmentstage; import dagon.render.deferred.geometrystage; import dagon.render.deferred.lightstage; import dagon.render.deferred.occlusionstage; import dagon.render.deferred.particlesstage; import dagon.render.deferred.forwardstage; }
D
/* EPANET 3 * * Copyright (c) 2016 Open Water Analytics * Distributed under the MIT License (see the LICENSE file for details). * */ module epanet.output.projectwriter; import core.stdc.math: pow; import std.stdio, std.format, std.string; import epanet.core.error; import epanet.core.network; import epanet.core.units; import epanet.core.options; import epanet.elements.node; import epanet.elements.junction; import epanet.elements.reservoir; import epanet.elements.tank; import epanet.elements.pipe; import epanet.elements.link; import epanet.elements.pump; import epanet.elements.pumpcurve; import epanet.elements.valve; import epanet.elements.demand; import epanet.elements.emitter; import epanet.elements.pattern; import epanet.elements.curve; import epanet.elements.control; import epanet.elements.qualsource; import epanet.models.tankmixmodel; import epanet.utilities.utilities; //! \class ProjectWriter //! \brief The ProjectWriter class writes a project's data to file. class ProjectWriter { public: this(){ network = null; } ~this(){} int writeFile(string fname, Network nw){ if (nw is null) return 0; network = nw; fout.open(fname, "w"); if (!fout.isOpen()) return FileError.CANNOT_OPEN_INPUT_FILE; writeTitle(); writeJunctions(); writeReservoirs(); writeTanks(); writePipes(); writePumps(); writeValves(); writeDemands(); writeEmitters(); writeStatus(); writePatterns(); writeCurves(); writeControls(); writeEnergy(); writeQuality(); writeSources(); writeMixing(); writeReactions(); writeOptions(); writeTimes(); writeReport(); writeTags(); writeCoords(); writeAuxData(); fout.close(); return 0; } private: void writeTitle(){ fout.writeln("[TITLE]"); network.writeTitle(fout); } void writeJunctions(){ fout.write("\n[JUNCTIONS]\n"); foreach (Node node; network.nodes) { if ( node.type() == Node.JUNCTION ) { auto junc = cast(Junction)node; string name = leftJustify(node.name, 16, ' '); immutable en = leftJustify(format("%.4f", node.elev*network.ucf(Units.LENGTH)), 12, ' '); string tw = name ~ en; if (network.option(Options.DEMAND_MODEL) != "FIXED" ) { string blank = "* * "; double pUcf = network.ucf(Units.PRESSURE); string tw2 = tw ~ blank ~ leftJustify(format("%.4f", junc.pMin * pUcf), 12, ' ') ~ leftJustify(format("%.4f", junc.pFull * pUcf), 12, ' '); fout.writef("%s\n", tw2); }else fout.writef("%s\n", tw); } } } void writeReservoirs(){ fout.write("\n[RESERVOIRS]\n"); foreach (Node node; network.nodes) { if ( node.type() == Node.RESERVOIR ) { Reservoir resv = cast(Reservoir)node; string name = leftJustify(node.name, 16, ' '); string tmp = name ~ format("%.4f", node.elev*network.ucf(Units.LENGTH)).leftJustify(12, ' '); if ( resv.headPattern ) { tmp ~= resv.headPattern.name; } fout.writef("%s\n", tmp.strip); } } } void writeTanks(){ fout.write("\n[TANKS]\n"); foreach (Node node; network.nodes) { if ( node.type() == Node.TANK ) { Tank tank = cast(Tank)node; double ucfLength = network.ucf(Units.LENGTH); string name = leftJustify(node.name, 16, ' '); string tmp = name ~ leftJustify(format("%.4f", node.elev * ucfLength), 12, ' ') ~ leftJustify(format("%.4f", (tank.initHead - node.elev) * ucfLength), 12, ' ') ~ leftJustify(format("%.4f", (tank.minHead - node.elev) * ucfLength), 12, ' ') ~ leftJustify(format("%.4f", (tank.maxHead - node.elev) * ucfLength), 12, ' ') ~ leftJustify(format("%.4f", tank.diameter * ucfLength), 12, ' ') ~ leftJustify(format("%.4f", tank.minVolume * network.ucf(Units.VOLUME)), 12, ' '); if ( tank.volCurve ) tmp ~= tank.volCurve.name; fout.writef("%s\n", tmp.strip); } } } void writePipes(){ fout.write("\n[PIPES]\n"); foreach (Link link; network.links) { if ( link.type() == Link.PIPE ) { Pipe pipe = cast(Pipe)link; string name = leftJustify(link.name, 16, ' '); string tmp = name ~ leftJustify(link.fromNode.name, 16, ' ') ~ leftJustify(link.toNode.name, 16, ' ') ~ leftJustify(format("%.4f", pipe.length * network.ucf(Units.LENGTH)), 12, ' ') ~ leftJustify(format("%.4f", pipe.diameter * network.ucf(Units.DIAMETER)), 12, ' '); double r = pipe.roughness; if ( network.option(Options.HEADLOSS_MODEL ) == "D-W") { r = r * network.ucf(Units.LENGTH) * 1000.0; } tmp ~= leftJustify(format("%.4f", r), 12, ' ') ~ leftJustify(format("%.4f", pipe.lossCoeff), 12, ' '); if (pipe.hasCheckValve) tmp ~= "CV\n"; else if ( link.initStatus == Link.LINK_CLOSED ) tmp ~= "CLOSED\n"; else tmp ~="\n"; fout.writef("%s", tmp); } } } void writePumps(){ fout.write("\n[PUMPS]\n"); foreach (Link link; network.links) { if ( link.type() == Link.PUMP ) { Pump pump = cast(Pump)link; string tmp = leftJustify(link.name, 16, ' ') ~ leftJustify(link.fromNode.name, 16, ' ') ~ leftJustify(link.toNode.name, 16, ' '); if ( pump.pumpCurve.horsepower > 0.0 ) { tmp ~= leftJustify("POWER", 8, ' ') ~ leftJustify(format("%.4f", pump.pumpCurve.horsepower * network.ucf(Units.POWER)), 12, ' '); } if ( pump.pumpCurve.curveType != PumpCurve.NO_CURVE ) { tmp ~= leftJustify("HEAD", 8, ' ') ~ leftJustify(pump.pumpCurve.curve.name, 16, ' '); } if ( pump.speed > 0.0 && pump.speed != 1.0 ) { tmp ~= leftJustify("SPEED", 8, ' ') ~ leftJustify(format("%.4f", pump.speed), 8, ' '); } if ( pump.speedPattern ) { tmp ~= leftJustify("PATTERN", 8, ' ') ~ leftJustify(pump.speedPattern.name, 16, ' '); } fout.writef("%s\n", tmp.strip); } } } void writeValves(){ fout.write("\n[VALVES]\n"); foreach (Link link; network.links) { if ( link.type() == Link.VALVE ) { Valve valve = cast(Valve)link; string tmp = leftJustify(link.name, 16, ' ') ~ leftJustify(link.fromNode.name, 16, ' ') ~ leftJustify(link.toNode.name, 16, ' ') ~ leftJustify(format("%.4f", valve.diameter*network.ucf(Units.DIAMETER)), 12, ' ') ~ leftJustify(Valve.ValveTypeWords[cast(size_t)valve.valveType], 8, ' '); if (valve.valveType == Valve.GPV) { tmp ~= leftJustify(network.curve(cast(int)link.initSetting).name, 16, ' '); } else { double cf = link.initSetting / link.convertSetting(network, link.initSetting); tmp ~= leftJustify(format("%.4f", cf * link.initSetting), 12, ' '); } fout.writef("%s\n", tmp.strip); } } } void writeDemands(){ fout.write("\n[DEMANDS]\n"); foreach (Node node; network.nodes) { if ( node.type() == Node.JUNCTION ) { Junction junc = cast(Junction)node; auto demandRange = junc.demands[]; foreach (ref demand; demandRange) { string tmp = leftJustify(node.name, 16, ' ') ~ leftJustify(format("%.4f", demand.baseDemand * network.ucf(Units.FLOW)), 12, ' '); if (demand.timePattern !is null) { tmp ~= leftJustify(demand.timePattern.name, 16, ' '); } fout.writef("%s\n", tmp.strip); } } } } void writeEmitters(){ fout.write("\n[EMITTERS]\n"); foreach (Node node; network.nodes) { if ( node.type() == Node.JUNCTION ) { Junction junc = cast(Junction)node; Emitter emitter = junc.emitter; if ( emitter ) { double qUcf = network.ucf(Units.FLOW); double pUcf = network.ucf(Units.PRESSURE); string tmp = leftJustify(node.name, 16, ' ') ~ leftJustify(format("%.4f", emitter.flowCoeff * qUcf * pow(pUcf, emitter.expon)), 12, ' ') ~ leftJustify(format("%.4f", emitter.expon), 12, ' '); if ( emitter.timePattern !is null ) tmp ~= leftJustify(emitter.timePattern.name, 16, ' '); fout.writef("%s\n", tmp.strip); } } } } void writeLeakages(){ fout.write("\n[LEAKAGES]\n"); foreach (Link link; network.links) { if ( link.type() == Link.PIPE ) { Pipe pipe = cast(Pipe)link; if ( pipe.leakCoeff1 > 0.0 ) { string tmp = leftJustify(link.name, 16, ' ') ~ leftJustify(format("%.4f", pipe.leakCoeff1), 12, ' ') ~ leftJustify(format("%.4f", pipe.leakCoeff2), 12, ' '); fout.writef("%s\n", tmp.strip); } } } } void writeStatus(){ fout.write("\n[STATUS]\n"); foreach (Link link; network.links) { if ( link.type() == Link.PUMP ) { if ( link.initSetting == 0 || link.initStatus == Link.LINK_CLOSED ) { string tmp = leftJustify(link.name, 16, ' ') ~ " CLOSED\n"; fout.write(tmp); } } else if ( link.type() == Link.VALVE ) { if ( link.initStatus == Link.LINK_OPEN || link.initStatus == Link.LINK_CLOSED ) { string tmp = leftJustify(link.name, 16, ' ') ~ " "; fout.write(tmp); if (link.initStatus == Link.LINK_OPEN) fout.write("OPEN\n"); else fout.write("CLOSED\n"); } } } } void writePatterns(){ fout.write("\n[PATTERNS]\n"); foreach (Pattern pattern; network.patterns) { if ( pattern.type == Pattern.FIXED_PATTERN ) { string tmp = leftJustify(pattern.name, 16, ' ') ~ " FIXED "; if ( pattern.timeInterval() > 0 ) tmp ~= Utilities.getTime(pattern.timeInterval()); int k = 0; int i = 0; int n = pattern.size(); while ( i < n ) { if ( k == 0 ) tmp ~= "\n" ~ leftJustify(pattern.name, 16, ' ') ~ " "; tmp ~= leftJustify(format("%.4f", pattern.factor(i)), 12, ' '); i++; k++; if ( k == 5 ) k = 0; } fout.write(tmp.strip); } else if (pattern. type == Pattern.VARIABLE_PATTERN ) { VariablePattern vp = cast(VariablePattern)pattern; string tmp = leftJustify(pattern.name, 16, ' ') ~ " VARIABLE "; for (int i = 0; i < pattern.size(); i++) { tmp ~= "\n" ~ leftJustify(pattern.name, 16, ' ') ~ " " ~ leftJustify(Utilities.getTime(cast(long)vp.time(i)) ~ format("%.4f", vp.factor(i)), 12, ' ') ~ "\n"; } fout.write(tmp.strip); } fout.write("\n"); } } void writeCurves(){ fout.write("\n[CURVES]\n"); foreach (Curve curve; network.curves) { if (curve.curveType() != Curve.UNKNOWN) { string tmp = leftJustify(curve.name, 16, ' ') ~ " " ~ Curve.CurveTypeWords[curve.curveType()] ~ "\n"; fout.write(tmp); } for (int i = 0; i < curve.size(); i++) { string tmp = leftJustify(curve.name, 16, ' ') ~ " " ~ leftJustify(format("%.4f", curve.x(i)), 12, ' ') ~ leftJustify(format("%.4f", curve.y(i)), 12, ' ') ~ "\n"; fout.write(tmp); } } } void writeControls(){ fout.write("\n[CONTROLS]\n"); foreach (Control control; network.controls) { fout.writef("%s\n", control.toStr(network)); } } void writeQuality(){ fout.write("\n[QUALITY]\n"); foreach (Node node; network.nodes) { if (node.initQual > 0.0) { string tmp = leftJustify(node.name, 16, ' ') ~ " " ~ leftJustify(format("%.4f", node.initQual * network.ucf(Units.CONCEN)), 12, ' '); fout.writef("%s\n", tmp); } } } void writeSources(){ fout.write("\n[SOURCES]\n"); foreach (Node node; network.nodes) { if ( node.qualSource && node.qualSource.base > 0.0) { string tmp = leftJustify(node.name, 16, ' ') ~ " " ~ leftJustify(QualSource.SourceTypeWords[node.qualSource.type], 12, ' ') ~ format("%.4f", node.qualSource.base); if ( node.qualSource.pattern ) { tmp ~= node.qualSource.pattern.name; } fout.writef("%s\n", tmp); } } } void writeMixing(){ fout.write("\n[MIXING]\n"); foreach (Node node; network.nodes) { if ( node.type() == Node.TANK ) { Tank tank = cast(Tank)node; string tmp = leftJustify(node.name, 16, ' ') ~ " " ~ leftJustify(TankMixModel.MixingModelWords[tank.mixingModel.type], 12, ' ') ~ format("%.4f", tank.mixingModel.fracMixed); fout.writef("%s\n", tmp); } } } void writeReactions(){ fout.write("\n[REACTIONS]\n"); fout.write(network.options.reactOptionsToStr()); double defBulkCoeff = network.option(Options.BULK_COEFF); double defWallCoeff = network.option(Options.WALL_COEFF); foreach (Link link; network.links) { if ( link.type() == Link.PIPE ) { Pipe pipe = cast(Pipe)link; if ( pipe.bulkCoeff != defBulkCoeff ) { fout.write("BULK "); fout.write(leftJustify(link.name, 16, ' ') ~ " "); fout.write(format("%.4f", pipe.bulkCoeff) ~ "\n"); } if ( pipe.wallCoeff != defWallCoeff ) { fout.write("WALL "); fout.write(leftJustify(link.name, 16, ' ') ~ " "); fout.write(format("%.4f", pipe.wallCoeff) ~ "\n"); } } } foreach (Node node; network.nodes) { if ( node.type() == Node.TANK ) { Tank tank = cast(Tank)node; if ( tank.bulkCoeff != defBulkCoeff ) { fout.write("TANK "); fout.write(leftJustify(node.name, 16, ' ') ~ " "); fout.write(format("%.4f", tank.bulkCoeff) ~ "\n"); } } } } void writeEnergy(){ fout.write("\n[ENERGY]\n"); fout.write(network.options.energyOptionsToStr(network)); foreach (Link link; network.links) { if ( link.type() == Link.PUMP ) { Pump pump = cast(Pump)link; if ( pump.efficCurve ) { fout.write("PUMP " ~ link.name ~ " " ~ "EFFIC "); fout.writef("%s\n", pump.efficCurve.name); } if ( pump.costPerKwh > 0.0 ) { fout.write("PUMP " ~ link.name ~ " " ~ "PRICE " ~ format("%.4f", pump.costPerKwh) ~ "\n"); } if ( pump.costPattern ) { fout.write("PUMP " ~ link.name ~ " " ~ "PATTERN "); fout.writef("%s\n", pump.costPattern.name); } } } } void writeTimes(){ fout.write("\n[TIMES]\n"); fout.write(network.options.timeOptionsToStr()); } void writeOptions(){ fout.write("\n[OPTIONS]\n"); fout.write(network.options.hydOptionsToStr()); fout.write("\n"); fout.write(network.options.demandOptionsToStr()); fout.write("\n"); fout.write(network.options.qualOptionsToStr()); } void writeReport(){ fout.write("\n[REPORT]\n"); fout.write(network.options.reportOptionsToStr()); } void writeTags(){} void writeCoords(){} void writeAuxData(){} Network network; File fout; }
D
module temple.tests.common; version(TempleUnittest): public import std.stdio, std.file : readText; public import temple, temple.util, temple.output_stream; bool isSameRender(in CompiledTemple t, TempleContext tc, string r2) { return isSameRender(t, r2, tc); } bool isSameRender(in CompiledTemple t, string r2, TempleContext tc = null) { return isSameRender(t.toString(tc), r2); } bool isSameRender(string r1, string r2) { auto ret = r1.stripWs == r2.stripWs; if(ret == false) { writeln("Renders differ: "); writeln("Got: -------------------------"); writeln(r1); writeln("Expected: --------------------"); writeln(r2); writeln("------------------------------"); } return ret; } deprecated("Please use template.toString()") string templeToString(CompiledTemple function() getr, TempleContext tc = null) { return getr().toString(tc); } unittest { auto render = compile_temple!""; assert(render.toString() == ""); } unittest { //Test to!string of eval delimers auto render = compile_temple!`<%= "foo" %>`; assert(render.toString == "foo"); } unittest { // Test delimer parsing auto render = compile_temple!("<% if(true) { %>foo<% } %>"); assert(render.toString == "foo"); } unittest { //Test raw text with no delimers auto render = compile_temple!(`foo`); assert(render.toString == "foo"); } unittest { //Test looping const templ = `<% foreach(i; 0..3) { %>foo<% } %>`; auto render = compile_temple!templ; assert(render.toString == "foofoofoo"); } unittest { //Test looping const templ = `<% foreach(i; 0..3) { %><%= i %><% } %>`; auto render = compile_temple!templ; assert(render.toString == "012"); } unittest { //Test escaping of " const templ = `"`; auto render = compile_temple!templ; assert(render.toString == `"`); } unittest { //Test escaping of ' const templ = `'`; auto render = compile_temple!templ; assert(render.toString == `'`); } unittest { auto render = compile_temple!`"%"`; assert(render.toString == `"%"`); } unittest { // Test shorthand const templ = ` % if(true) { Hello! % } `; auto render = compile_temple!(templ); assert(isSameRender(render.toString, "Hello!")); } unittest { // Test shorthand string eval const templ = ` % if(true) { %= "foo" % } `; auto render = compile_temple!(templ); //static assert(false); assert(isSameRender(render.toString, "foo")); } unittest { // Test shorthand only after newline const templ = `foo%bar`; auto render = compile_temple!(templ); assert(render.toString == "foo%bar"); } unittest { // Ditto auto render = compile_temple!`<%= "foo%bar" %>`; assert(render.toString == "foo%bar"); } unittest { auto context = new TempleContext(); context.foo = 123; context.bar = "test"; auto render = compile_temple!`<%= var("foo") %> <%= var("bar") %>`; assert(render.toString(context) == "123 test"); } unittest { // Loading templates from a file auto render = compile_temple_file!"test1.emd"; auto compare = readText("test/test1.emd.txt"); assert(isSameRender(render.toString, compare)); } unittest { auto render = compile_temple_file!"test2.emd"; auto compare = readText("test/test2.emd.txt"); auto ctx = new TempleContext(); ctx.name = "dymk"; ctx.will_work = true; assert(isSameRender(render.toString(ctx), compare)); } unittest { auto render = compile_temple_file!"test3_nester.emd"; auto compare = readText("test/test3.emd.txt"); assert(isSameRender(render.toString, compare)); } unittest { auto render = compile_temple_file!"test4_root.emd"; auto compare = readText("test/test4.emd.txt"); auto ctx = new TempleContext(); ctx.var1 = "this_is_var1"; assert(isSameRender(render.toString(ctx), compare)); } unittest { auto parent = compile_temple!"before <%= yield %> after"; auto partial = compile_temple!"between"; assert(isSameRender(parent.layout(&partial), "before between after")); } unittest { auto parent = compile_temple!"before <%= yield %> after"; auto partial = compile_temple!"between"; assert(isSameRender(parent.layout(&partial), "before between after")); } unittest { auto parent = compile_temple_file!"test5_layout.emd"; auto partial1 = compile_temple_file!"test5_partial1.emd"; auto partial2 = compile_temple_file!"test5_partial2.emd"; auto p1 = parent.layout(&partial1); auto p2 = parent.layout(&partial2); assert(isSameRender(p1, readText("test/test5_partial1.emd.txt"))); assert(isSameRender(p2, readText("test/test5_partial2.emd.txt"))); } // Layouts and contexts unittest { auto parent = compile_temple_file!"test6_layout.emd"; auto partial = compile_temple_file!"test6_partial.emd"; auto context = new TempleContext(); context.name = "dymk"; context.uni = "UCSD"; context.age = 19; assert(isSameRender(parent.layout(&partial), context, readText("test/test6_partial.emd.txt"))); } // opDispatch variable getting unittest { auto render = compile_temple!"<%= var.foo %>"; auto context = new TempleContext(); context.foo = "Hello, world"; assert(isSameRender(render, context, "Hello, world")); } unittest { // 22 Nov, 2014: Disabled this bit, because DMD now ICEs when // evaluating the erronious template (but not before spitting out // a lot of errors). This will have to do for finding out that a templtae // has a lot of errors in it. // Uncomment to view the line numbers inserted into the template //TODO: check if this works in future DMD releases //auto render = compile_temple_file!"test7_error.emd"; //assert(!__traits(compiles, { // auto t = compile_temple_file!"test7_error.emd"; //})); } unittest { import temple.func_string_gen; // Test returning early from templates //auto str = ` auto render = compile_temple!` one % auto blah = true; % if(blah) { two % return; % } three `; //writeln(__temple_gen_temple_func_string(str, "Inline")); assert(isSameRender(render.toString, `one two`)); }
D
updown.o: C:/PROGRA~1/MATLAB/R2015b/rtw/c/src/ext_mode/common/updown.c \ C:/Users/Joern/DOCUME~1/github/DH_ARD~1/LABOR0~1/Simulink/Geschwindigkeitsregler_ert_rtw/rtwtypes.h \ C:/PROGRA~1/MATLAB/R2015b/simulink/include/rtw_extmode.h \ C:/PROGRA~1/MATLAB/R2015b/simulink/include/sysran_types.h \ C:/PROGRA~1/MATLAB/R2015b/rtw/c/src/ext_mode/common/ext_types.h \ C:/PROGRA~1/MATLAB/R2015b/rtw/c/src/ext_mode/common/ext_share.h \ C:/PROGRA~1/MATLAB/R2015b/rtw/c/src/ext_mode/common/ext_svr.h \ C:/PROGRA~1/MATLAB/R2015b/rtw/c/src/ext_mode/common/ext_work.h \ C:/PROGRA~1/MATLAB/R2015b/rtw/c/src/ext_mode/common/updown_util.h \ C:/PROGRA~1/MATLAB/R2015b/rtw/c/src/dt_info.h \ C:/PROGRA~1/MATLAB/R2015b/rtw/c/src/ext_mode/common/upsup_public.h
D
/** License: Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Authors: aermicioi **/ module aermicioi.aedi.test.factory.decorating_factory; import aermicioi.aedi.storage.object_storage; import aermicioi.aedi.test.fixture; import aermicioi.aedi.factory.decorating_factory; import aermicioi.aedi.exception.di_exception; import aermicioi.aedi.factory.wrapping_factory; import std.exception; unittest { MockFactory!MockObject ofactory = new MockFactory!MockObject; auto factory = new WrappingFactory!(MockFactory!MockObject)(ofactory); ObjectStorage!() locator = new ObjectStorage!(); factory.locator = locator; assert(factory.decorated is ofactory); assert(factory.type is typeid(MockObject)); assert(ofactory.locator_ is locator); assert(factory.factory() !is null); } unittest { MockFactory!MockObject ofactory = new MockFactory!MockObject; TaggableFactoryDecorator!(Object, string) factory = new TaggableFactoryDecorator!(Object, string)(); ObjectStorage!() locator = new ObjectStorage!(); factory.decorated = ofactory; factory.locator = locator; factory.tag("test"); factory.tag("test1"); factory.tag("test2"); assert(factory.tags == ["test", "test1", "test2"]); factory.untag("test1"); assert(factory.tags == ["test", "test2"]); factory.tags = ["tagged", "tagged1"]; assert(factory.tags == ["tagged", "tagged1"]); assert(factory.decorated is ofactory); assert(factory.type is typeid(MockObject)); assert(ofactory.locator_ is locator); assert(factory.factory() !is null); } unittest { import std.conv; RegistrationAwareDecoratingFactory!Object factory = new RegistrationAwareDecoratingFactory!Object; factory.line = 20; factory.file = "some/hyphotetical/folder"; factory.decorated = new MockFailingFactory!MockObject; assertThrown!AediException( factory.factory, ); assert(factory.line == 20); assert(factory.file == "some/hyphotetical/folder"); assert(factory.type is typeid(MockObject)); }
D
module UnrealScript.Engine.AnimNotify_ViewShake; import ScriptClasses; import UnrealScript.Helpers; import UnrealScript.Engine.AnimNodeSequence; import UnrealScript.Engine.CameraShake; import UnrealScript.Engine.Actor; import UnrealScript.Engine.AnimNotify_Scripted; extern(C++) interface AnimNotify_ViewShake : AnimNotify_Scripted { public extern(D): private static __gshared ScriptClass mStaticClass; @property final static ScriptClass StaticClass() { mixin(MGSCC("Class Engine.AnimNotify_ViewShake")); } private static __gshared AnimNotify_ViewShake mDefaultProperties; @property final static AnimNotify_ViewShake DefaultProperties() { mixin(MGDPC("AnimNotify_ViewShake", "AnimNotify_ViewShake Engine.Default__AnimNotify_ViewShake")); } static struct Functions { private static __gshared ScriptFunction mNotify; public @property static final ScriptFunction Notify() { mixin(MGF("mNotify", "Function Engine.AnimNotify_ViewShake.Notify")); } } @property final { auto ref { CameraShake ShakeParamsVar() { mixin(MGPC("CameraShake", 140)); } ScriptName BoneName() { mixin(MGPC("ScriptName", 132)); } float ShakeRadius() { mixin(MGPC("float", 128)); } float FOVFrequency() { mixin(MGPC("float", 120)); } float FOVAmplitude() { mixin(MGPC("float", 116)); } Vector LocFrequency() { mixin(MGPC("Vector", 104)); } Vector LocAmplitude() { mixin(MGPC("Vector", 92)); } Vector RotFrequency() { mixin(MGPC("Vector", 80)); } Vector RotAmplitude() { mixin(MGPC("Vector", 68)); } float Duration() { mixin(MGPC("float", 64)); } } bool bUseBoneLocation() { mixin(MGBPC(124, 0x2)); } bool bUseBoneLocation(bool val) { mixin(MSBPC(124, 0x2)); } bool bDoControllerVibration() { mixin(MGBPC(124, 0x1)); } bool bDoControllerVibration(bool val) { mixin(MSBPC(124, 0x1)); } } final void Notify(Actor Owner, AnimNodeSequence AnimSeqInstigator) { ubyte params[8]; params[] = 0; *cast(Actor*)params.ptr = Owner; *cast(AnimNodeSequence*)&params[4] = AnimSeqInstigator; (cast(ScriptObject)this).ProcessEvent(Functions.Notify, params.ptr, cast(void*)0); } }
D
E: c692, c49, c551, c517, c21, c44, c273, c585, c627, c746, c202, c363, c680, c405, c404, c449, c540, c99, c470, c266, c513, c332, c448, c136, c205, c832, c709, c105, c673, c697, c177, c693, c556, c314, c648, c91, c758, c628, c657, c391, c233, c180, c37, c753, c639, c553, c185, c353, c226, c554, c242, c735, c101, c439, c603, c529, c605, c309, c234, c769, c522, c370, c728, c102, c348, c620, c663, c30, c47, c516, c640, c809, c141, c13, c222, c711, c33, c818, c501, c817, c678, c184, c144, c25, c120, c828, c40, c75, c481, c197, c29, c50, c89, c583, c577, c97, c119, c93, c826, c106, c71, c174, c701, c140, c324, c173, c149, c827, c526, c339, c39, c225, c3, c382, c812, c713, c134, c36, c643, c159, c82, c820, c131, c182, c280, c706, c48, c253, c636, c710, c462, c27, c518, c276, c609, c357, c687, c562, c447, c107, c179, c199, c652, c45, c530, c350, c473, c824, c633, c541, c299, c317, c646, c606, c386, c533, c813, c96, c290, c800, c245, c155, c414, c485, c760, c587, c343, c257, c671, c354, c334, c54, c35, c138, c840, c786, c791, c564, c338, c433, c654, c375, c186, c191, c674, c424, c799, c806, c65, c279, c305, c219, c87, c146, c816, c72, c108, c677, c679, c269, c726, c829, c600, c104, c580, c20, c842, c792, c642, c113, c412, c135, c534, c807, c374, c751, c514, c145, c109, c667, c406, c178, c76, c84, c790, c227, c152, c352, c203, c125, c496, c744, c9, c399, c163, c236, c576, c844, c608, c232, c477, c454, c373, c214, c426, c46, c319, c653, c669, c695, c594, c691, c330, c171, c805, c249, c193, c230, c756, c475, c2, c116, c95, c74, c417, c528, c22, c524, c659, c14, c51, c250, c676, c112, c574, c0, c837, c79, c579, c326, c43, c662, c507, c712, c162, c571, c732, c244, c83, c773, c830, c19, c52, c189, c834, c770, c509, c154, c164, c254, c637, c10, c130, c810, c672, c468, c315, c632, c53, c228, c360, c4, c425, c766, c34, c291, c431, c390, c416, c1, c150, c649, c621, c327, c783, c596, c61, c70, c595, c287, c201, c670, c625, c626, c288, c329, c718, c767, c24, c484, c187, c361, c787, c393, c198, c801, c506, c613, c777, c715, c460, c277, c381, c142, c694, c308, c651, c127, c624, c394, c445, c128, c295, c160, c469, c256, c15, c121, c755, c294, c631, c761, c650, c23, c443, c80, c681, c593, c458, c436, c415, c200, c73, c103, c494, c100, c655, c298, c302, c11, c28, c167, c421, c78, c289, c555, c223, c607, c379, c114, c808, c351, c759, c383, c739, c397, c720. p0(E,E) c692,c49 c551,c517 c404,c449 c709,c105 c648,c91 c391,c233 c226,c554 c735,c758 c439,c603 c628,c242 c234,c769 c102,c348 c222,c711 c120,c828 c693,c29 c36,c101 c439,c439 c27,c673 c276,c609 c357,c91 c179,c199 c735,c44 c27,c517 c107,c447 c556,c556 c234,c386 c386,c386 c350,c350 c343,c526 c35,c554 c138,c840 c375,c199 c186,c191 c120,c89 c87,c146 c800,c40 c225,c29 c534,c45 c91,c91 c577,c577 c501,c501 c227,c710 c809,c809 c680,c680 c186,c518 c633,c583 c553,c20 c399,c44 c50,c828 c636,c653 c119,c273 c105,c105 c214,c583 c363,c363 c449,c449 c439,c386 c828,c828 c74,c485 c305,c812 c144,c144 c524,c654 c701,c242 c290,c76 c439,c125 c514,c514 c305,c159 c79,c579 c529,c529 c475,c40 c507,c507 c140,c571 c39,c197 c242,c242 c842,c713 c770,c509 c309,c76 c791,c746 c627,c104 c186,c447 c693,c177 c360,c4 c766,c197 c653,c653 c391,c753 c1,c449 c179,c150 c71,c753 c766,c425 c93,c254 c273,c273 c404,c33 c516,c516 c817,c449 c226,c254 c324,c529 c829,c626 c343,c711 c329,c269 c674,c439 c587,c363 c837,c131 c198,c529 c412,c350 c692,c659 c715,c439 c837,c809 c288,c713 c338,c338 c697,c653 c669,c37 c203,c185 c735,c21 c228,c556 c50,c652 c309,c605 c620,c663 c155,c155 c373,c353 c353,c353 c299,c155 c541,c818 c9,c501 c526,c827 c417,c620 c534,c83 c583,c583 c657,c657 c76,c76 c753,c753 c324,c140 c791,c202 c627,c585 c203,c353 c636,c99 c674,c433 c417,c35 c177,c659 c27,c824 c755,c680 c759,c383 c773,c829 c197,c197 c397,c150 c1,c643 c735,c245 c254,c254 . p6(E,E) c21,c44 c746,c202 c202,c202 c540,c540 c99,c99 c556,c314 c758,c44 c185,c353 c273,c529 c314,c556 c522,c522 c818,c818 c40,c540 c769,c769 c583,c583 c713,c134 c449,c643 c159,c159 c131,c131 c710,c462 c652,c652 c603,c386 c518,c518 c348,c155 c620,c35 c233,c753 c49,c49 c433,c439 c654,c654 c529,c273 c518,c191 c679,c679 c146,c350 c245,c245 c516,c680 c20,c20 c652,c828 c809,c131 c605,c76 c159,c812 c790,c363 c140,c529 c352,c120 c202,c746 c439,c439 c518,c840 c829,c242 c236,c576 c517,c673 c824,c673 c44,c21 c758,c245 c426,c46 c603,c603 c653,c99 c447,c518 c691,c330 c125,c386 c29,c29 c516,c2 c350,c146 c353,c522 c673,c517 c30,c680 c657,c657 c516,c30 c125,c603 c30,c30 c585,c104 c245,c44 c144,c676 c643,c449 c758,c21 c35,c620 c620,c620 c83,c83 c269,c501 c363,c790 c101,c556 c680,c30 c828,c828 c273,c273 c72,c315 c517,c517 c840,c518 c517,c824 c695,c695 c416,c533 c449,c33 c386,c125 c37,c338 c245,c758 c125,c125 c2,c516 c37,c37 c695,c583 c338,c338 c70,c595 c637,c637 c155,c348 c134,c134 c185,c185 c800,c625 c101,c101 c21,c758 c425,c197 c350,c350 c554,c554 c425,c425 c191,c447 c556,c101 c386,c603 c89,c89 c529,c140 c605,c605 c526,c711 c155,c155 c460,c277 c713,c713 c501,c501 c199,c199 c21,c21 c105,c105 c529,c529 c653,c653 c131,c809 c657,c242 c449,c449 c769,c386 c104,c585 c540,c40 c91,c91 c659,c637 c758,c758 c177,c29 c473,c357 c200,c73 c809,c809 c827,c827 c522,c353 c659,c49 c494,c842 c518,c447 c753,c753 c191,c518 c746,c746 c40,c40 c594,c167 c44,c44 c526,c526 c242,c657 c242,c242 c353,c185 c516,c516 c254,c254 c2,c2 c753,c233 c150,c199 c585,c585 c808,c351 c348,c348 c828,c89 c812,c812 . p1(E,E) c273,c273 c105,c105 c628,c657 c391,c753 c620,c663 c516,c516 c640,c809 c657,c657 c746,c746 c501,c501 c817,c449 c577,c577 c119,c273 c529,c529 c701,c657 c339,c39 c225,c29 c382,c812 c828,c828 c182,c280 c518,c518 c350,c350 c473,c824 c533,c813 c648,c91 c343,c711 c709,c105 c155,c155 c791,c746 c583,c583 c305,c812 c36,c556 c50,c828 c44,c44 c374,c751 c556,c556 c324,c529 c399,c44 c144,c144 c735,c44 c91,c91 c530,c45 c152,c155 c475,c40 c667,c529 c43,c662 c386,c386 c712,c433 c439,c386 c120,c828 c357,c91 c14,c516 c404,c449 c628,c242 c53,c146 c228,c556 c633,c583 c93,c254 c52,c52 c222,c711 c87,c350 c138,c518 c363,c363 c564,c501 c113,c746 c61,c753 c39,c197 c234,c386 c29,c29 c562,c670 c353,c353 c186,c518 c288,c713 c203,c353 c219,c810 c404,c33 c29,c673 c514,c514 c329,c269 c179,c199 c242,c242 c76,c76 c128,c266 c295,c160 c667,c273 c469,c256 c15,c121 c697,c653 c36,c679 c631,c516 c443,c80 c681,c826 c226,c254 c653,c653 c439,c125 c562,c562 c276,c609 c837,c809 c421,c78 c338,c338 c555,c810 c309,c76 c753,c753 c756,c125 c693,c29 c197,c197 c755,c516 c332,c353 c214,c583 c807,c353 . p10(E,E) c585,c627 c363,c363 c680,c405 c470,c266 c177,c693 c605,c309 c33,c404 c828,c50 c89,c120 c753,c391 c140,c324 c82,c820 c99,c636 c447,c107 c45,c530 c583,c633 c818,c541 c348,c299 c233,c391 c828,c120 c96,c290 c40,c800 c245,c735 c363,c587 c334,c54 c33,c786 c501,c564 c433,c674 c657,c701 c657,c628 c353,c807 c273,c667 c679,c84 c155,c152 c746,c791 c185,c203 c269,c9 c439,c674 c583,c214 c522,c807 c338,c669 c695,c633 c812,c305 c125,c439 c202,c791 c769,c234 c20,c553 c746,c113 c517,c27 c753,c71 c659,c177 c516,c14 c809,c837 c245,c162 c840,c138 c386,c234 c242,c773 c146,c87 c556,c36 c254,c93 c37,c669 c637,c177 c155,c299 c579,c79 c2,c14 c242,c701 c199,c375 c425,c766 c191,c186 c199,c179 c350,c412 c711,c222 c150,c179 c40,c475 c449,c404 c29,c225 c254,c226 c131,c837 c353,c332 c529,c324 c29,c693 c643,c1 c447,c186 c51,c393 c21,c735 c654,c524 c76,c309 c353,c203 c104,c627 c142,c694 c529,c667 c556,c228 c624,c394 c338,c473 c673,c27 c518,c186 c439,c715 c49,c692 c516,c755 c540,c475 c449,c1 c82,c761 c554,c226 c458,c95 c790,c363 c436,c415 c30,c755 c655,c662 c526,c343 c302,c609 c758,c735 c659,c692 c386,c439 c105,c709 c680,c755 c350,c87 c517,c551 c812,c382 c101,c36 c197,c39 c242,c628 c620,c417 c91,c357 . p9(E,E) c363,c363 c657,c242 c101,c556 c197,c197 c33,c449 c105,c105 c44,c44 c3,c680 c643,c449 c687,c562 c89,c828 c439,c439 c522,c353 c177,c29 c758,c44 c30,c680 c680,c516 c338,c338 c424,c799 c652,c828 c447,c279 c269,c501 c829,c242 c642,c131 c276,c514 c583,c583 c449,c449 c273,c273 c191,c518 c744,c663 c233,c753 c140,c529 c540,c40 c185,c353 c840,c518 c433,c439 c30,c516 c19,c52 c828,c828 c10,c130 c131,c809 c276,c171 c526,c711 c314,c556 c676,c144 c245,c44 c254,c254 c425,c197 c21,c44 c19,c609 c447,c518 c596,c141 c746,c201 c657,c657 c840,c585 c556,c556 c146,c350 c83,c577 c76,c76 c603,c386 c37,c338 c651,c127 c40,c40 c605,c76 c753,c753 c45,c45 c155,c155 c125,c386 c83,c45 c518,c518 c603,c125 c242,c242 c134,c713 c29,c29 c448,c657 c670,c93 c150,c199 c529,c273 c353,c353 c516,c516 . p2(E,E) c513,c332 c448,c136 c205,c832 c673,c697 c639,c553 c106,c71 c174,c628 c646,c606 c414,c119 c485,c760 c726,c382 c317,c842 c792,c225 c113,c27 c125,c412 c496,c530 c232,c477 c163,c50 c454,c373 c171,c756 c22,c152 c112,c574 c174,c701 c732,c244 c834,c35 c728,c290 c431,c390 c695,c399 c621,c327 c613,c186 c777,c587 c381,c317 c294,c162 c414,c298 c783,c640 . p7(E,E) c180,c37 c354,c448 c334,c594 c605,c0 c830,c84 c273,c24 c533,c657 c146,c100 c433,c242 . p5(E,E) c370,c728 c75,c481 c826,c89 c827,c526 c806,c65 c501,c564 c412,c135 c406,c178 c163,c807 c844,c608 c116,c95 c357,c485 c679,c84 c199,c375 c154,c164 c386,c439 c709,c790 c37,c553 c718,c767 c484,c187 c405,c308 c197,c39 c607,c379 c556,c228 c374,c114 . p8(E,E) c30,c47 c141,c13 c97,c746 c93,c40 c48,c253 c816,c72 c386,c319 c193,c230 c417,c528 c697,c632 c361,c182 c787,c82 c801,c506 c593,c773 c52,c834 c11,c28 c289,c266 c295,c739 c449,c720 . p3(E,E) c678,c184 c657,c174 c706,c620 c242,c174 c713,c317 c711,c219 c108,c677 c104,c580 c526,c177 c273,c414 c125,c171 c805,c249 c653,c673 c326,c553 c155,c22 c554,c834 c810,c642 c672,c842 c468,c107 c34,c291 c45,c496 c332,c606 c824,c113 c809,c783 c753,c106 c76,c728 c445,c812 c29,c792 c509,c837 c650,c23 c553,c103 c254,c223 c353,c454 c812,c726 . p4(E,E) c144,c25 c173,c149 c769,c257 c106,c671 c600,c48 c145,c109 c475,c554 c447,c191 c51,c250 c412,c189 c649,c21 c695,c113 c119,c287 c640,c135 .
D
module core.lexer; /// enum TokenId { number, identifier, string_, parentheses, brackets, list, } /// Token struct Token { TokenId id; string lexeme; this(TokenId id, string lexeme) { this.lexeme = lexeme; this.id = id; } bool opEquals()(auto ref const Token other) const { return id == other.id && lexeme == other.lexeme; } } /// Find next token in code and return it in t. /// Tokens are integral literals, string literals and identifiers. /// It ignores white space. /// Returns: true, if a token was read. Otherwise false. bool nextToken(ref string code, out Token t) { skipWhitespace(code); string saveCode = code; if (code.length == 0) return false; switch (code[0]) { case '(', ')': t = Token(TokenId.parentheses, code[0 .. 1]); code = code[1 .. $]; return true; case '{', '}': t = Token(TokenId.brackets, code[0 .. 1]); code = code[1 .. $]; return true; case '0': .. case '9': import core.lexer.integral_literal; if (!consumeIntegralLiteral(code)) { import core.diagnostics; lexingError(ErrorId.expectedNumber, code); return false; } t = Token(TokenId.number, saveCode[0 .. saveCode.length - code.length]); return true; case '"': import core.lexer.string_literal; if (!consumeStringLiteral(code)) { import core.diagnostics; lexingError(ErrorId.expectedString, code); return false; } t = Token(TokenId.string_, saveCode[0 .. saveCode.length - code.length]); return true; default: import core.lexer.identifier; if (!consumeIdentifier(code)) { import core.diagnostics; lexingError(ErrorId.expectedIdentifier, code); return false; } t = Token(TokenId.identifier, saveCode[0 .. saveCode.length - code.length]); return true; } assert(false); } import core.diagnostics; /// Reports an error with given id for lexing. void lexingError(ErrorId id, string code) { import std.string : format; immutable auto savedCode = code; Token t; auto str = nextToken(code, t) ? format(" (a %s)", t) : ""; auto got = savedCode[0 .. savedCode.length - code.length]; import core.diagnostics : Error; auto e = Error(id, format("got '%s'%s", got, str)); auto l = locateFromCode(savedCode); if (l.isValid()) e.location = l; error(e); } unittest { string code; Token t; code = ""; assert(!nextToken(code, t)); assert(code == ""); code = " "; assert(!nextToken(code, t)); assert(code == ""); code = "1587"; assert(nextToken(code, t)); assert(code == "", code); assert(t == Token(TokenId.number, "1587")); code = "0x234+12"; assert(nextToken(code, t)); assert(code == "+12", code); assert(t == Token(TokenId.number, "0x234")); code = "+12"; assert(nextToken(code, t)); assert(code == "", code); assert(t == Token(TokenId.identifier, "+12")); code = " \n\r2"; assert(nextToken(code, t)); assert(code == "", code); assert(t == Token(TokenId.number, "2")); code = "2 1"; assert(nextToken(code, t)); assert(code == " 1", code); assert(t == Token(TokenId.number, "2")); code = "2uL"; assert(nextToken(code, t)); assert(code == "", code); assert(t == Token(TokenId.number, "2uL")); code = "2u 1"; assert(nextToken(code, t)); assert(code == " 1", code); assert(t == Token(TokenId.number, "2u")); code = "0b12"; assert(nextToken(code, t)); assert(code == "2", code); assert(t == Token(TokenId.number, "0b1")); code = "0a"; assert(nextToken(code, t)); assert(code == "a", code); code = "(a"; assert(nextToken(code, t)); assert(code == "a", code); assert(t == Token(TokenId.parentheses, "(")); code = "0xa_23_42+foo"; assert(nextToken(code, t)); assert(code == "+foo", code); assert(t == Token(TokenId.number, "0xa_23_42")); code = "foo"; assert(nextToken(code, t)); assert(code == "", code); assert(t == Token(TokenId.identifier, "foo")); code = "α"; assert(nextToken(code, t)); assert(code == "", code); assert(t == Token(TokenId.identifier, "α")); code = ";"; assert(nextToken(code, t)); assert(code == "", code); assert(t == Token(TokenId.identifier, ";")); code = "0ba"; assert(!nextToken(code, t)); assert(code == "a", code); code = "@#"; assert(nextToken(code, t)); assert(code == "", code); assert(t == Token(TokenId.identifier, "@#")); code = "_foo"; assert(nextToken(code, t)); assert(code == "", code); assert(t == Token(TokenId.identifier, "_foo")); code = "_foo_bar"; assert(nextToken(code, t)); assert(code == "", code); assert(t == Token(TokenId.identifier, "_foo_bar")); code = "F00"; assert(nextToken(code, t)); assert(code == "", code); assert(t == Token(TokenId.identifier, "F00")); code = "foo@bar"; assert(nextToken(code, t)); assert(code == "", code); assert(t == Token(TokenId.identifier, "foo@bar")); code = "C++"; assert(nextToken(code, t)); assert(code == "", code); assert(t == Token(TokenId.identifier, "C++")); code = "\"\"wef"; assert(nextToken(code, t)); assert(code == "wef", code); assert(t == Token(TokenId.string_, "\"\"")); code = "\"@ Î ±\n…\"wef"; assert(nextToken(code, t)); assert(code == "wef", code); assert(t == Token(TokenId.string_, "\"@ Î ±\n…\"")); } /// Like nextToken but does not modify code. bool peekToken(string code, out Token t) { return nextToken(code, t); } void skipWhitespace(ref string code) { import std.ascii; // skip white space while (code.length > 0 && isWhite(code[0])) code = code[1 .. $]; }
D
a Japanese form of wrestling
D
instance STRF_1106_Fed (Npc_Default) { // ------ NSC ------ name = "Fed"; guild = GIL_OUT; id = 1106; voice = 8; flags = 0; //NPC_FLAG_IMMORTAL oder 0 npctype = NPCTYPE_MAIN; // ------ Attribute ------ B_SetAttributesToChapter (self, 2); //setzt Attribute und LEVEL entsprechend dem angegebenen Kapitel (1-6) // ------ Kampf-Taktik ------ fight_tactic = FAI_HUMAN_COWARD; // MASTER / STRONG / COWARD // ------ Equippte Waffen ------ //Munition wird automatisch generiert, darf aber angegeben werden EquipItem (self, ItMw_2H_Axe_L_01); // ------ 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_P_Gilbert, BodyTex_N, ITAR_Prisoner); Mdl_SetModelFatness (self, 0); Mdl_ApplyOverlayMds (self, "Humans_Tired.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, 15); //Grenzen für Talent-Level liegen bei 30 und 60 // ------ TA anmelden ------ daily_routine = Rtn_Start_1106; }; FUNC VOID Rtn_Start_1106 () { TA_Pick_Ore (08,00,23,00,"OW_NEWMINE_06_B"); TA_Pick_Ore (23,00,08,00,"OW_NEWMINE_06_B"); };
D
module krepel.game_framework; public import krepel.game_framework.tick; public import krepel.game_framework.game_framework_manager;
D
a native or inhabitant of Finland
D
module internal.variable; import internal.val; import internal.typeinfo; struct RelativeVarIndex { size_t depth; size_t index; } final class Variable { enum Type { local, global, } Type type; TI ti; string name; size_t index; Val init_val = void; private this(TI t, string n) { ti = t; name = n; } static Variable new_global(TI ti, string name, Val val) { auto v = new Variable(ti, name); v.type = Type.global; v.init_val = val; return v; } static Variable new_local(TI ti, string name) { auto v = new Variable(ti, name); v.type = Type.local; return v; } bool local() @property { return type == Type.local; } bool global() @property { return type == Type.global; } }
D
an offensive term for Roman Catholics of or relating to or supporting Romanism
D
/******************************************************************************* copyright: Copyright (c) 2007 the Tango team. All rights reserved license: BSD style: $(LICENSE) version: Initial release: July 2007 author: Cyborg16, Sean Kelly *******************************************************************************/ module tango.sys.win32.SpecialPath; private import tango.text.convert.Utf; private import tango.sys.Common; private import tango.sys.win32.CodePage; private import tango.stdc.stringz; pragma(lib, "shell32.lib"); version(Win32SansUnicode) extern(Windows) int SHGetSpecialFolderPathA(HWND, LPCSTR, int, BOOL); else extern(Windows) int SHGetSpecialFolderPathW(HWND, LPCWSTR, int, BOOL); enum { CSIDL_DESKTOP = 0, CSIDL_INTERNET, CSIDL_PROGRAMS, CSIDL_CONTROLS, CSIDL_PRINTERS, CSIDL_PERSONAL, CSIDL_FAVORITES, CSIDL_STARTUP, CSIDL_RECENT, CSIDL_SENDTO, CSIDL_BITBUCKET, CSIDL_STARTMENU, // = 11 CSIDL_DESKTOPDIRECTORY = 16, CSIDL_DRIVES, CSIDL_NETWORK, CSIDL_NETHOOD, CSIDL_FONTS, CSIDL_TEMPLATES, CSIDL_COMMON_STARTMENU, CSIDL_COMMON_PROGRAMS, CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY, CSIDL_APPDATA, CSIDL_PRINTHOOD, CSIDL_LOCAL_APPDATA, CSIDL_ALTSTARTUP, CSIDL_COMMON_ALTSTARTUP, CSIDL_COMMON_FAVORITES, CSIDL_INTERNET_CACHE, CSIDL_COOKIES, CSIDL_HISTORY, CSIDL_COMMON_APPDATA, CSIDL_WINDOWS, CSIDL_SYSTEM, CSIDL_PROGRAM_FILES, CSIDL_MYPICTURES, CSIDL_PROFILE, CSIDL_SYSTEMX86, CSIDL_PROGRAM_FILESX86, CSIDL_PROGRAM_FILES_COMMON, CSIDL_PROGRAM_FILES_COMMONX86, CSIDL_COMMON_TEMPLATES, CSIDL_COMMON_DOCUMENTS, CSIDL_COMMON_ADMINTOOLS, CSIDL_ADMINTOOLS, CSIDL_CONNECTIONS, // =49 CSIDL_COMMON_MUSIC = 53, CSIDL_COMMON_PICTURES, CSIDL_COMMON_VIDEO, CSIDL_RESOURCES, CSIDL_RESOURCES_LOCALIZED, CSIDL_COMMON_OEM_LINKS, CSIDL_CDBURN_AREA, // = 59 CSIDL_COMPUTERSNEARME = 61, CSIDL_FLAG_DONT_VERIFY = 0x4000, CSIDL_FLAG_CREATE = 0x8000, CSIDL_FLAG_MASK = 0xFF00 } /** * Get a special path (on Windows). * * Params: * csidl = Enum of path to get * * Throws: * * * Returns: * A string containing the path */ char[] getSpecialPath( int csidl ) { version( Win32SansUnicode ) { char* spath = (new char[MAX_PATH]).ptr; scope(exit) delete spath; if( !SHGetSpecialFolderPathA( null, spath, csidl, true ) ) throw new Exception( "getSpecialPath :: " ~ SysError.lastMsg.idup ); char[] dpath = new char[MAX_PATH]; return CodePage.from(fromStringz(spath), dpath); } else { wchar* spath = (new wchar[MAX_PATH]).ptr; scope(exit) delete spath; if( !SHGetSpecialFolderPathW( null, spath, csidl, true ) ) throw new Exception( "getSpecialPath :: " ~ SysError.lastMsg.idup ); return toString(fromString16z(spath)); } }
D
a small inexpensive mass-produced article miscellaneous curios
D
module derelict.opengl; public import derelict.opengl.gl, derelict.opengl.impl, derelict.opengl.types;
D
module markovd.util; import markovd.core; import std.stdio; /** This function steps through a markov chain set and returns the selected values in an array. license: BSD 3-clause license authors: John Whitley, dogjaw2233@protonmail.com Date: August 27, 2017 Version: 0 Params: start = The starting node. iterator = Amount of times to step through the chain. */ auto stepChain(T)(MarkovNode!T *start, long iterator) { T[] rarr; int i; MarkovNode!T *curnode = start; for (i = 1; i < iterator; i++) { rarr ~= curnode.value; curnode = curnode.nextBranch; } return rarr; }
D
// Written in the D programming language. /++ $(SECTION Overview) $(P The $(D std.uni) module provides an implementation of fundamental Unicode algorithms and data structures. This doesn't include UTF encoding and decoding primitives, see $(XREF _utf, decode) and $(XREF _utf, encode) in std.utf for this functionality. ) $(P All primitives listed operate on Unicode characters and sets of characters. For functions which operate on ASCII characters and ignore Unicode $(CHARACTERS), see $(LINK2 std_ascii.html, std.ascii). For definitions of Unicode $(CHARACTER), $(CODEPOINT) and other terms used throughout this module see the $(S_LINK Terminology, terminology) section below. ) $(P The focus of this module is the core needs of developing Unicode-aware applications. To that effect it provides the following optimized primitives: ) $(UL $(LI Character classification by category and common properties: $(LREF isAlpha), $(LREF isWhite) and others. ) $(LI Case-insensitive string comparison ($(LREF sicmp), $(LREF icmp)). ) $(LI Converting text to any of the four normalization forms via $(LREF normalize). ) $(LI Decoding ($(LREF decodeGrapheme)) and iteration ($(LREF byGrapheme), $(LREF graphemeStride)) by user-perceived characters, that is by $(LREF Grapheme) clusters. ) $(LI Decomposing and composing of individual character(s) according to canonical or compatibility rules, see $(LREF compose) and $(LREF decompose), including the specific version for Hangul syllables $(LREF composeJamo) and $(LREF decomposeHangul). ) ) $(P It's recognized that an application may need further enhancements and extensions, such as less commonly known algorithms, or tailoring existing ones for region specific needs. To help users with building any extra functionality beyond the core primitives, the module provides: ) $(UL $(LI $(LREF CodepointSet), a type for easy manipulation of sets of characters. Besides the typical set algebra it provides an unusual feature: a D source code generator for detection of $(CODEPOINTS) in this set. This is a boon for meta-programming parser frameworks, and is used internally to power classification in small sets like $(LREF isWhite). ) $(LI A way to construct optimal packed multi-stage tables also known as a special case of $(LUCKY Trie). The functions $(LREF codepointTrie), $(LREF codepointSetTrie) construct custom tries that map dchar to value. The end result is a fast and predictable $(BIGOH 1) lookup that powers functions like $(LREF isAlpha) and $(LREF combiningClass), but for user-defined data sets. ) $(LI Generally useful building blocks for customized normalization: $(LREF combiningClass) for querying combining class and $(LREF allowedIn) for testing the Quick_Check property of a given normalization form. ) $(LI Access to a large selection of commonly used sets of $(CODEPOINTS). $(S_LINK Unicode properties, Supported sets) include Script, Block and General Category. The exact contents of a set can be observed in the CLDR utility, on the $(WEB www.unicode.org/cldr/utility/properties.jsp, property index) page of the Unicode website. See $(LREF unicode) for easy and (optionally) compile-time checked set queries. ) ) $(SECTION Synopsis) --- import std.uni; void main() { // initialize code point sets using script/block or property name // now 'set' contains code points from both scripts. auto set = unicode("Cyrillic") | unicode("Armenian"); // same thing but simpler and checked at compile-time auto ascii = unicode.ASCII; auto currency = unicode.Currency_Symbol; // easy set ops auto a = set & ascii; assert(a.empty); // as it has no intersection with ascii a = set | ascii; auto b = currency - a; // subtract all ASCII, Cyrillic and Armenian // some properties of code point sets assert(b.length > 45); // 46 items in Unicode 6.1, even more in 6.2 // testing presence of a code point in a set // is just fine, it is O(logN) assert(!b['$']); assert(!b['\u058F']); // Armenian dram sign assert(b['¥']); // building fast lookup tables, these guarantee O(1) complexity // 1-level Trie lookup table essentially a huge bit-set ~262Kb auto oneTrie = toTrie!1(b); // 2-level far more compact but typically slightly slower auto twoTrie = toTrie!2(b); // 3-level even smaller, and a bit slower yet auto threeTrie = toTrie!3(b); assert(oneTrie['£']); assert(twoTrie['£']); assert(threeTrie['£']); // build the trie with the most sensible trie level // and bind it as a functor auto cyrillicOrArmenian = toDelegate(set); auto balance = find!(cyrillicOrArmenian)("Hello ընկեր!"); assert(balance == "ընկեր!"); // compatible with bool delegate(dchar) bool delegate(dchar) bindIt = cyrillicOrArmenian; // Normalization string s = "Plain ascii (and not only), is always normalized!"; assert(s is normalize(s));// is the same string string nonS = "A\u0308ffin"; // A ligature auto nS = normalize(nonS); // to NFC, the W3C endorsed standard assert(nS == "Äffin"); assert(nS != nonS); string composed = "Äffin"; assert(normalize!NFD(composed) == "A\u0308ffin"); // to NFKD, compatibility decomposition useful for fuzzy matching/searching assert(normalize!NFKD("2¹⁰") == "210"); } --- $(SECTION Terminology) $(P The following is a list of important Unicode notions and definitions. Any conventions used specifically in this module alone are marked as such. The descriptions are based on the formal definition as found in $(WEB http://www.unicode.org/versions/Unicode6.2.0/ch03.pdf, chapter three of The Unicode Standard Core Specification.) ) $(P $(DEF Abstract character) A unit of information used for the organization, control, or representation of textual data. Note that: $(UL $(LI When representing data, the nature of that data is generally symbolic as opposed to some other kind of data (for example, visual).) $(LI An abstract character has no concrete form and should not be confused with a $(S_LINK Glyph, glyph).) $(LI An abstract character does not necessarily correspond to what a user thinks of as a “character” and should not be confused with a $(LREF Grapheme).) $(LI The abstract characters encoded (see Encoded character) are known as Unicode abstract characters.) $(LI Abstract characters not directly encoded by the Unicode Standard can often be represented by the use of combining character sequences.) ) ) $(P $(DEF Canonical decomposition) The decomposition of a character or character sequence that results from recursively applying the canonical mappings found in the Unicode Character Database and these described in Conjoining Jamo Behavior (section 12 of $(WEB www.unicode.org/uni2book/ch03.pdf, Unicode Conformance)). ) $(P $(DEF Canonical composition) The precise definition of the Canonical composition is the algorithm as specified in $(WEB www.unicode.org/uni2book/ch03.pdf, Unicode Conformance) section 11. Informally it's the process that does the reverse of the canonical decomposition with the addition of certain rules that e.g. prevent legacy characters from appearing in the composed result. ) $(P $(DEF Canonical equivalent) Two character sequences are said to be canonical equivalents if their full canonical decompositions are identical. ) $(P $(DEF Character) Typically differs by context. For the purpose of this documentation the term $(I character) implies $(I encoded character), that is, a code point having an assigned abstract character (a symbolic meaning). ) $(P $(DEF Code point) Any value in the Unicode codespace; that is, the range of integers from 0 to 10FFFF (hex). Not all code points are assigned to encoded characters. ) $(P $(DEF Code unit) The minimal bit combination that can represent a unit of encoded text for processing or interchange. Depending on the encoding this could be: 8-bit code units in the UTF-8 ($(D char)), 16-bit code units in the UTF-16 ($(D wchar)), and 32-bit code units in the UTF-32 ($(D dchar)). $(I Note that in UTF-32, a code unit is a code point and is represented by the D $(D dchar) type.) ) $(P $(DEF Combining character) A character with the General Category of Combining Mark(M). $(UL $(LI All characters with non-zero canonical combining class are combining characters, but the reverse is not the case: there are combining characters with a zero combining class. ) $(LI These characters are not normally used in isolation unless they are being described. They include such characters as accents, diacritics, Hebrew points, Arabic vowel signs, and Indic matras. ) ) ) $(P $(DEF Combining class) A numerical value used by the Unicode Canonical Ordering Algorithm to determine which sequences of combining marks are to be considered canonically equivalent and which are not. ) $(P $(DEF Compatibility decomposition) The decomposition of a character or character sequence that results from recursively applying both the compatibility mappings and the canonical mappings found in the Unicode Character Database, and those described in Conjoining Jamo Behavior no characters can be further decomposed. ) $(P $(DEF Compatibility equivalent) Two character sequences are said to be compatibility equivalents if their full compatibility decompositions are identical. ) $(P $(DEF Encoded character) An association (or mapping) between an abstract character and a code point. ) $(P $(DEF Glyph) The actual, concrete image of a glyph representation having been rasterized or otherwise imaged onto some display surface. ) $(P $(DEF Grapheme base) A character with the property Grapheme_Base, or any standard Korean syllable block. ) $(P $(DEF Grapheme cluster) Defined as the text between grapheme boundaries as specified by Unicode Standard Annex #29, $(WEB www.unicode.org/reports/tr29/, Unicode text segmentation). Important general properties of a grapheme: $(UL $(LI The grapheme cluster represents a horizontally segmentable unit of text, consisting of some grapheme base (which may consist of a Korean syllable) together with any number of nonspacing marks applied to it. ) $(LI A grapheme cluster typically starts with a grapheme base and then extends across any subsequent sequence of nonspacing marks. A grapheme cluster is most directly relevant to text rendering and processes such as cursor placement and text selection in editing, but may also be relevant to comparison and searching. ) $(LI For many processes, a grapheme cluster behaves as if it was a single character with the same properties as its grapheme base. Effectively, nonspacing marks apply $(I graphically) to the base, but do not change its properties. ) ) $(P This module defines a number of primitives that work with graphemes: $(LREF Grapheme), $(LREF decodeGrapheme) and $(LREF graphemeStride). All of them are using $(I extended grapheme) boundaries as defined in the aforementioned standard annex. ) ) $(P $(DEF Nonspacing mark) A combining character with the General Category of Nonspacing Mark (Mn) or Enclosing Mark (Me). ) $(P $(DEF Spacing mark) A combining character that is not a nonspacing mark.) $(SECTION Normalization) $(P The concepts of $(S_LINK Canonical equivalent, canonical equivalent) or $(S_LINK Compatibility equivalent, compatibility equivalent) characters in the Unicode Standard make it necessary to have a full, formal definition of equivalence for Unicode strings. String equivalence is determined by a process called normalization, whereby strings are converted into forms which are compared directly for identity. This is the primary goal of the normalization process, see the function $(LREF normalize) to convert into any of the four defined forms. ) $(P A very important attribute of the Unicode Normalization Forms is that they must remain stable between versions of the Unicode Standard. A Unicode string normalized to a particular Unicode Normalization Form in one version of the standard is guaranteed to remain in that Normalization Form for implementations of future versions of the standard. ) $(P The Unicode Standard specifies four normalization forms. Informally, two of these forms are defined by maximal decomposition of equivalent sequences, and two of these forms are defined by maximal $(I composition) of equivalent sequences. $(UL $(LI Normalization Form D (NFD): The $(S_LINK Canonical decomposition, canonical decomposition) of a character sequence.) $(LI Normalization Form KD (NFKD): The $(S_LINK Compatibility decomposition, compatibility decomposition) of a character sequence.) $(LI Normalization Form C (NFC): The canonical composition of the $(S_LINK Canonical decomposition, canonical decomposition) of a coded character sequence.) $(LI Normalization Form KC (NFKC): The canonical composition of the $(S_LINK Compatibility decomposition, compatibility decomposition) of a character sequence) ) ) $(P The choice of the normalization form depends on the particular use case. NFC is the best form for general text, since it's more compatible with strings converted from legacy encodings. NFKC is the preferred form for identifiers, especially where there are security concerns. NFD and NFKD are the most useful for internal processing. ) $(SECTION Construction of lookup tables) $(P The Unicode standard describes a set of algorithms that depend on having the ability to quickly look up various properties of a code point. Given the the codespace of about 1 million $(CODEPOINTS), it is not a trivial task to provide a space-efficient solution for the multitude of properties.) $(P Common approaches such as hash-tables or binary search over sorted code point intervals (as in $(LREF InversionList)) are insufficient. Hash-tables have enormous memory footprint and binary search over intervals is not fast enough for some heavy-duty algorithms. ) $(P The recommended solution (see Unicode Implementation Guidelines) is using multi-stage tables that are an implementation of the $(WEB http://en.wikipedia.org/wiki/Trie, Trie) data structure with integer keys and a fixed number of stages. For the remainder of the section this will be called a fixed trie. The following describes a particular implementation that is aimed for the speed of access at the expense of ideal size savings. ) $(P Taking a 2-level Trie as an example the principle of operation is as follows. Split the number of bits in a key (code point, 21 bits) into 2 components (e.g. 15 and 8). The first is the number of bits in the index of the trie and the other is number of bits in each page of the trie. The layout of the trie is then an array of size 2^^bits-of-index followed an array of memory chunks of size 2^^bits-of-page/bits-per-element. ) $(P The number of pages is variable (but not less then 1) unlike the number of entries in the index. The slots of the index all have to contain a number of a page that is present. The lookup is then just a couple of operations - slice the upper bits, lookup an index for these, take a page at this index and use the lower bits as an offset within this page. Assuming that pages are laid out consequently in one array at $(D pages), the pseudo-code is: ) --- auto elemsPerPage = (2 ^^ bits_per_page) / Value.sizeOfInBits; pages[index[n >> bits_per_page]][n & (elemsPerPage - 1)]; --- $(P Where if $(D elemsPerPage) is a power of 2 the whole process is a handful of simple instructions and 2 array reads. Subsequent levels of the trie are introduced by recursing on this notion - the index array is treated as values. The number of bits in index is then again split into 2 parts, with pages over 'current-index' and the new 'upper-index'. ) $(P For completeness a level 1 trie is simply an array. The current implementation takes advantage of bit-packing values when the range is known to be limited in advance (such as $(D bool)). See also $(LREF BitPacked) for enforcing it manually. The major size advantage however comes from the fact that multiple $(B identical pages on every level are merged) by construction. ) $(P The process of constructing a trie is more involved and is hidden from the user in a form of the convenience functions $(LREF codepointTrie), $(LREF codepointSetTrie) and the even more convenient $(LREF toTrie). In general a set or built-in AA with $(D dchar) type can be turned into a trie. The trie object in this module is read-only (immutable); it's effectively frozen after construction. ) $(SECTION Unicode properties) $(P This is a full list of Unicode properties accessible through $(LREF unicode) with specific helpers per category nested within. Consult the $(WEB www.unicode.org/cldr/utility/properties.jsp, CLDR utility) when in doubt about the contents of a particular set.) $(P General category sets listed below are only accessible with the $(LREF unicode) shorthand accessor.) $(BOOKTABLE $(B General category ), $(TR $(TH Abb.) $(TH Long form) $(TH Abb.) $(TH Long form)$(TH Abb.) $(TH Long form)) $(TR $(TD L) $(TD Letter) $(TD Cn) $(TD Unassigned) $(TD Po) $(TD Other_Punctuation)) $(TR $(TD Ll) $(TD Lowercase_Letter) $(TD Co) $(TD Private_Use) $(TD Ps) $(TD Open_Punctuation)) $(TR $(TD Lm) $(TD Modifier_Letter) $(TD Cs) $(TD Surrogate) $(TD S) $(TD Symbol)) $(TR $(TD Lo) $(TD Other_Letter) $(TD N) $(TD Number) $(TD Sc) $(TD Currency_Symbol)) $(TR $(TD Lt) $(TD Titlecase_Letter) $(TD Nd) $(TD Decimal_Number) $(TD Sk) $(TD Modifier_Symbol)) $(TR $(TD Lu) $(TD Uppercase_Letter) $(TD Nl) $(TD Letter_Number) $(TD Sm) $(TD Math_Symbol)) $(TR $(TD M) $(TD Mark) $(TD No) $(TD Other_Number) $(TD So) $(TD Other_Symbol)) $(TR $(TD Mc) $(TD Spacing_Mark) $(TD P) $(TD Punctuation) $(TD Z) $(TD Separator)) $(TR $(TD Me) $(TD Enclosing_Mark) $(TD Pc) $(TD Connector_Punctuation) $(TD Zl) $(TD Line_Separator)) $(TR $(TD Mn) $(TD Nonspacing_Mark) $(TD Pd) $(TD Dash_Punctuation) $(TD Zp) $(TD Paragraph_Separator)) $(TR $(TD C) $(TD Other) $(TD Pe) $(TD Close_Punctuation) $(TD Zs) $(TD Space_Separator)) $(TR $(TD Cc) $(TD Control) $(TD Pf) $(TD Final_Punctuation) $(TD -) $(TD Any)) $(TR $(TD Cf) $(TD Format) $(TD Pi) $(TD Initial_Punctuation) $(TD -) $(TD ASCII)) ) $(P Sets for other commonly useful properties that are accessible with $(LREF unicode):) $(BOOKTABLE $(B Common binary properties), $(TR $(TH Name) $(TH Name) $(TH Name)) $(TR $(TD Alphabetic) $(TD Ideographic) $(TD Other_Uppercase)) $(TR $(TD ASCII_Hex_Digit) $(TD IDS_Binary_Operator) $(TD Pattern_Syntax)) $(TR $(TD Bidi_Control) $(TD ID_Start) $(TD Pattern_White_Space)) $(TR $(TD Cased) $(TD IDS_Trinary_Operator) $(TD Quotation_Mark)) $(TR $(TD Case_Ignorable) $(TD Join_Control) $(TD Radical)) $(TR $(TD Dash) $(TD Logical_Order_Exception) $(TD Soft_Dotted)) $(TR $(TD Default_Ignorable_Code_Point) $(TD Lowercase) $(TD STerm)) $(TR $(TD Deprecated) $(TD Math) $(TD Terminal_Punctuation)) $(TR $(TD Diacritic) $(TD Noncharacter_Code_Point) $(TD Unified_Ideograph)) $(TR $(TD Extender) $(TD Other_Alphabetic) $(TD Uppercase)) $(TR $(TD Grapheme_Base) $(TD Other_Default_Ignorable_Code_Point) $(TD Variation_Selector)) $(TR $(TD Grapheme_Extend) $(TD Other_Grapheme_Extend) $(TD White_Space)) $(TR $(TD Grapheme_Link) $(TD Other_ID_Continue) $(TD XID_Continue)) $(TR $(TD Hex_Digit) $(TD Other_ID_Start) $(TD XID_Start)) $(TR $(TD Hyphen) $(TD Other_Lowercase) ) $(TR $(TD ID_Continue) $(TD Other_Math) ) ) $(P Bellow is the table with block names accepted by $(LREF unicode.block). Note that the shorthand version $(LREF unicode) requires "In" to be prepended to the names of blocks so as to disambiguate scripts and blocks.) $(BOOKTABLE $(B Blocks), $(TR $(TD Aegean Numbers) $(TD Ethiopic Extended) $(TD Mongolian)) $(TR $(TD Alchemical Symbols) $(TD Ethiopic Extended-A) $(TD Musical Symbols)) $(TR $(TD Alphabetic Presentation Forms) $(TD Ethiopic Supplement) $(TD Myanmar)) $(TR $(TD Ancient Greek Musical Notation) $(TD General Punctuation) $(TD Myanmar Extended-A)) $(TR $(TD Ancient Greek Numbers) $(TD Geometric Shapes) $(TD New Tai Lue)) $(TR $(TD Ancient Symbols) $(TD Georgian) $(TD NKo)) $(TR $(TD Arabic) $(TD Georgian Supplement) $(TD Number Forms)) $(TR $(TD Arabic Extended-A) $(TD Glagolitic) $(TD Ogham)) $(TR $(TD Arabic Mathematical Alphabetic Symbols) $(TD Gothic) $(TD Ol Chiki)) $(TR $(TD Arabic Presentation Forms-A) $(TD Greek and Coptic) $(TD Old Italic)) $(TR $(TD Arabic Presentation Forms-B) $(TD Greek Extended) $(TD Old Persian)) $(TR $(TD Arabic Supplement) $(TD Gujarati) $(TD Old South Arabian)) $(TR $(TD Armenian) $(TD Gurmukhi) $(TD Old Turkic)) $(TR $(TD Arrows) $(TD Halfwidth and Fullwidth Forms) $(TD Optical Character Recognition)) $(TR $(TD Avestan) $(TD Hangul Compatibility Jamo) $(TD Oriya)) $(TR $(TD Balinese) $(TD Hangul Jamo) $(TD Osmanya)) $(TR $(TD Bamum) $(TD Hangul Jamo Extended-A) $(TD Phags-pa)) $(TR $(TD Bamum Supplement) $(TD Hangul Jamo Extended-B) $(TD Phaistos Disc)) $(TR $(TD Basic Latin) $(TD Hangul Syllables) $(TD Phoenician)) $(TR $(TD Batak) $(TD Hanunoo) $(TD Phonetic Extensions)) $(TR $(TD Bengali) $(TD Hebrew) $(TD Phonetic Extensions Supplement)) $(TR $(TD Block Elements) $(TD High Private Use Surrogates) $(TD Playing Cards)) $(TR $(TD Bopomofo) $(TD High Surrogates) $(TD Private Use Area)) $(TR $(TD Bopomofo Extended) $(TD Hiragana) $(TD Rejang)) $(TR $(TD Box Drawing) $(TD Ideographic Description Characters) $(TD Rumi Numeral Symbols)) $(TR $(TD Brahmi) $(TD Imperial Aramaic) $(TD Runic)) $(TR $(TD Braille Patterns) $(TD Inscriptional Pahlavi) $(TD Samaritan)) $(TR $(TD Buginese) $(TD Inscriptional Parthian) $(TD Saurashtra)) $(TR $(TD Buhid) $(TD IPA Extensions) $(TD Sharada)) $(TR $(TD Byzantine Musical Symbols) $(TD Javanese) $(TD Shavian)) $(TR $(TD Carian) $(TD Kaithi) $(TD Sinhala)) $(TR $(TD Chakma) $(TD Kana Supplement) $(TD Small Form Variants)) $(TR $(TD Cham) $(TD Kanbun) $(TD Sora Sompeng)) $(TR $(TD Cherokee) $(TD Kangxi Radicals) $(TD Spacing Modifier Letters)) $(TR $(TD CJK Compatibility) $(TD Kannada) $(TD Specials)) $(TR $(TD CJK Compatibility Forms) $(TD Katakana) $(TD Sundanese)) $(TR $(TD CJK Compatibility Ideographs) $(TD Katakana Phonetic Extensions) $(TD Sundanese Supplement)) $(TR $(TD CJK Compatibility Ideographs Supplement) $(TD Kayah Li) $(TD Superscripts and Subscripts)) $(TR $(TD CJK Radicals Supplement) $(TD Kharoshthi) $(TD Supplemental Arrows-A)) $(TR $(TD CJK Strokes) $(TD Khmer) $(TD Supplemental Arrows-B)) $(TR $(TD CJK Symbols and Punctuation) $(TD Khmer Symbols) $(TD Supplemental Mathematical Operators)) $(TR $(TD CJK Unified Ideographs) $(TD Lao) $(TD Supplemental Punctuation)) $(TR $(TD CJK Unified Ideographs Extension A) $(TD Latin-1 Supplement) $(TD Supplementary Private Use Area-A)) $(TR $(TD CJK Unified Ideographs Extension B) $(TD Latin Extended-A) $(TD Supplementary Private Use Area-B)) $(TR $(TD CJK Unified Ideographs Extension C) $(TD Latin Extended Additional) $(TD Syloti Nagri)) $(TR $(TD CJK Unified Ideographs Extension D) $(TD Latin Extended-B) $(TD Syriac)) $(TR $(TD Combining Diacritical Marks) $(TD Latin Extended-C) $(TD Tagalog)) $(TR $(TD Combining Diacritical Marks for Symbols) $(TD Latin Extended-D) $(TD Tagbanwa)) $(TR $(TD Combining Diacritical Marks Supplement) $(TD Lepcha) $(TD Tags)) $(TR $(TD Combining Half Marks) $(TD Letterlike Symbols) $(TD Tai Le)) $(TR $(TD Common Indic Number Forms) $(TD Limbu) $(TD Tai Tham)) $(TR $(TD Control Pictures) $(TD Linear B Ideograms) $(TD Tai Viet)) $(TR $(TD Coptic) $(TD Linear B Syllabary) $(TD Tai Xuan Jing Symbols)) $(TR $(TD Counting Rod Numerals) $(TD Lisu) $(TD Takri)) $(TR $(TD Cuneiform) $(TD Low Surrogates) $(TD Tamil)) $(TR $(TD Cuneiform Numbers and Punctuation) $(TD Lycian) $(TD Telugu)) $(TR $(TD Currency Symbols) $(TD Lydian) $(TD Thaana)) $(TR $(TD Cypriot Syllabary) $(TD Mahjong Tiles) $(TD Thai)) $(TR $(TD Cyrillic) $(TD Malayalam) $(TD Tibetan)) $(TR $(TD Cyrillic Extended-A) $(TD Mandaic) $(TD Tifinagh)) $(TR $(TD Cyrillic Extended-B) $(TD Mathematical Alphanumeric Symbols) $(TD Transport And Map Symbols)) $(TR $(TD Cyrillic Supplement) $(TD Mathematical Operators) $(TD Ugaritic)) $(TR $(TD Deseret) $(TD Meetei Mayek) $(TD Unified Canadian Aboriginal Syllabics)) $(TR $(TD Devanagari) $(TD Meetei Mayek Extensions) $(TD Unified Canadian Aboriginal Syllabics Extended)) $(TR $(TD Devanagari Extended) $(TD Meroitic Cursive) $(TD Vai)) $(TR $(TD Dingbats) $(TD Meroitic Hieroglyphs) $(TD Variation Selectors)) $(TR $(TD Domino Tiles) $(TD Miao) $(TD Variation Selectors Supplement)) $(TR $(TD Egyptian Hieroglyphs) $(TD Miscellaneous Mathematical Symbols-A) $(TD Vedic Extensions)) $(TR $(TD Emoticons) $(TD Miscellaneous Mathematical Symbols-B) $(TD Vertical Forms)) $(TR $(TD Enclosed Alphanumerics) $(TD Miscellaneous Symbols) $(TD Yijing Hexagram Symbols)) $(TR $(TD Enclosed Alphanumeric Supplement) $(TD Miscellaneous Symbols and Arrows) $(TD Yi Radicals)) $(TR $(TD Enclosed CJK Letters and Months) $(TD Miscellaneous Symbols And Pictographs) $(TD Yi Syllables)) $(TR $(TD Enclosed Ideographic Supplement) $(TD Miscellaneous Technical) ) $(TR $(TD Ethiopic) $(TD Modifier Tone Letters) ) ) $(P Bellow is the table with script names accepted by $(LREF unicode.script) and by the shorthand version $(LREF unicode):) $(BOOKTABLE $(B Scripts), $(TR $(TD Arabic) $(TD Hanunoo) $(TD Old_Italic)) $(TR $(TD Armenian) $(TD Hebrew) $(TD Old_Persian)) $(TR $(TD Avestan) $(TD Hiragana) $(TD Old_South_Arabian)) $(TR $(TD Balinese) $(TD Imperial_Aramaic) $(TD Old_Turkic)) $(TR $(TD Bamum) $(TD Inherited) $(TD Oriya)) $(TR $(TD Batak) $(TD Inscriptional_Pahlavi) $(TD Osmanya)) $(TR $(TD Bengali) $(TD Inscriptional_Parthian) $(TD Phags_Pa)) $(TR $(TD Bopomofo) $(TD Javanese) $(TD Phoenician)) $(TR $(TD Brahmi) $(TD Kaithi) $(TD Rejang)) $(TR $(TD Braille) $(TD Kannada) $(TD Runic)) $(TR $(TD Buginese) $(TD Katakana) $(TD Samaritan)) $(TR $(TD Buhid) $(TD Kayah_Li) $(TD Saurashtra)) $(TR $(TD Canadian_Aboriginal) $(TD Kharoshthi) $(TD Sharada)) $(TR $(TD Carian) $(TD Khmer) $(TD Shavian)) $(TR $(TD Chakma) $(TD Lao) $(TD Sinhala)) $(TR $(TD Cham) $(TD Latin) $(TD Sora_Sompeng)) $(TR $(TD Cherokee) $(TD Lepcha) $(TD Sundanese)) $(TR $(TD Common) $(TD Limbu) $(TD Syloti_Nagri)) $(TR $(TD Coptic) $(TD Linear_B) $(TD Syriac)) $(TR $(TD Cuneiform) $(TD Lisu) $(TD Tagalog)) $(TR $(TD Cypriot) $(TD Lycian) $(TD Tagbanwa)) $(TR $(TD Cyrillic) $(TD Lydian) $(TD Tai_Le)) $(TR $(TD Deseret) $(TD Malayalam) $(TD Tai_Tham)) $(TR $(TD Devanagari) $(TD Mandaic) $(TD Tai_Viet)) $(TR $(TD Egyptian_Hieroglyphs) $(TD Meetei_Mayek) $(TD Takri)) $(TR $(TD Ethiopic) $(TD Meroitic_Cursive) $(TD Tamil)) $(TR $(TD Georgian) $(TD Meroitic_Hieroglyphs) $(TD Telugu)) $(TR $(TD Glagolitic) $(TD Miao) $(TD Thaana)) $(TR $(TD Gothic) $(TD Mongolian) $(TD Thai)) $(TR $(TD Greek) $(TD Myanmar) $(TD Tibetan)) $(TR $(TD Gujarati) $(TD New_Tai_Lue) $(TD Tifinagh)) $(TR $(TD Gurmukhi) $(TD Nko) $(TD Ugaritic)) $(TR $(TD Han) $(TD Ogham) $(TD Vai)) $(TR $(TD Hangul) $(TD Ol_Chiki) $(TD Yi)) ) $(P Bellow is the table of names accepted by $(LREF unicode.hangulSyllableType).) $(BOOKTABLE $(B Hangul syllable type), $(TR $(TH Abb.) $(TH Long form)) $(TR $(TD L) $(TD Leading_Jamo)) $(TR $(TD LV) $(TD LV_Syllable)) $(TR $(TD LVT) $(TD LVT_Syllable) ) $(TR $(TD T) $(TD Trailing_Jamo)) $(TR $(TD V) $(TD Vowel_Jamo)) ) References: $(WEB www.digitalmars.com/d/ascii-table.html, ASCII Table), $(WEB en.wikipedia.org/wiki/Unicode, Wikipedia), $(WEB www.unicode.org, The Unicode Consortium), $(WEB www.unicode.org/reports/tr15/, Unicode normalization forms), $(WEB www.unicode.org/reports/tr29/, Unicode text segmentation) $(WEB www.unicode.org/uni2book/ch05.pdf, Unicode Implementation Guidelines) $(WEB www.unicode.org/uni2book/ch03.pdf, Unicode Conformance) Trademarks: Unicode(tm) is a trademark of Unicode, Inc. Macros: WIKI=Phobos/StdUni Copyright: Copyright 2013 - License: $(WEB www.boost.org/LICENSE_1_0.txt, Boost License 1.0). Authors: Dmitry Olshansky Source: $(PHOBOSSRC std/_uni.d) Standards: $(WEB www.unicode.org/versions/Unicode6.2.0/, Unicode v6.2) Macros: SECTION = <h3><a id="$1">$0</a></h3> DEF = <div><a id="$1"><i>$0</i></a></div> S_LINK = <a href="#$1">$+</a> CODEPOINT = $(S_LINK Code point, code point) CODEPOINTS = $(S_LINK Code point, code points) CHARACTER = $(S_LINK Character, character) CHARACTERS = $(S_LINK Character, characters) CLUSTER = $(S_LINK Grapheme cluster, grapheme cluster) +/ module std.uni; static import std.ascii; import std.traits, std.range, std.algorithm, std.conv, std.typetuple, std.exception, core.stdc.stdlib; import std.array; //@@BUG UFCS doesn't work with 'local' imports import core.bitop; import std.typecons; // debug = std_uni; debug(std_uni) import std.stdio; private: version(std_uni_bootstrap){} else { import std.internal.unicode_tables; // generated file } void copyBackwards(T)(T[] src, T[] dest) { assert(src.length == dest.length); for(size_t i=src.length; i-- > 0; ) dest[i] = src[i]; } void copyForward(T)(T[] src, T[] dest) { assert(src.length == dest.length); for(size_t i=0; i<src.length; i++) dest[i] = src[i]; } // TODO: update to reflect all major CPUs supporting unaligned reads version(X86) enum hasUnalignedReads = true; else version(X86_64) enum hasUnalignedReads = true; else enum hasUnalignedReads = false; // better be safe then sorry public enum dchar lineSep = '\u2028'; /// Constant $(CODEPOINT) (0x2028) - line separator. public enum dchar paraSep = '\u2029'; /// Constant $(CODEPOINT) (0x2029) - paragraph separator. // test the intro example unittest { // initialize code point sets using script/block or property name // set contains code points from both scripts. auto set = unicode("Cyrillic") | unicode("Armenian"); // or simpler and statically-checked look auto ascii = unicode.ASCII; auto currency = unicode.Currency_Symbol; // easy set ops auto a = set & ascii; assert(a.empty); // as it has no intersection with ascii a = set | ascii; auto b = currency - a; // subtract all ASCII, Cyrillic and Armenian // some properties of code point sets assert(b.length > 45); // 46 items in Unicode 6.1, even more in 6.2 // testing presence of a code point in a set // is just fine, it is O(logN) assert(!b['$']); assert(!b['\u058F']); // Armenian dram sign assert(b['¥']); // building fast lookup tables, these guarantee O(1) complexity // 1-level Trie lookup table essentially a huge bit-set ~262Kb auto oneTrie = toTrie!1(b); // 2-level far more compact but typically slightly slower auto twoTrie = toTrie!2(b); // 3-level even smaller, and a bit slower yet auto threeTrie = toTrie!3(b); assert(oneTrie['£']); assert(twoTrie['£']); assert(threeTrie['£']); // build the trie with the most sensible trie level // and bind it as a functor auto cyrillicOrArmenian = toDelegate(set); auto balance = find!(cyrillicOrArmenian)("Hello ընկեր!"); assert(balance == "ընկեր!"); // compatible with bool delegate(dchar) bool delegate(dchar) bindIt = cyrillicOrArmenian; // Normalization string s = "Plain ascii (and not only), is always normalized!"; assert(s is normalize(s));// is the same string string nonS = "A\u0308ffin"; // A ligature auto nS = normalize(nonS); // to NFC, the W3C endorsed standard assert(nS == "Äffin"); assert(nS != nonS); string composed = "Äffin"; assert(normalize!NFD(composed) == "A\u0308ffin"); // to NFKD, compatibility decomposition useful for fuzzy matching/searching assert(normalize!NFKD("2¹⁰") == "210"); } enum lastDchar = 0x10FFFF; auto force(T, F)(F from) if(isIntegral!T && !is(T == F)) { assert(from <= T.max && from >= T.min); return cast(T)from; } auto force(T, F)(F from) if(isBitPacked!T && !is(T == F)) { assert(from <= 2^^bitSizeOf!T-1); return T(cast(TypeOfBitPacked!T)from); } auto force(T, F)(F from) if(is(T == F)) { return from; } // cheap algorithm grease ;) auto adaptIntRange(T, F)(F[] src) { //@@@BUG when in the 9 hells will map be copyable again?! static struct ConvertIntegers { private F[] data; @property T front() { return force!T(data.front); } void popFront(){ data.popFront(); } @property bool empty()const { return data.empty; } @property size_t length()const { return data.length; } auto opSlice(size_t s, size_t e) { return ConvertIntegers(data[s..e]); } @property size_t opDollar(){ return data.length; } } return ConvertIntegers(src); } // repeat X times the bit-pattern in val assuming it's length is 'bits' size_t replicateBits(size_t times, size_t bits)(size_t val) { static if(times == 1) return val; else static if(bits == 1) { static if(times == size_t.sizeof*8) return val ? size_t.max : 0; else return val ? (1<<times)-1 : 0; } else static if(times % 2) return (replicateBits!(times-1, bits)(val)<<bits) | val; else return replicateBits!(times/2, bits*2)((val<<bits) | val); } unittest // for replicate { size_t m = 0b111; size_t m2 = 0b01; foreach(i; TypeTuple!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) { assert(replicateBits!(i, 3)(m)+1 == (1<<(3*i))); assert(replicateBits!(i, 2)(m2) == iota(0, i).map!"2^^(2*a)"().reduce!"a+b"()); } } // multiple arrays squashed into one memory block struct MultiArray(Types...) { this(size_t[] sizes...) { size_t full_size; foreach(i, v; Types) { full_size += spaceFor!(bitSizeOf!v)(sizes[i]); sz[i] = sizes[i]; static if(i >= 1) offsets[i] = offsets[i-1] + spaceFor!(bitSizeOf!(Types[i-1]))(sizes[i-1]); } storage = new size_t[full_size]; } this(const(size_t)[] raw_offsets, const(size_t)[] raw_sizes, const(size_t)[] data)const { offsets[] = raw_offsets[]; sz[] = raw_sizes[]; storage = data; } @property auto slice(size_t n)()inout pure nothrow { auto ptr = raw_ptr!n; return packedArrayView!(Types[n])(ptr, sz[n]); } @property auto ptr(size_t n)()inout pure nothrow { auto ptr = raw_ptr!n; return inout(PackedPtr!(Types[n]))(ptr); } template length(size_t n) { @property size_t length()const{ return sz[n]; } @property void length(size_t new_size) { if(new_size > sz[n]) {// extend size_t delta = (new_size - sz[n]); sz[n] += delta; delta = spaceFor!(bitSizeOf!(Types[n]))(delta); storage.length += delta;// extend space at end // raw_slice!x must follow resize as it could be moved! // next stmts move all data past this array, last-one-goes-first static if(n != dim-1) { auto start = raw_ptr!(n+1); // len includes delta size_t len = (storage.ptr+storage.length-start); copyBackwards(start[0..len-delta], start[delta..len]); start[0..delta] = 0; // offsets are used for raw_slice, ptr etc. foreach(i; n+1..dim) offsets[i] += delta; } } else if(new_size < sz[n]) {// shrink size_t delta = (sz[n] - new_size); sz[n] -= delta; delta = spaceFor!(bitSizeOf!(Types[n]))(delta); // move all data past this array, forward direction static if(n != dim-1) { auto start = raw_ptr!(n+1); size_t len = (storage.ptr+storage.length-start); copyForward(start[0..len-delta], start[delta..len]); // adjust offsets last, they affect raw_slice foreach(i; n+1..dim) offsets[i] -= delta; } storage.length -= delta; } // else - NOP } } @property size_t bytes(size_t n=size_t.max)() const { static if(n == size_t.max) return storage.length*size_t.sizeof; else static if(n != Types.length-1) return (raw_ptr!(n+1)-raw_ptr!n)*size_t.sizeof; else return (storage.ptr+storage.length - raw_ptr!n)*size_t.sizeof; } void store(OutRange)(scope OutRange sink) const if(isOutputRange!(OutRange, char)) { import std.format; formattedWrite(sink, "[%( 0x%x, %)]", offsets[]); formattedWrite(sink, ", [%( 0x%x, %)]", sz[]); formattedWrite(sink, ", [%( 0x%x, %)]", storage); } private: @property auto raw_ptr(size_t n)()inout { static if(n == 0) return storage.ptr; else { return storage.ptr+offsets[n]; } } enum dim = Types.length; size_t[dim] offsets;// offset for level x size_t[dim] sz;// size of level x alias bitWidth = staticMap!(bitSizeOf, Types); size_t[] storage; } unittest { enum dg = (){ // sizes are: // lvl0: 3, lvl1 : 2, lvl2: 1 auto m = MultiArray!(int, ubyte, int)(3,2,1); static void check(size_t k, T)(ref T m, int n) { foreach(i; 0..n) assert(m.slice!(k)[i] == i+1, text("level:",i," : ",m.slice!(k)[0..n])); } static void checkB(size_t k, T)(ref T m, int n) { foreach(i; 0..n) assert(m.slice!(k)[i] == n-i, text("level:",i," : ",m.slice!(k)[0..n])); } static void fill(size_t k, T)(ref T m, int n) { foreach(i; 0..n) m.slice!(k)[i] = force!ubyte(i+1); } static void fillB(size_t k, T)(ref T m, int n) { foreach(i; 0..n) m.slice!(k)[i] = force!ubyte(n-i); } m.length!1 = 100; fill!1(m, 100); check!1(m, 100); m.length!0 = 220; fill!0(m, 220); check!1(m, 100); check!0(m, 220); m.length!2 = 17; fillB!2(m, 17); checkB!2(m, 17); check!0(m, 220); check!1(m, 100); m.length!2 = 33; checkB!2(m, 17); fillB!2(m, 33); checkB!2(m, 33); check!0(m, 220); check!1(m, 100); m.length!1 = 195; fillB!1(m, 195); checkB!1(m, 195); checkB!2(m, 33); check!0(m, 220); auto marr = MultiArray!(BitPacked!(uint, 4), BitPacked!(uint, 6))(20, 10); marr.length!0 = 15; marr.length!1 = 30; fill!1(marr, 30); fill!0(marr, 15); check!1(marr, 30); check!0(marr, 15); return 0; }; enum ct = dg(); auto rt = dg(); } unittest {// more bitpacking tests alias Bitty = MultiArray!(BitPacked!(size_t, 3) , BitPacked!(size_t, 4) , BitPacked!(size_t, 3) , BitPacked!(size_t, 6) , bool); alias fn1 = sliceBits!(13, 16); alias fn2 = sliceBits!( 9, 13); alias fn3 = sliceBits!( 6, 9); alias fn4 = sliceBits!( 0, 6); static void check(size_t lvl, MA)(ref MA arr){ for(size_t i = 0; i< arr.length!lvl; i++) assert(arr.slice!(lvl)[i] == i, text("Mismatch on lvl ", lvl, " idx ", i, " value: ", arr.slice!(lvl)[i])); } static void fillIdx(size_t lvl, MA)(ref MA arr){ for(size_t i = 0; i< arr.length!lvl; i++) arr.slice!(lvl)[i] = i; } Bitty m1; m1.length!4 = 10; m1.length!3 = 2^^6; m1.length!2 = 2^^3; m1.length!1 = 2^^4; m1.length!0 = 2^^3; m1.length!4 = 2^^16; for(size_t i = 0; i< m1.length!4; i++) m1.slice!(4)[i] = i % 2; fillIdx!1(m1); check!1(m1); fillIdx!2(m1); check!2(m1); fillIdx!3(m1); check!3(m1); fillIdx!0(m1); check!0(m1); check!3(m1); check!2(m1); check!1(m1); for(size_t i=0; i < 2^^16; i++) { m1.slice!(4)[i] = i % 2; m1.slice!(0)[fn1(i)] = fn1(i); m1.slice!(1)[fn2(i)] = fn2(i); m1.slice!(2)[fn3(i)] = fn3(i); m1.slice!(3)[fn4(i)] = fn4(i); } for(size_t i=0; i < 2^^16; i++) { assert(m1.slice!(4)[i] == i % 2); assert(m1.slice!(0)[fn1(i)] == fn1(i)); assert(m1.slice!(1)[fn2(i)] == fn2(i)); assert(m1.slice!(2)[fn3(i)] == fn3(i)); assert(m1.slice!(3)[fn4(i)] == fn4(i)); } } size_t spaceFor(size_t _bits)(size_t new_len) pure nothrow { enum bits = _bits == 1 ? 1 : ceilPowerOf2(_bits);// see PackedArrayView static if(bits > 8*size_t.sizeof) { static assert(bits % (size_t.sizeof*8) == 0); return new_len * bits/(8*size_t.sizeof); } else { enum factor = size_t.sizeof*8/bits; return (new_len+factor-1)/factor; // rounded up } } template isBitPackableType(T) { enum isBitPackableType = isBitPacked!T || isIntegral!T || is(T == bool) || isSomeChar!T; } //============================================================================ template PackedArrayView(T) if((is(T dummy == BitPacked!(U, sz), U, size_t sz) && isBitPackableType!U) || isBitPackableType!T) { private enum bits = bitSizeOf!T; alias PackedArrayView = PackedArrayViewImpl!(T, bits > 1 ? ceilPowerOf2(bits) : 1); } //unsafe and fast access to a chunk of RAM as if it contains packed values template PackedPtr(T) if((is(T dummy == BitPacked!(U, sz), U, size_t sz) && isBitPackableType!U) || isBitPackableType!T) { private enum bits = bitSizeOf!T; alias PackedPtr = PackedPtrImpl!(T, bits > 1 ? ceilPowerOf2(bits) : 1); } @trusted struct PackedPtrImpl(T, size_t bits) { pure nothrow: static assert(isPowerOf2(bits)); this(inout(size_t)* ptr)inout { origin = ptr; } private T simpleIndex(size_t n) inout { auto q = n / factor; auto r = n % factor; return cast(T)((origin[q] >> bits*r) & mask); } private void simpleWrite(TypeOfBitPacked!T val, size_t n) in { static if(isIntegral!T) assert(val <= mask); } body { auto q = n / factor; auto r = n % factor; size_t tgt_shift = bits*r; size_t word = origin[q]; origin[q] = (word & ~(mask<<tgt_shift)) | (cast(size_t)val << tgt_shift); } static if(factor == bytesPerWord// can safely pack by byte || factor == 1 // a whole word at a time || ((factor == bytesPerWord/2 || factor == bytesPerWord/4) && hasUnalignedReads)) // this needs unaligned reads { static if(factor == bytesPerWord) alias U = ubyte; else static if(factor == bytesPerWord/2) alias U = ushort; else static if(factor == bytesPerWord/4) alias U = uint; else static if(size_t.sizeof == 8 && factor == bytesPerWord/8) alias U = ulong; T opIndex(size_t idx) inout { return __ctfe ? simpleIndex(idx) : cast(inout(T))(cast(U*)origin)[idx]; } static if(isBitPacked!T) // lack of user-defined implicit conversion { void opIndexAssign(T val, size_t idx) { return opIndexAssign(cast(TypeOfBitPacked!T)val, idx); } } void opIndexAssign(TypeOfBitPacked!T val, size_t idx) { if(__ctfe) simpleWrite(val, idx); else (cast(U*)origin)[idx] = cast(U)val; } } else { T opIndex(size_t n) inout { return simpleIndex(n); } static if(isBitPacked!T) // lack of user-defined implicit conversion { void opIndexAssign(T val, size_t idx) { return opIndexAssign(cast(TypeOfBitPacked!T)val, idx); } } void opIndexAssign(TypeOfBitPacked!T val, size_t n) { return simpleWrite(val, n); } } private: // factor - number of elements in one machine word enum factor = size_t.sizeof*8/bits, mask = 2^^bits-1; enum bytesPerWord = size_t.sizeof; size_t* origin; } // data is packed only by power of two sized packs per word, // thus avoiding mul/div overhead at the cost of ultimate packing // this construct doesn't own memory, only provides access, see MultiArray for usage @trusted struct PackedArrayViewImpl(T, size_t bits) { pure nothrow: this(inout(size_t)* origin, size_t items)inout { ptr = inout(PackedPtr!(T))(origin); limit = items; } bool zeros(size_t s, size_t e) in { assert(s <= e); } body { foreach(v; this[s..e]) if(v) return false; return true; } T opIndex(size_t idx) inout in { assert(idx < limit); } body { return ptr[idx]; } static if(isBitPacked!T) // lack of user-defined implicit conversion { void opIndexAssign(T val, size_t idx) { return opIndexAssign(cast(TypeOfBitPacked!T)val, idx); } } void opIndexAssign(TypeOfBitPacked!T val, size_t idx) in { assert(idx < limit); } body { ptr[idx] = val; } static if(isBitPacked!T) // lack of user-defined implicit conversions { void opSliceAssign(T val, size_t start, size_t end) { opSliceAssign(cast(TypeOfBitPacked!T)val, start, end); } } void opSliceAssign(TypeOfBitPacked!T val, size_t start, size_t end) in { assert(start <= end); assert(end <= limit); } body { // rounded to factor granularity size_t pad_start = (start+factor-1)/factor*factor;// rounded up if(pad_start >= end) //rounded up >= then end of slice { //nothing to gain, use per element assignment foreach(i; start..end) ptr[i] = val; return; } size_t pad_end = end/factor*factor; // rounded down size_t i; for(i=start; i<pad_start; i++) ptr[i] = val; // all in between is x*factor elements if(pad_start != pad_end) { size_t repval = replicateBits!(factor, bits)(val); for(size_t j=i/factor; i<pad_end; i+=factor, j++) ptr.origin[j] = repval;// so speed it up by factor } for(; i<end; i++) ptr[i] = val; } auto opSlice(size_t from, size_t to) { return sliceOverIndexed(from, to, &this); } auto opSlice(){ return opSlice(0, length); } bool opEquals(T)(auto ref T arr) const { if(length != arr.length) return false; for(size_t i=0;i<length; i++) if(this[i] != arr[i]) return false; return true; } @property size_t length()const{ return limit; } private: // factor - number of elements in one machine word enum factor = size_t.sizeof*8/bits; PackedPtr!(T) ptr; size_t limit; } private struct SliceOverIndexed(T) { enum assignableIndex = is(typeof((){ T.init[0] = Item.init; })); enum assignableSlice = is(typeof((){ T.init[0..0] = Item.init; })); auto opIndex(size_t idx)const in { assert(idx < to - from); } body { return (*arr)[from+idx]; } static if(assignableIndex) void opIndexAssign(Item val, size_t idx) in { assert(idx < to - from); } body { (*arr)[from+idx] = val; } auto opSlice(size_t a, size_t b) { return typeof(this)(from+a, from+b, arr); } // static if(assignableSlice) void opSliceAssign(T)(T val, size_t start, size_t end) { (*arr)[start+from .. end+from] = val; } auto opSlice() { return typeof(this)(from, to, arr); } @property size_t length()const { return to-from;} auto opDollar()const { return length; } @property bool empty()const { return from == to; } @property auto front()const { return (*arr)[from]; } static if(assignableIndex) @property void front(Item val) { (*arr)[from] = val; } @property auto back()const { return (*arr)[to-1]; } static if(assignableIndex) @property void back(Item val) { (*arr)[to-1] = val; } @property auto save() inout { return this; } void popFront() { from++; } void popBack() { to--; } bool opEquals(T)(auto ref T arr) const { if(arr.length != length) return false; for(size_t i=0; i <length; i++) if(this[i] != arr[i]) return false; return true; } private: alias Item = typeof(T.init[0]); size_t from, to; T* arr; } static assert(isRandomAccessRange!(SliceOverIndexed!(int[]))); // BUG? forward reference to return type of sliceOverIndexed!Grapheme SliceOverIndexed!(const(T)) sliceOverIndexed(T)(size_t a, size_t b, const(T)* x) if(is(Unqual!T == T)) { return SliceOverIndexed!(const(T))(a, b, x); } // BUG? inout is out of reach //...SliceOverIndexed.arr only parameters or stack based variables can be inout SliceOverIndexed!T sliceOverIndexed(T)(size_t a, size_t b, T* x) if(is(Unqual!T == T)) { return SliceOverIndexed!T(a, b, x); } unittest { int[] idxArray = [2, 3, 5, 8, 13]; auto sliced = sliceOverIndexed(0, idxArray.length, &idxArray); assert(!sliced.empty); assert(sliced.front == 2); sliced.front = 1; assert(sliced.front == 1); assert(sliced.back == 13); sliced.popFront(); assert(sliced.front == 3); assert(sliced.back == 13); sliced.back = 11; assert(sliced.back == 11); sliced.popBack(); assert(sliced.front == 3); assert(sliced[$-1] == 8); sliced = sliced[]; assert(sliced[0] == 3); assert(sliced.back == 8); sliced = sliced[1..$]; assert(sliced.front == 5); sliced = sliced[0..$-1]; assert(sliced[$-1] == 5); int[] other = [2, 5]; assert(sliced[] == sliceOverIndexed(1, 2, &other)); sliceOverIndexed(0, 2, &idxArray)[0..2] = -1; assert(idxArray[0..2] == [-1, -1]); uint[] nullArr = null; auto nullSlice = sliceOverIndexed(0, 0, &idxArray); assert(nullSlice.empty); } private auto packedArrayView(T)(inout(size_t)* ptr, size_t items) @trusted pure nothrow { return inout(PackedArrayView!T)(ptr, items); } //============================================================================ // Partially unrolled binary search using Shar's method //============================================================================ private import std.math : pow; string genUnrolledSwitchSearch(size_t size) { assert(isPowerOf2(size)); string code = `auto power = bsr(m)+1; switch(power){`; size_t i = bsr(size); foreach_reverse(val; 0..bsr(size)) { auto v = 2^^val; code ~= ` case pow: if(pred(range[idx+m], needle)) idx += m; goto case; `.replace("m", to!string(v)) .replace("pow", to!string(i)); i--; } code ~= ` case 0: if(pred(range[idx], needle)) idx += 1; goto default; `; code ~= ` default: }`; return code; } bool isPowerOf2(size_t sz) @safe pure nothrow { return (sz & (sz-1)) == 0; } size_t uniformLowerBound(alias pred, Range, T)(Range range, T needle) if(is(T : ElementType!Range)) { assert(isPowerOf2(range.length)); size_t idx = 0, m = range.length/2; while(m != 0) { if(pred(range[idx+m], needle)) idx += m; m /= 2; } if(pred(range[idx], needle)) idx += 1; return idx; } size_t switchUniformLowerBound(alias pred, Range, T)(Range range, T needle) if(is(T : ElementType!Range)) { assert(isPowerOf2(range.length)); size_t idx = 0, m = range.length/2; enum max = 1<<10; while(m >= max) { if(pred(range[idx+m], needle)) idx += m; m /= 2; } mixin(genUnrolledSwitchSearch(max)); return idx; } // size_t floorPowerOf2(size_t arg) @safe pure nothrow { assert(arg > 1); // else bsr is undefined return 1<<bsr(arg-1); } size_t ceilPowerOf2(size_t arg) @safe pure nothrow { assert(arg > 1); // else bsr is undefined return 1<<bsr(arg-1)+1; } template sharMethod(alias uniLowerBound) { size_t sharMethod(alias _pred="a<b", Range, T)(Range range, T needle) if(is(T : ElementType!Range)) { import std.functional; alias pred = binaryFun!_pred; if(range.length == 0) return 0; if(isPowerOf2(range.length)) return uniLowerBound!pred(range, needle); size_t n = floorPowerOf2(range.length); if(pred(range[n-1], needle)) {// search in another 2^^k area that fully covers the tail of range size_t k = ceilPowerOf2(range.length - n + 1); return range.length - k + uniLowerBound!pred(range[$-k..$], needle); } else return uniLowerBound!pred(range[0..n], needle); } } alias sharLowerBound = sharMethod!uniformLowerBound; alias sharSwitchLowerBound = sharMethod!switchUniformLowerBound; unittest { auto stdLowerBound(T)(T[] range, T needle) { return assumeSorted(range).lowerBound(needle).length; } immutable MAX = 5*1173; auto arr = array(iota(5, MAX, 5)); assert(arr.length == MAX/5-1); foreach(i; 0..MAX+5) { auto std = stdLowerBound(arr, i); assert(std == sharLowerBound(arr, i)); assert(std == sharSwitchLowerBound(arr, i)); } arr = []; auto std = stdLowerBound(arr, 33); assert(std == sharLowerBound(arr, 33)); assert(std == sharSwitchLowerBound(arr, 33)); } //============================================================================ @safe: // hope to see simillar stuff in public interface... once Allocators are out //@@@BUG moveFront and friends? dunno, for now it's POD-only @trusted size_t genericReplace(Policy=void, T, Range) (ref T dest, size_t from, size_t to, Range stuff) { size_t delta = to - from; size_t stuff_end = from+stuff.length; if(stuff.length > delta) {// replace increases length delta = stuff.length - delta;// now, new is > old by delta static if(is(Policy == void)) dest.length = dest.length+delta;//@@@BUG lame @property else dest = Policy.realloc(dest, dest.length+delta); auto rem = copy(retro(dest[to..dest.length-delta]) , retro(dest[to+delta..dest.length])); assert(rem.empty); copy(stuff, dest[from..stuff_end]); } else if(stuff.length == delta) { copy(stuff, dest[from..to]); } else {// replace decreases length by delta delta = delta - stuff.length; copy(stuff, dest[from..stuff_end]); auto rem = copy(dest[to..dest.length] , dest[stuff_end..dest.length-delta]); static if(is(Policy == void)) dest.length = dest.length - delta;//@@@BUG lame @property else dest = Policy.realloc(dest, dest.length-delta); assert(rem.empty); } return stuff_end; } // Simple storage manipulation policy @trusted public struct GcPolicy { static T[] dup(T)(const T[] arr) { return arr.dup; } static T[] alloc(T)(size_t size) { return new T[size]; } static T[] realloc(T)(T[] arr, size_t sz) { arr.length = sz; return arr; } static void replaceImpl(T, Range)(ref T[] dest, size_t from, size_t to, Range stuff) { replaceInPlace(dest, from, to, stuff); } static void append(T, V)(ref T[] arr, V value) if(!isInputRange!V) { arr ~= force!T(value); } static void append(T, V)(ref T[] arr, V value) if(isInputRange!V) { insertInPlace(arr, arr.length, value); } static void destroy(T)(ref T arr) if(isDynamicArray!T && is(Unqual!T == T)) { version(bug10929) //@@@BUG@@@ { debug { arr[] = cast(typeof(T.init[0]))(0xdead_beef); } arr = null; } } static void destroy(T)(ref T arr) if(isDynamicArray!T && !is(Unqual!T == T)) { arr = null; } } // ditto @trusted struct ReallocPolicy { static T[] dup(T)(const T[] arr) { auto result = alloc!T(arr.length); result[] = arr[]; return result; } static T[] alloc(T)(size_t size) { auto ptr = cast(T*)enforce(malloc(T.sizeof*size), "out of memory on C heap"); return ptr[0..size]; } static T[] realloc(T)(T[] arr, size_t size) { if(!size) { destroy(arr); return null; } auto ptr = cast(T*)enforce(core.stdc.stdlib.realloc( arr.ptr, T.sizeof*size), "out of memory on C heap"); return ptr[0..size]; } static void replaceImpl(T, Range)(ref T[] dest, size_t from, size_t to, Range stuff) { genericReplace!(ReallocPolicy)(dest, from, to, stuff); } static void append(T, V)(ref T[] arr, V value) if(!isInputRange!V) { arr = realloc(arr, arr.length+1); arr[$-1] = force!T(value); } static void append(T, V)(ref T[] arr, V value) if(isInputRange!V && hasLength!V) { arr = realloc(arr, arr.length+value.length); copy(value, arr[$-value.length..$]); } static void destroy(T)(ref T[] arr) { if(arr.ptr) free(arr.ptr); arr = null; } } //build hack alias _RealArray = Uint24Array!ReallocPolicy; unittest { with(ReallocPolicy) { bool test(T, U, V)(T orig, size_t from, size_t to, U toReplace, V result, string file = __FILE__, size_t line = __LINE__) { { replaceImpl(orig, from, to, toReplace); scope(exit) destroy(orig); if(!equalS(orig, result)) return false; } return true; } static T[] arr(T)(T[] args... ) { return dup(args); } assert(test(arr([1, 2, 3, 4]), 0, 0, [5, 6, 7], [5, 6, 7, 1, 2, 3, 4])); assert(test(arr([1, 2, 3, 4]), 0, 2, cast(int[])[], [3, 4])); assert(test(arr([1, 2, 3, 4]), 0, 4, [5, 6, 7], [5, 6, 7])); assert(test(arr([1, 2, 3, 4]), 0, 2, [5, 6, 7], [5, 6, 7, 3, 4])); assert(test(arr([1, 2, 3, 4]), 2, 3, [5, 6, 7], [1, 2, 5, 6, 7, 4])); } } /** Tests if T is some kind a set of code points. Intended for template constraints. */ public template isCodepointSet(T) { static if(is(T dummy == InversionList!(Args), Args...)) enum isCodepointSet = true; else enum isCodepointSet = false; } /** Tests if $(D T) is a pair of integers that implicitly convert to $(D V). The following code must compile for any pair $(D T): --- (T x){ V a = x[0]; V b = x[1];} --- The following must not compile: --- (T x){ V c = x[2];} --- */ public template isIntegralPair(T, V=uint) { enum isIntegralPair = is(typeof((T x){ V a = x[0]; V b = x[1];})) && !is(typeof((T x){ V c = x[2]; })); } /** The recommended default type for set of $(CODEPOINTS). For details, see the current implementation: $(LREF InversionList). */ public alias CodepointSet = InversionList!GcPolicy; //@@@BUG: std.typecons tuples depend on std.format to produce fields mixin // which relies on std.uni.isGraphical and this chain blows up with Forward reference error // hence below doesn't seem to work // public alias CodepointInterval = Tuple!(uint, "a", uint, "b"); /** The recommended type of $(XREF _typecons, Tuple) to represent [a, b$(RPAREN) intervals of $(CODEPOINTS). As used in $(LREF InversionList). Any interval type should pass $(LREF isIntegralPair) trait. */ public struct CodepointInterval { uint[2] _tuple; alias _tuple this; this(uint low, uint high) { _tuple[0] = low; _tuple[1] = high; } bool opEquals(T)(T val) const { return this[0] == val[0] && this[1] == val[1]; } @property ref uint a(){ return _tuple[0]; } @property ref uint b(){ return _tuple[1]; } } //@@@BUG another forward reference workaround @trusted bool equalS(R1, R2)(R1 lhs, R2 rhs) { for(;;){ if(lhs.empty) return rhs.empty; if(rhs.empty) return false; if(lhs.front != rhs.front) return false; lhs.popFront(); rhs.popFront(); } } /** $(P $(D InversionList) is a set of $(CODEPOINTS) represented as an array of open-right [a, b$(RPAREN) intervals (see $(LREF CodepointInterval) above). The name comes from the way the representation reads left to right. For instance a set of all values [10, 50$(RPAREN), [80, 90$(RPAREN), plus a singular value 60 looks like this: ) --- 10, 50, 60, 61, 80, 90 --- $(P The way to read this is: start with negative meaning that all numbers smaller then the next one are not present in this set (and positive - the contrary). Then switch positive/negative after each number passed from left to right. ) $(P This way negative spans until 10, then positive until 50, then negative until 60, then positive until 61, and so on. As seen this provides a space-efficient storage of highly redundant data that comes in long runs. A description which Unicode $(CHARACTER) properties fit nicely. The technique itself could be seen as a variation on $(LUCKY RLE encoding). ) $(P Sets are value types (just like $(D int) is) thus they are never aliased. ) Example: --- auto a = CodepointSet('a', 'z'+1); auto b = CodepointSet('A', 'Z'+1); auto c = a; a = a | b; assert(a == CodepointSet('A', 'Z'+1, 'a', 'z'+1)); assert(a != c); --- $(P See also $(LREF unicode) for simpler construction of sets from predefined ones. ) $(P Memory usage is 6 bytes per each contiguous interval in a set. The value semantics are achieved by using the $(WEB http://en.wikipedia.org/wiki/Copy-on-write, COW) technique and thus it's $(RED not) safe to cast this type to $(D_KEYWORD shared). ) Note: $(P It's not recommended to rely on the template parameters or the exact type of a current $(CODEPOINT) set in $(D std.uni). The type and parameters may change when the standard allocators design is finalized. Use $(LREF isCodepointSet) with templates or just stick with the default alias $(LREF CodepointSet) throughout the whole code base. ) */ @trusted public struct InversionList(SP=GcPolicy) { public: /** Construct from another code point set of any type. */ this(Set)(Set set) if(isCodepointSet!Set) { uint[] arr; foreach(v; set.byInterval) { arr ~= v.a; arr ~= v.b; } data = Uint24Array!(SP)(arr); } /** Construct a set from a forward range of code point intervals. */ this(Range)(Range intervals) if(isForwardRange!Range && isIntegralPair!(ElementType!Range)) { auto flattened = roundRobin(intervals.save.map!"a[0]"(), intervals.save.map!"a[1]"()); data = Uint24Array!(SP)(flattened); sanitize(); //enforce invariant: sort intervals etc. } /** Construct a set from plain values of code point intervals. Example: --- import std.algorithm; auto set = CodepointSet('a', 'z'+1, 'а', 'я'+1); foreach(v; 'a'..'z'+1) assert(set[v]); // Cyrillic lowercase interval foreach(v; 'а'..'я'+1) assert(set[v]); //specific order is not required, intervals may interesect auto set2 = CodepointSet('а', 'я'+1, 'a', 'd', 'b', 'z'+1); //the same end result assert(set2.byInterval.equal(set.byInterval)); --- */ this()(uint[] intervals...) in { assert(intervals.length % 2 == 0, "Odd number of interval bounds [a, b)!"); for(uint i=0; i<intervals.length/2; i++) { auto a = intervals[2*i], b = intervals[2*i+1]; assert(a < b, text("illegal interval [a, b): ", a, " > ", b)); } } body { data = Uint24Array!(SP)(intervals); sanitize(); //enforce invariant: sort intervals etc. } /** Get range that spans all of the $(CODEPOINT) intervals in this $(LREF InversionList). Example: --- import std.algorithm, std.typecons; auto set = CodepointSet('A', 'D'+1, 'a', 'd'+1); set.byInterval.equal([tuple('A', 'E'), tuple('a', 'e')]); --- */ @property auto byInterval() { return Intervals!(typeof(data))(data); } /** Tests the presence of code point $(D val) in this set. Example: --- auto gothic = unicode.Gothic; // Gothic letter ahsa assert(gothic['\U00010330']); // no ascii in Gothic obviously assert(!gothic['$']); --- */ bool opIndex(uint val) const { // the <= ensures that searching in interval of [a, b) for 'a' you get .length == 1 // return assumeSorted!((a,b) => a<=b)(data[]).lowerBound(val).length & 1; return sharSwitchLowerBound!"a<=b"(data[], val) & 1; } /// Number of $(CODEPOINTS) in this set @property size_t length() { size_t sum = 0; foreach(iv; byInterval) { sum += iv.b - iv.a; } return sum; } // bootstrap full set operations from 4 primitives (suitable as a template mixin): // addInterval, skipUpTo, dropUpTo & byInterval iteration //============================================================================ public: /** $(P Sets support natural syntax for set algebra, namely: ) $(BOOKTABLE , $(TR $(TH Operator) $(TH Math notation) $(TH Description) ) $(TR $(TD &) $(TD a ∩ b) $(TD intersection) ) $(TR $(TD |) $(TD a ∪ b) $(TD union) ) $(TR $(TD -) $(TD a ∖ b) $(TD subtraction) ) $(TR $(TD ~) $(TD a ~ b) $(TD symmetric set difference i.e. (a ∪ b) \ (a ∩ b)) ) ) Example: --- auto lower = unicode.LowerCase; auto upper = unicode.UpperCase; auto ascii = unicode.ASCII; assert((lower & upper).empty); // no intersection auto lowerASCII = lower & ascii; assert(lowerASCII.byCodepoint.equal(iota('a', 'z'+1))); // throw away all of the lowercase ASCII assert((ascii - lower).length == 128 - 26); auto onlyOneOf = lower ~ ascii; assert(!onlyOneOf['Δ']); // not ASCII and not lowercase assert(onlyOneOf['$']); // ASCII and not lowercase assert(!onlyOneOf['a']); // ASCII and lowercase assert(onlyOneOf['я']); // not ASCII but lowercase // throw away all cased letters from ASCII auto noLetters = ascii - (lower | upper); assert(noLetters.length == 128 - 26*2); --- */ This opBinary(string op, U)(U rhs) if(isCodepointSet!U || is(U:dchar)) { static if(op == "&" || op == "|" || op == "~") {// symmetric ops thus can swap arguments to reuse r-value static if(is(U:dchar)) { auto tmp = this; mixin("tmp "~op~"= rhs; "); return tmp; } else { static if(is(Unqual!U == U)) { // try hard to reuse r-value mixin("rhs "~op~"= this;"); return rhs; } else { auto tmp = this; mixin("tmp "~op~"= rhs;"); return tmp; } } } else static if(op == "-") // anti-symmetric { auto tmp = this; tmp -= rhs; return tmp; } else static assert(0, "no operator "~op~" defined for Set"); } /// The 'op=' versions of the above overloaded operators. ref This opOpAssign(string op, U)(U rhs) if(isCodepointSet!U || is(U:dchar)) { static if(op == "|") // union { static if(is(U:dchar)) { this.addInterval(rhs, rhs+1); return this; } else return this.add(rhs); } else static if(op == "&") // intersection return this.intersect(rhs);// overloaded else static if(op == "-") // set difference return this.sub(rhs);// overloaded else static if(op == "~") // symmetric set difference { auto copy = this & rhs; this |= rhs; this -= copy; return this; } else static assert(0, "no operator "~op~" defined for Set"); } /** Tests the presence of codepoint $(D ch) in this set, the same as $(LREF opIndex). */ bool opBinaryRight(string op: "in", U)(U ch) const if(is(U : dchar)) { return this[ch]; } /// unittest { assert('я' in unicode.Cyrillic); assert(!('z' in unicode.Cyrillic)); } /// Obtains a set that is the inversion of this set. See also $(LREF inverted). auto opUnary(string op: "!")() { return this.inverted; } /** A range that spans each $(CODEPOINT) in this set. Example: --- import std.algorithm; auto set = unicode.ASCII; set.byCodepoint.equal(iota(0, 0x80)); --- */ @property auto byCodepoint() { @trusted static struct CodepointRange { this(This set) { r = set.byInterval; if(!r.empty) cur = r.front.a; } @property dchar front() const { return cast(dchar)cur; } @property bool empty() const { return r.empty; } void popFront() { cur++; while(cur >= r.front.b) { r.popFront(); if(r.empty) break; cur = r.front.a; } } private: uint cur; typeof(This.init.byInterval) r; } return CodepointRange(this); } /** $(P Obtain textual representation of this set in from of open-right intervals and feed it to $(D sink). ) $(P Used by various standard formatting facilities such as $(XREF _format, formattedWrite), $(XREF _stdio, write), $(XREF _stdio, writef), $(XREF _conv, to) and others. ) Example: --- import std.conv; assert(unicode.ASCII.to!string == "[0..128$(RPAREN)"); --- */ void toString(scope void delegate (const(char)[]) sink) { import std.format; auto range = byInterval; if(range.empty) return; auto val = range.front; formattedWrite(sink, "[%d..%d)", val.a, val.b); range.popFront(); foreach(i; range) formattedWrite(sink, " [%d..%d)", i.a, i.b); } /** Add an interval [a, b$(RPAREN) to this set. Example: --- CodepointSet someSet; someSet.add('0', '5').add('A','Z'+1); someSet.add('5', '9'+1); assert(someSet['0']); assert(someSet['5']); assert(someSet['9']); assert(someSet['Z']); --- */ ref add()(uint a, uint b) { addInterval(a, b); return this; } private: ref intersect(U)(U rhs) if(isCodepointSet!U) { Marker mark; foreach( i; rhs.byInterval) { mark = this.dropUpTo(i.a, mark); mark = this.skipUpTo(i.b, mark); } this.dropUpTo(uint.max, mark); return this; } ref intersect()(dchar ch) { foreach(i; byInterval) if(i.a <= ch && ch < i.b) return this = This.init.add(ch, ch+1); this = This.init; return this; } /// unittest { assert(unicode.Cyrillic.intersect('-').byInterval.empty); } ref sub()(dchar ch) { return subChar(ch); } // same as the above except that skip & drop parts are swapped ref sub(U)(U rhs) if(isCodepointSet!U) { uint top; Marker mark; foreach(i; rhs.byInterval) { mark = this.skipUpTo(i.a, mark); mark = this.dropUpTo(i.b, mark); } return this; } ref add(U)(U rhs) if(isCodepointSet!U) { Marker start; foreach(i; rhs.byInterval) { start = addInterval(i.a, i.b, start); } return this; } // end of mixin-able part //============================================================================ public: /** Obtains a set that is the inversion of this set. See the '!' $(LREF opUnary) for the same but using operators. Example: --- set = unicode.ASCII; // union with the inverse gets all of the code points in the Unicode assert((set | set.inverted).length == 0x110000); // no intersection with the inverse assert((set & set.inverted).empty); --- */ @property auto inverted() { InversionList inversion = this; if(inversion.data.length == 0) { inversion.addInterval(0, lastDchar+1); return inversion; } if(inversion.data[0] != 0) genericReplace(inversion.data, 0, 0, [0]); else genericReplace(inversion.data, 0, 1, cast(uint[])null); if(data[data.length-1] != lastDchar+1) genericReplace(inversion.data, inversion.data.length, inversion.data.length, [lastDchar+1]); else genericReplace(inversion.data, inversion.data.length-1, inversion.data.length, cast(uint[])null); return inversion; } /** Generates string with D source code of unary function with name of $(D funcName) taking a single $(D dchar) argument. If $(D funcName) is empty the code is adjusted to be a lambda function. The function generated tests if the $(CODEPOINT) passed belongs to this set or not. The result is to be used with string mixin. The intended usage area is aggressive optimization via meta programming in parser generators and the like. Note: Use with care for relatively small or regular sets. It could end up being slower then just using multi-staged tables. Example: --- import std.stdio; // construct set directly from [a, b) intervals auto set = CodepointSet(10, 12, 45, 65, 100, 200); writeln(set); writeln(set.toSourceCode("func")); --- The above outputs something along the lines of: --- bool func(dchar ch) { if(ch < 45) { if(ch == 10 || ch == 11) return true; return false; } else if (ch < 65) return true; else { if(ch < 100) return false; if(ch < 200) return true; return false; } } --- */ string toSourceCode(string funcName="") { import std.string; enum maxBinary = 3; static string linearScope(R)(R ivals, string indent) { string result = indent~"{\n"; string deeper = indent~" "; foreach(ival; ivals) { auto span = ival[1] - ival[0]; assert(span != 0); if(span == 1) { result ~= format("%sif(ch == %s) return true;\n", deeper, ival[0]); } else if(span == 2) { result ~= format("%sif(ch == %s || ch == %s) return true;\n", deeper, ival[0], ival[0]+1); } else { if(ival[0] != 0) // dchar is unsigned and < 0 is useless result ~= format("%sif(ch < %s) return false;\n", deeper, ival[0]); result ~= format("%sif(ch < %s) return true;\n", deeper, ival[1]); } } result ~= format("%sreturn false;\n%s}\n", deeper, indent); // including empty range of intervals return result; } static string binaryScope(R)(R ivals, string indent) { // time to do unrolled comparisons? if(ivals.length < maxBinary) return linearScope(ivals, indent); else return bisect(ivals, ivals.length/2, indent); } // not used yet if/elsebinary search is far better with DMD as of 2.061 // and GDC is doing fine job either way static string switchScope(R)(R ivals, string indent) { string result = indent~"switch(ch){\n"; string deeper = indent~" "; foreach(ival; ivals) { if(ival[0]+1 == ival[1]) { result ~= format("%scase %s: return true;\n", deeper, ival[0]); } else { result ~= format("%scase %s: .. case %s: return true;\n", deeper, ival[0], ival[1]-1); } } result ~= deeper~"default: return false;\n"~indent~"}\n"; return result; } static string bisect(R)(R range, size_t idx, string indent) { string deeper = indent ~ " "; // bisect on one [a, b) interval at idx string result = indent~"{\n"; // less branch, < a result ~= format("%sif(ch < %s)\n%s", deeper, range[idx][0], binaryScope(range[0..idx], deeper)); // middle point, >= a && < b result ~= format("%selse if (ch < %s) return true;\n", deeper, range[idx][1]); // greater or equal branch, >= b result ~= format("%selse\n%s", deeper, binaryScope(range[idx+1..$], deeper)); return result~indent~"}\n"; } string code = format("bool %s(dchar ch) @safe pure nothrow\n", funcName.empty ? "function" : funcName); auto range = byInterval.array(); // special case first bisection to be on ASCII vs beyond auto tillAscii = countUntil!"a[0] > 0x80"(range); if(tillAscii <= 0) // everything is ASCII or nothing is ascii (-1 & 0) code ~= binaryScope(range, ""); else code ~= bisect(range, tillAscii, ""); return code; } /** True if this set doesn't contain any $(CODEPOINTS). Example: --- CodepointSet emptySet; assert(emptySet.length == 0); assert(emptySet.empty); --- */ @property bool empty() const { return data.length == 0; } private: alias This = typeof(this); alias Marker = size_t; // a random-access range of integral pairs static struct Intervals(Range) { this(Range sp) { slice = sp; start = 0; end = sp.length; } this(Range sp, size_t s, size_t e) { slice = sp; start = s; end = e; } @property auto front()const { uint a = slice[start]; uint b = slice[start+1]; return CodepointInterval(a, b); } //may break sorted property - but we need std.sort to access it //hence package protection attribute package @property auto front(CodepointInterval val) { slice[start] = val.a; slice[start+1] = val.b; } @property auto back()const { uint a = slice[end-2]; uint b = slice[end-1]; return CodepointInterval(a, b); } //ditto about package package @property auto back(CodepointInterval val) { slice[end-2] = val.a; slice[end-1] = val.b; } void popFront() { start += 2; } void popBack() { end -= 2; } auto opIndex(size_t idx) const { uint a = slice[start+idx*2]; uint b = slice[start+idx*2+1]; return CodepointInterval(a, b); } //ditto about package package auto opIndexAssign(CodepointInterval val, size_t idx) { slice[start+idx*2] = val.a; slice[start+idx*2+1] = val.b; } auto opSlice(size_t s, size_t e) { return Intervals(slice, s*2+start, e*2+start); } @property size_t length()const { return slice.length/2; } @property bool empty()const { return start == end; } @property auto save(){ return this; } private: size_t start, end; Range slice; } // called after construction from intervals // to make sure invariants hold void sanitize() { if (data.length == 0) return; alias Ival = CodepointInterval; //intervals wrapper for a _range_ over packed array auto ivals = Intervals!(typeof(data[]))(data[]); sort!("a.a < b.a", SwapStrategy.stable)(ivals); // what follows is a variation on stable remove // differences: // - predicate is binary, and is tested against // the last kept element (at 'i'). // - predicate mutates lhs (merges rhs into lhs) size_t len = ivals.length; size_t i = 0; size_t j = 1; while (j < len) { if (ivals[i].b >= ivals[j].a) { ivals[i] = Ival(ivals[i].a, max(ivals[i].b, ivals[j].b)); j++; } else //unmergable { // check if there is a hole after merges // (in the best case we do 0 writes to ivals) if (j != i+1) ivals[i+1] = ivals[j]; //copy over i++; j++; } } len = i + 1; for (size_t k=0; k + 1 < len; k++) { assert(ivals[k].a < ivals[k].b); assert(ivals[k].b < ivals[k+1].a); } data.length = len * 2; } // special case for normal InversionList ref subChar(dchar ch) { auto mark = skipUpTo(ch); if(mark != data.length && data[mark] == ch && data[mark-1] == ch) { // it has split, meaning that ch happens to be in one of intervals data[mark] = data[mark]+1; } return this; } // Marker addInterval(int a, int b, Marker hint=Marker.init) in { assert(a <= b, text(a, " > ", b)); } body { auto range = assumeSorted(data[]); size_t pos; size_t a_idx = range.lowerBound(a).length; if(a_idx == range.length) { // [---+++----++++----++++++] // [ a b] data.append([a, b]); return data.length-1; } size_t b_idx = range[a_idx..range.length].lowerBound(b).length+a_idx; uint[] to_insert; debug(std_uni) { writefln("a_idx=%d; b_idx=%d;", a_idx, b_idx); } if(b_idx == range.length) { // [-------++++++++----++++++-] // [ s a b] if(a_idx & 1)// a in positive { to_insert = [ b ]; } else// a in negative { to_insert = [a, b]; } genericReplace(data, a_idx, b_idx, to_insert); return a_idx+to_insert.length-1; } uint top = data[b_idx]; debug(std_uni) { writefln("a_idx=%d; b_idx=%d;", a_idx, b_idx); writefln("a=%s; b=%s; top=%s;", a, b, top); } if(a_idx & 1) {// a in positive if(b_idx & 1)// b in positive { // [-------++++++++----++++++-] // [ s a b ] to_insert = [top]; } else // b in negative { // [-------++++++++----++++++-] // [ s a b ] if(top == b) { assert(b_idx+1 < data.length); pos = genericReplace(data, a_idx, b_idx+2, [data[b_idx+1]]); return pos; } to_insert = [b, top ]; } } else { // a in negative if(b_idx & 1) // b in positive { // [----------+++++----++++++-] // [ a b ] to_insert = [a, top]; } else// b in negative { // [----------+++++----++++++-] // [ a s b ] if(top == b) { assert(b_idx+1 < data.length); pos = genericReplace(data, a_idx, b_idx+2, [a, data[b_idx+1] ]); return pos; } to_insert = [a, b, top]; } } pos = genericReplace(data, a_idx, b_idx+1, to_insert); debug(std_uni) { writefln("marker idx: %d; length=%d", pos, data[pos], data.length); writeln("inserting ", to_insert); } return pos; } // Marker dropUpTo(uint a, Marker pos=Marker.init) in { assert(pos % 2 == 0); // at start of interval } body { auto range = assumeSorted!"a<=b"(data[pos..data.length]); if(range.empty) return pos; size_t idx = pos; idx += range.lowerBound(a).length; debug(std_uni) { writeln("dropUpTo full length=", data.length); writeln(pos,"~~~", idx); } if(idx == data.length) return genericReplace(data, pos, idx, cast(uint[])[]); if(idx & 1) { // a in positive //[--+++----++++++----+++++++------...] // |<---si s a t genericReplace(data, pos, idx, [a]); } else { // a in negative //[--+++----++++++----+++++++-------+++...] // |<---si s a t genericReplace(data, pos, idx, cast(uint[])[]); } return pos; } // Marker skipUpTo(uint a, Marker pos=Marker.init) out(result) { assert(result % 2 == 0);// always start of interval //(may be 0-width after-split) } body { assert(data.length % 2 == 0); auto range = assumeSorted!"a<=b"(data[pos..data.length]); size_t idx = pos+range.lowerBound(a).length; if(idx >= data.length) // could have Marker point to recently removed stuff return data.length; if(idx & 1)// inside of interval, check for split { uint top = data[idx]; if(top == a)// no need to split, it's end return idx+1; uint start = data[idx-1]; if(a == start) return idx-1; // split it up genericReplace(data, idx, idx+1, [a, a, top]); return idx+1; // avoid odd index } return idx; } Uint24Array!SP data; }; @system unittest { // test examples import std.algorithm, std.typecons; auto set = CodepointSet('A', 'D'+1, 'a', 'd'+1); set.byInterval.equalS([tuple('A', 'E'), tuple('a', 'e')]); set = unicode.ASCII; assert(set.byCodepoint.equalS(iota(0, 0x80))); set = CodepointSet('a', 'z'+1, 'а', 'я'+1); foreach(v; 'a'..'z'+1) assert(set[v]); // Cyrillic lowercase interval foreach(v; 'а'..'я'+1) assert(set[v]); //specific order is not required, intervals may interesect auto set2 = CodepointSet('а', 'я'+1, 'a', 'd', 'b', 'z'+1); assert(set2.byInterval.equal(set.byInterval)); auto gothic = unicode.Gothic; // Gothic letter ahsa assert(gothic['\U00010330']); // no ascii in Gothic obviously assert(!gothic['$']); CodepointSet emptySet; assert(emptySet.length == 0); assert(emptySet.empty); set = unicode.ASCII; // union with the inverse gets all of code points in the Unicode assert((set | set.inverted).length == 0x110000); // no intersection with inverse assert((set & set.inverted).empty); CodepointSet someSet; someSet.add('0', '5').add('A','Z'+1); someSet.add('5', '9'+1); assert(someSet['0']); assert(someSet['5']); assert(someSet['9']); assert(someSet['Z']); auto lower = unicode.LowerCase; auto upper = unicode.UpperCase; auto ascii = unicode.ASCII; assert((lower & upper).empty); // no intersection auto lowerASCII = lower & ascii; assert(lowerASCII.byCodepoint.equalS(iota('a', 'z'+1))); // throw away all of the lowercase ASCII assert((ascii - lower).length == 128 - 26); auto onlyOneOf = lower ~ ascii; assert(!onlyOneOf['Δ']); // not ASCII and not lowercase assert(onlyOneOf['$']); // ASCII and not lowercase assert(!onlyOneOf['a']); // ASCII and lowercase assert(onlyOneOf['я']); // not ASCII but lowercase auto noLetters = ascii - (lower | upper); assert(noLetters.length == 128 - 26*2); import std.conv; assert(unicode.ASCII.to!string() == "[0..128)"); } // pedantic version for ctfe, and aligned-access only architectures @trusted uint safeRead24(const ubyte* ptr, size_t idx) pure nothrow { idx *= 3; version(LittleEndian) return ptr[idx] + (cast(uint)ptr[idx+1]<<8) + (cast(uint)ptr[idx+2]<<16); else return (cast(uint)ptr[idx]<<16) + (cast(uint)ptr[idx+1]<<8) + ptr[idx+2]; } // ditto @trusted void safeWrite24(ubyte* ptr, uint val, size_t idx) pure nothrow { idx *= 3; version(LittleEndian) { ptr[idx] = val & 0xFF; ptr[idx+1] = (val>>8) & 0xFF; ptr[idx+2] = (val>>16) & 0xFF; } else { ptr[idx] = (val>>16) & 0xFF; ptr[idx+1] = (val>>8) & 0xFF; ptr[idx+2] = val & 0xFF; } } // unaligned x86-like read/write functions @trusted uint unalignedRead24(const ubyte* ptr, size_t idx) pure nothrow { uint* src = cast(uint*)(ptr+3*idx); version(LittleEndian) return *src & 0xFF_FFFF; else return *src >> 8; } // ditto @trusted void unalignedWrite24(ubyte* ptr, uint val, size_t idx) pure nothrow { uint* dest = cast(uint*)(cast(ubyte*)ptr + 3*idx); version(LittleEndian) *dest = val | (*dest & 0xFF00_0000); else *dest = (val<<8) | (*dest & 0xFF); } uint read24(const ubyte* ptr, size_t idx) pure nothrow { static if(hasUnalignedReads) return __ctfe ? safeRead24(ptr, idx) : unalignedRead24(ptr, idx); else return safeRead24(ptr, idx); } void write24(ubyte* ptr, uint val, size_t idx) pure nothrow { static if(hasUnalignedReads) return __ctfe ? safeWrite24(ptr, val, idx) : unalignedWrite24(ptr, val, idx); else return safeWrite24(ptr, val, idx); } // Packed array of 24-bit integers, COW semantics. @trusted struct Uint24Array(SP=GcPolicy) { this(Range)(Range range) if(isInputRange!Range && hasLength!Range) { length = range.length; copy(range, this[]); } this(Range)(Range range) if(isForwardRange!Range && !hasLength!Range) { auto len = walkLength(range.save); length = len; copy(range, this[]); } this(this) { if(!empty) { refCount = refCount + 1; } } ~this() { if(!empty) { auto cnt = refCount; if(cnt == 1) SP.destroy(data); else refCount = cnt - 1; } } // no ref-count for empty U24 array @property bool empty() const { return data.length == 0; } // report one less then actual size @property size_t length() const { return data.length ? (data.length-4)/3 : 0; } //+ an extra slot for ref-count @property void length(size_t len) { if(len == 0) { if(!empty) freeThisReference(); return; } immutable bytes = len*3+4; // including ref-count if(empty) { data = SP.alloc!ubyte(bytes); refCount = 1; return; } auto cur_cnt = refCount; if(cur_cnt != 1) // have more references to this memory { refCount = cur_cnt - 1; auto new_data = SP.alloc!ubyte(bytes); // take shrinking into account auto to_copy = min(bytes, data.length)-4; copy(data[0..to_copy], new_data[0..to_copy]); data = new_data; // before setting refCount! refCount = 1; } else // 'this' is the only reference { // use the realloc (hopefully in-place operation) data = SP.realloc(data, bytes); refCount = 1; // setup a ref-count in the new end of the array } } alias opDollar = length; // Read 24-bit packed integer uint opIndex(size_t idx)const { return read24(data.ptr, idx); } // Write 24-bit packed integer void opIndexAssign(uint val, size_t idx) in { assert(!empty && val <= 0xFF_FFFF); } body { auto cnt = refCount; if(cnt != 1) dupThisReference(cnt); write24(data.ptr, val, idx); } // auto opSlice(size_t from, size_t to) { return sliceOverIndexed(from, to, &this); } /// auto opSlice(size_t from, size_t to) const { return sliceOverIndexed(from, to, &this); } // length slices before the ref count auto opSlice() { return opSlice(0, length); } // length slices before the ref count auto opSlice() const { return opSlice(0, length); } void append(Range)(Range range) if(isInputRange!Range && hasLength!Range && is(ElementType!Range : uint)) { size_t nl = length + range.length; length = nl; copy(range, this[nl-range.length..nl]); } void append()(uint val) { length = length + 1; this[$-1] = val; } bool opEquals()(auto const ref Uint24Array rhs)const { if(empty ^ rhs.empty) return false; // one is empty and the other isn't return empty || data[0..$-4] == rhs.data[0..$-4]; } private: // ref-count is right after the data @property uint refCount() const { return read24(data.ptr, length); } @property void refCount(uint cnt) in { assert(cnt <= 0xFF_FFFF); } body { write24(data.ptr, cnt, length); } void freeThisReference() { auto count = refCount; if(count != 1) // have more references to this memory { // dec shared ref-count refCount = count - 1; data = []; } else SP.destroy(data); version(bug10929) assert(!data.ptr); else data = null; } void dupThisReference(uint count) in { assert(!empty && count != 1 && count == refCount); } body { // dec shared ref-count refCount = count - 1; // copy to the new chunk of RAM auto new_data = SP.alloc!ubyte(data.length); // bit-blit old stuff except the counter copy(data[0..$-4], new_data[0..$-4]); data = new_data; // before setting refCount! refCount = 1; // so that this updates the right one } ubyte[] data; } @trusted unittest// Uint24 tests //@@@BUG@@ iota is system ?! { void funcRef(T)(ref T u24) { u24.length = 2; u24[1] = 1024; T u24_c = u24; assert(u24[1] == 1024); u24.length = 0; assert(u24.empty); u24.append([1, 2]); assert(equalS(u24[], [1, 2])); u24.append(111); assert(equalS(u24[], [1, 2, 111])); assert(!u24_c.empty && u24_c[1] == 1024); u24.length = 3; copy(iota(0, 3), u24[]); assert(equalS(u24[], iota(0, 3))); assert(u24_c[1] == 1024); } void func2(T)(T u24) { T u24_2 = u24; T u24_3; u24_3 = u24_2; assert(u24_2 == u24_3); assert(equalS(u24[], u24_2[])); assert(equalS(u24_2[], u24_3[])); funcRef(u24_3); assert(equalS(u24_3[], iota(0, 3))); assert(!equalS(u24_2[], u24_3[])); assert(equalS(u24_2[], u24[])); u24_2 = u24_3; assert(equalS(u24_2[], iota(0, 3))); // to test that passed arg is intact outside // plus try out opEquals u24 = u24_3; u24 = T.init; u24_3 = T.init; assert(u24.empty); assert(u24 == u24_3); assert(u24 != u24_2); } foreach(Policy; TypeTuple!(GcPolicy, ReallocPolicy)) { alias Range = typeof(Uint24Array!Policy.init[]); alias U24A = Uint24Array!Policy; static assert(isForwardRange!Range); static assert(isBidirectionalRange!Range); static assert(isOutputRange!(Range, uint)); static assert(isRandomAccessRange!(Range)); auto arr = U24A([42u, 36, 100]); assert(arr[0] == 42); assert(arr[1] == 36); arr[0] = 72; arr[1] = 0xFE_FEFE; assert(arr[0] == 72); assert(arr[1] == 0xFE_FEFE); assert(arr[2] == 100); U24A arr2 = arr; assert(arr2[0] == 72); arr2[0] = 11; // test COW-ness assert(arr[0] == 72); assert(arr2[0] == 11); // set this to about 100M to stress-test COW memory management foreach(v; 0..10_000) func2(arr); assert(equalS(arr[], [72, 0xFE_FEFE, 100])); auto r2 = U24A(iota(0, 100)); assert(equalS(r2[], iota(0, 100)), text(r2[])); copy(iota(10, 170, 2), r2[10..90]); assert(equalS(r2[], chain(iota(0, 10), iota(10, 170, 2), iota(90, 100))) , text(r2[])); } } version(unittest) { private alias AllSets = TypeTuple!(InversionList!GcPolicy, InversionList!ReallocPolicy); } @trusted unittest// core set primitives test { foreach(CodeList; AllSets) { CodeList a; //"plug a hole" test a.add(10, 20).add(25, 30).add(15, 27); assert(a == CodeList(10, 30), text(a)); auto x = CodeList.init; x.add(10, 20).add(30, 40).add(50, 60); a = x; a.add(20, 49);//[10, 49) [50, 60) assert(a == CodeList(10, 49, 50 ,60)); a = x; a.add(20, 50); assert(a == CodeList(10, 60), text(a)); // simple unions, mostly edge effects x = CodeList.init; x.add(10, 20).add(40, 60); a = x; a.add(10, 25); //[10, 25) [40, 60) assert(a == CodeList(10, 25, 40, 60)); a = x; a.add(5, 15); //[5, 20) [40, 60) assert(a == CodeList(5, 20, 40, 60)); a = x; a.add(0, 10); // [0, 20) [40, 60) assert(a == CodeList(0, 20, 40, 60)); a = x; a.add(0, 5); // prepand assert(a == CodeList(0, 5, 10, 20, 40, 60), text(a)); a = x; a.add(5, 20); assert(a == CodeList(5, 20, 40, 60)); a = x; a.add(3, 37); assert(a == CodeList(3, 37, 40, 60)); a = x; a.add(37, 65); assert(a == CodeList(10, 20, 37, 65)); // some tests on helpers for set intersection x = CodeList.init.add(10, 20).add(40, 60).add(100, 120); a = x; auto m = a.skipUpTo(60); a.dropUpTo(110, m); assert(a == CodeList(10, 20, 40, 60, 110, 120), text(a.data[])); a = x; a.dropUpTo(100); assert(a == CodeList(100, 120), text(a.data[])); a = x; m = a.skipUpTo(50); a.dropUpTo(140, m); assert(a == CodeList(10, 20, 40, 50), text(a.data[])); a = x; a.dropUpTo(60); assert(a == CodeList(100, 120), text(a.data[])); } } //test constructor to work with any order of intervals @system unittest //@@@BUG@@@ iota is @system { import std.conv, std.range, std.algorithm; //ensure constructor handles bad ordering and overlap auto c1 = CodepointSet('а', 'я'+1, 'А','Я'+1); foreach(ch; chain(iota('а', 'я'+1), iota('А','Я'+1))) assert(ch in c1, to!string(ch)); //contiguos assert(CodepointSet(1000, 1006, 1006, 1009) .byInterval.equal([tuple(1000, 1009)])); //contains assert(CodepointSet(900, 1200, 1000, 1100) .byInterval.equal([tuple(900, 1200)])); //intersect left assert(CodepointSet(900, 1100, 1000, 1200) .byInterval.equal([tuple(900, 1200)])); //intersect right assert(CodepointSet(1000, 1200, 900, 1100) .byInterval.equal([tuple(900, 1200)])); //ditto with extra items at end assert(CodepointSet(1000, 1200, 900, 1100, 800, 850) .byInterval.equal([tuple(800, 850), tuple(900, 1200)])); assert(CodepointSet(900, 1100, 1000, 1200, 800, 850) .byInterval.equal([tuple(800, 850), tuple(900, 1200)])); //"plug a hole" test auto c2 = CodepointSet(20, 40, 60, 80, 100, 140, 150, 200, 40, 60, 80, 100, 140, 150 ); assert(c2.byInterval.equal([tuple(20, 200)])); auto c3 = CodepointSet( 20, 40, 60, 80, 100, 140, 150, 200, 0, 10, 15, 100, 10, 20, 200, 220); assert(c3.byInterval.equal([tuple(0, 140), tuple(150, 220)])); } @trusted unittest { // full set operations foreach(CodeList; AllSets) { CodeList a, b, c, d; //"plug a hole" a.add(20, 40).add(60, 80).add(100, 140).add(150, 200); b.add(40, 60).add(80, 100).add(140, 150); c = a | b; d = b | a; assert(c == CodeList(20, 200), text(CodeList.stringof," ", c)); assert(c == d, text(c," vs ", d)); b = CodeList.init.add(25, 45).add(65, 85).add(95,110).add(150, 210); c = a | b; //[20,45) [60, 85) [95, 140) [150, 210) d = b | a; assert(c == CodeList(20, 45, 60, 85, 95, 140, 150, 210), text(c)); assert(c == d, text(c," vs ", d)); b = CodeList.init.add(10, 20).add(30,100).add(145,200); c = a | b;//[10, 140) [145, 200) d = b | a; assert(c == CodeList(10, 140, 145, 200)); assert(c == d, text(c," vs ", d)); b = CodeList.init.add(0, 10).add(15, 100).add(10, 20).add(200, 220); c = a | b;//[0, 140) [150, 220) d = b | a; assert(c == CodeList(0, 140, 150, 220)); assert(c == d, text(c," vs ", d)); a = CodeList.init.add(20, 40).add(60, 80); b = CodeList.init.add(25, 35).add(65, 75); c = a & b; d = b & a; assert(c == CodeList(25, 35, 65, 75), text(c)); assert(c == d, text(c," vs ", d)); a = CodeList.init.add(20, 40).add(60, 80).add(100, 140).add(150, 200); b = CodeList.init.add(25, 35).add(65, 75).add(110, 130).add(160, 180); c = a & b; d = b & a; assert(c == CodeList(25, 35, 65, 75, 110, 130, 160, 180), text(c)); assert(c == d, text(c," vs ", d)); a = CodeList.init.add(20, 40).add(60, 80).add(100, 140).add(150, 200); b = CodeList.init.add(10, 30).add(60, 120).add(135, 160); c = a & b;//[20, 30)[60, 80) [100, 120) [135, 140) [150, 160) d = b & a; assert(c == CodeList(20, 30, 60, 80, 100, 120, 135, 140, 150, 160),text(c)); assert(c == d, text(c, " vs ",d)); assert((c & a) == c); assert((d & b) == d); assert((c & d) == d); b = CodeList.init.add(40, 60).add(80, 100).add(140, 200); c = a & b; d = b & a; assert(c == CodeList(150, 200), text(c)); assert(c == d, text(c, " vs ",d)); assert((c & a) == c); assert((d & b) == d); assert((c & d) == d); assert((a & a) == a); assert((b & b) == b); a = CodeList.init.add(20, 40).add(60, 80).add(100, 140).add(150, 200); b = CodeList.init.add(30, 60).add(75, 120).add(190, 300); c = a - b;// [30, 40) [60, 75) [120, 140) [150, 190) d = b - a;// [40, 60) [80, 100) [200, 300) assert(c == CodeList(20, 30, 60, 75, 120, 140, 150, 190), text(c)); assert(d == CodeList(40, 60, 80, 100, 200, 300), text(d)); assert(c - d == c, text(c-d, " vs ", c)); assert(d - c == d, text(d-c, " vs ", d)); assert(c - c == CodeList.init); assert(d - d == CodeList.init); a = CodeList.init.add(20, 40).add( 60, 80).add(100, 140).add(150, 200); b = CodeList.init.add(10, 50).add(60, 160).add(190, 300); c = a - b;// [160, 190) d = b - a;// [10, 20) [40, 50) [80, 100) [140, 150) [200, 300) assert(c == CodeList(160, 190), text(c)); assert(d == CodeList(10, 20, 40, 50, 80, 100, 140, 150, 200, 300), text(d)); assert(c - d == c, text(c-d, " vs ", c)); assert(d - c == d, text(d-c, " vs ", d)); assert(c - c == CodeList.init); assert(d - d == CodeList.init); a = CodeList.init.add(20, 40).add(60, 80).add(100, 140).add(150, 200); b = CodeList.init.add(10, 30).add(45, 100).add(130, 190); c = a ~ b; // [10, 20) [30, 40) [45, 60) [80, 130) [140, 150) [190, 200) d = b ~ a; assert(c == CodeList(10, 20, 30, 40, 45, 60, 80, 130, 140, 150, 190, 200), text(c)); assert(c == d, text(c, " vs ", d)); } } @system: unittest// vs single dchar { CodepointSet a = CodepointSet(10, 100, 120, 200); assert(a - 'A' == CodepointSet(10, 65, 66, 100, 120, 200), text(a - 'A')); assert((a & 'B') == CodepointSet(66, 67)); } unittest// iteration & opIndex { import std.typecons; foreach(CodeList; TypeTuple!(InversionList!(ReallocPolicy))) { auto arr = "ABCDEFGHIJKLMabcdefghijklm"d; auto a = CodeList('A','N','a', 'n'); assert(equalS(a.byInterval, [tuple(cast(uint)'A', cast(uint)'N'), tuple(cast(uint)'a', cast(uint)'n')] ), text(a.byInterval)); // same @@@BUG as in issue 8949 ? version(bug8949) { assert(equalS(retro(a.byInterval), [tuple(cast(uint)'a', cast(uint)'n'), tuple(cast(uint)'A', cast(uint)'N')] ), text(retro(a.byInterval))); } auto achr = a.byCodepoint; assert(equalS(achr, arr), text(a.byCodepoint)); foreach(ch; a.byCodepoint) assert(a[ch]); auto x = CodeList(100, 500, 600, 900, 1200, 1500); assert(equalS(x.byInterval, [ tuple(100, 500), tuple(600, 900), tuple(1200, 1500)]), text(x.byInterval)); foreach(ch; x.byCodepoint) assert(x[ch]); static if(is(CodeList == CodepointSet)) { auto y = CodeList(x.byInterval); assert(equalS(x.byInterval, y.byInterval)); } assert(equalS(CodepointSet.init.byInterval, cast(Tuple!(uint, uint)[])[])); assert(equalS(CodepointSet.init.byCodepoint, cast(dchar[])[])); } } //============================================================================ // Generic Trie template and various ways to build it //============================================================================ // debug helper to get a shortened array dump auto arrayRepr(T)(T x) { if(x.length > 32) { return text(x[0..16],"~...~", x[x.length-16..x.length]); } else return text(x); } /** Maps $(D Key) to a suitable integer index within the range of $(D size_t). The mapping is constructed by applying predicates from $(D Prefix) left to right and concatenating the resulting bits. The first (leftmost) predicate defines the most significant bits of the resulting index. */ template mapTrieIndex(Prefix...) { size_t mapTrieIndex(Key)(Key key) if(isValidPrefixForTrie!(Key, Prefix)) { alias p = Prefix; size_t idx; foreach(i, v; p[0..$-1]) { idx |= p[i](key); idx <<= p[i+1].bitSize; } idx |= p[$-1](key); return idx; } } /* $(D TrieBuilder) is a type used for incremental construction of $(LREF Trie)s. See $(LREF buildTrie) for generic helpers built on top of it. */ @trusted struct TrieBuilder(Value, Key, Args...) if(isBitPackableType!Value && isValidArgsForTrie!(Key, Args)) { private: // last index is not stored in table, it is used as an offset to values in a block. static if(is(Value == bool))// always pack bool alias V = BitPacked!(Value, 1); else alias V = Value; static auto deduceMaxIndex(Preds...)() { size_t idx = 1; foreach(v; Preds) idx *= 2^^v.bitSize; return idx; } static if(is(typeof(Args[0]) : Key)) // Args start with upper bound on Key { alias Prefix = Args[1..$]; enum lastPageSize = 2^^Prefix[$-1].bitSize; enum translatedMaxIndex = mapTrieIndex!(Prefix)(Args[0]); enum roughedMaxIndex = (translatedMaxIndex + lastPageSize-1)/lastPageSize*lastPageSize; // check warp around - if wrapped, use the default deduction rule enum maxIndex = roughedMaxIndex < translatedMaxIndex ? deduceMaxIndex!(Prefix)() : roughedMaxIndex; } else { alias Prefix = Args; enum maxIndex = deduceMaxIndex!(Prefix)(); } alias getIndex = mapTrieIndex!(Prefix); enum lastLevel = Prefix.length-1; struct ConstructState { size_t idx_zeros, idx_ones; } // iteration over levels of Trie, each indexes its own level and thus a shortened domain size_t[Prefix.length] indices; // default filler value to use Value defValue; // this is a full-width index of next item size_t curIndex; // all-zeros page index, all-ones page index (+ indicator if there is such a page) ConstructState[Prefix.length] state; // the table being constructed MultiArray!(idxTypes!(Key, fullBitSize!(Prefix), Prefix[0..$]), V) table; @disable this(); //shortcut for index variable at level 'level' @property ref idx(size_t level)(){ return indices[level]; } // this function assumes no holes in the input so // indices are going one by one void addValue(size_t level, T)(T val, size_t numVals) { alias j = idx!level; enum pageSize = 1<<Prefix[level].bitSize; if(numVals == 0) return; auto ptr = table.slice!(level); if(numVals == 1) { static if(level == Prefix.length-1) ptr[j] = val; else {// can incur narrowing conversion assert(j < ptr.length); ptr[j] = force!(typeof(ptr[j]))(val); } j++; if(j % pageSize == 0) spillToNextPage!level(ptr); return; } // longer row of values // get to the next page boundary size_t nextPB = (j + pageSize) & ~(pageSize-1); size_t n = nextPB - j;// can fill right in this page if(numVals < n) //fits in current page { ptr[j..j+numVals] = val; j += numVals; return; } static if(level != 0)//on the first level it always fits { numVals -= n; //write till the end of current page ptr[j..j+n] = val; j += n; //spill to the next page spillToNextPage!level(ptr); // page at once loop if(state[level].idx_zeros != size_t.max && val == T.init) { alias NextIdx = typeof(table.slice!(level-1)[0]); addValue!(level-1)(force!NextIdx(state[level].idx_zeros), numVals/pageSize); ptr = table.slice!level; //table structure might have changed numVals %= pageSize; } else { while(numVals >= pageSize) { numVals -= pageSize; ptr[j..j+pageSize] = val; j += pageSize; spillToNextPage!level(ptr); } } if(numVals) { // the leftovers, an incomplete page ptr[j..j+numVals] = val; j += numVals; } } } void spillToNextPage(size_t level, Slice)(ref Slice ptr) { // last level (i.e. topmost) has 1 "page" // thus it need not to add a new page on upper level static if(level != 0) spillToNextPageImpl!(level)(ptr); } // this can re-use the current page if duplicate or allocate a new one // it also makes sure that previous levels point to the correct page in this level void spillToNextPageImpl(size_t level, Slice)(ref Slice ptr) { alias NextIdx = typeof(table.slice!(level-1)[0]); NextIdx next_lvl_index; enum pageSize = 1<<Prefix[level].bitSize; assert(idx!level % pageSize == 0); auto last = idx!level-pageSize; auto slice = ptr[idx!level - pageSize..idx!level]; size_t j; for(j=0; j<last; j+=pageSize) { if(equalS(ptr[j..j+pageSize], slice[0..pageSize])) { // get index to it, reuse ptr space for the next block next_lvl_index = force!NextIdx(j/pageSize); version(none) { writefln("LEVEL(%s) page maped idx: %s: 0..%s ---> [%s..%s]" ,level ,indices[level-1], pageSize, j, j+pageSize); writeln("LEVEL(", level , ") mapped page is: ", slice, ": ", arrayRepr(ptr[j..j+pageSize])); writeln("LEVEL(", level , ") src page is :", ptr, ": ", arrayRepr(slice[0..pageSize])); } idx!level -= pageSize; // reuse this page, it is duplicate break; } } if(j == last) { L_allocate_page: next_lvl_index = force!NextIdx(idx!level/pageSize - 1); if(state[level].idx_zeros == size_t.max && ptr.zeros(j, j+pageSize)) { state[level].idx_zeros = next_lvl_index; } // allocate next page version(none) { writefln("LEVEL(%s) page allocated: %s" , level, arrayRepr(slice[0..pageSize])); writefln("LEVEL(%s) index: %s ; page at this index %s" , level , next_lvl_index , arrayRepr( table.slice!(level) [pageSize*next_lvl_index..(next_lvl_index+1)*pageSize] )); } table.length!level = table.length!level + pageSize; } L_know_index: // for the previous level, values are indices to the pages in the current level addValue!(level-1)(next_lvl_index, 1); ptr = table.slice!level; //re-load the slice after moves } // idx - full-width index to fill with v (full-width index != key) // fills everything in the range of [curIndex, idx) with filler void putAt(size_t idx, Value v) { assert(idx >= curIndex); size_t numFillers = idx - curIndex; addValue!lastLevel(defValue, numFillers); addValue!lastLevel(v, 1); curIndex = idx + 1; } // ditto, but sets the range of [idxA, idxB) to v void putRangeAt(size_t idxA, size_t idxB, Value v) { assert(idxA >= curIndex); assert(idxB >= idxA); size_t numFillers = idxA - curIndex; addValue!lastLevel(defValue, numFillers); addValue!lastLevel(v, idxB - idxA); curIndex = idxB; // open-right } enum errMsg = "non-monotonic prefix function(s), an unsorted range or "~ "duplicate key->value mapping"; public: /** Construct a builder, where $(D filler) is a value to indicate empty slots (or "not found" condition). */ this(Value filler) { curIndex = 0; defValue = filler; // zeros-page index, ones-page index foreach(ref v; state) v = ConstructState(size_t.max, size_t.max); table = typeof(table)(indices); // one page per level is a bootstrap minimum foreach(i; Sequence!(0, Prefix.length)) table.length!i = (1<<Prefix[i].bitSize); } /** Put a value $(D v) into interval as mapped by keys from $(D a) to $(D b). All slots prior to $(D a) are filled with the default filler. */ void putRange(Key a, Key b, Value v) { auto idxA = getIndex(a), idxB = getIndex(b); // indexes of key should always grow enforce(idxB >= idxA && idxA >= curIndex, errMsg); putRangeAt(idxA, idxB, v); } /** Put a value $(D v) into slot mapped by $(D key). All slots prior to $(D key) are filled with the default filler. */ void putValue(Key key, Value v) { auto idx = getIndex(key); enforce(idx >= curIndex, text(errMsg, " ", idx)); putAt(idx, v); } /// Finishes construction of Trie, yielding an immutable Trie instance. auto build() { static if(maxIndex != 0) // doesn't cover full range of size_t { assert(curIndex <= maxIndex); addValue!lastLevel(defValue, maxIndex - curIndex); } else { if(curIndex != 0 // couldn't wrap around || (Prefix.length != 1 && indices[lastLevel] == 0)) // can be just empty { addValue!lastLevel(defValue, size_t.max - curIndex); addValue!lastLevel(defValue, 1); } // else curIndex already completed the full range of size_t by wrapping around } return Trie!(V, Key, maxIndex, Prefix)(table); } } /* $(P A generic Trie data-structure for a fixed number of stages. The design goal is optimal speed with smallest footprint size. ) $(P It's intentionally read-only and doesn't provide constructors. To construct one use a special builder, see $(LREF TrieBuilder) and $(LREF buildTrie). ) */ @trusted public struct Trie(Value, Key, Args...) if(isValidPrefixForTrie!(Key, Args) || (isValidPrefixForTrie!(Key, Args[1..$]) && is(typeof(Args[0]) : size_t))) { static if(is(typeof(Args[0]) : size_t)) { enum maxIndex = Args[0]; enum hasBoundsCheck = true; alias Prefix = Args[1..$]; } else { enum hasBoundsCheck = false; alias Prefix = Args; } private this()(typeof(_table) table) { _table = table; } // only for constant Tries constructed from precompiled tables private this()(const(size_t)[] offsets, const(size_t)[] sizes, const(size_t)[] data) const { _table = typeof(_table)(offsets, sizes, data); } /* $(P Lookup the $(D key) in this $(D Trie). ) $(P The lookup always succeeds if key fits the domain provided during construction. The whole domain defined is covered so instead of not found condition the sentinel (filler) value could be used. ) $(P See $(LREF buildTrie), $(LREF TrieBuilder) for how to define a domain of $(D Trie) keys and the sentinel value. ) Note: Domain range-checking is only enabled in debug builds and results in assertion failure. */ // templated to auto-detect pure, @safe and nothrow TypeOfBitPacked!Value opIndex()(Key key) const { static if(hasBoundsCheck) assert(mapTrieIndex!Prefix(key) < maxIndex); size_t idx; alias p = Prefix; idx = cast(size_t)p[0](key); foreach(i, v; p[0..$-1]) idx = cast(size_t)((_table.ptr!i[idx]<<p[i+1].bitSize) + p[i+1](key)); return _table.ptr!(p.length-1)[idx]; } @property size_t bytes(size_t n=size_t.max)() const { return _table.bytes!n; } @property size_t pages(size_t n)() const { return (bytes!n+2^^(Prefix[n].bitSize-1)) /2^^Prefix[n].bitSize; } void store(OutRange)(scope OutRange sink) const if(isOutputRange!(OutRange, char)) { _table.store(sink); } private: MultiArray!(idxTypes!(Key, fullBitSize!(Prefix), Prefix[0..$]), Value) _table; } // create a tuple of 'sliceBits' that slice the 'top' of bits into pieces of sizes 'sizes' // left-to-right, the most significant bits first template GetBitSlicing(size_t top, sizes...) { static if(sizes.length > 0) alias GetBitSlicing = TypeTuple!(sliceBits!(top - sizes[0], top), GetBitSlicing!(top - sizes[0], sizes[1..$])); else alias GetBitSlicing = TypeTuple!(); } template callableWith(T) { template callableWith(alias Pred) { static if(!is(typeof(Pred(T.init)))) enum callableWith = false; else { alias Result = typeof(Pred(T.init)); enum callableWith = isBitPackableType!(TypeOfBitPacked!(Result)); } } } /* Check if $(D Prefix) is a valid set of predicates for $(D Trie) template having $(D Key) as the type of keys. This requires all predicates to be callable, take single argument of type $(D Key) and return unsigned value. */ template isValidPrefixForTrie(Key, Prefix...) { enum isValidPrefixForTrie = allSatisfy!(callableWith!Key, Prefix); // TODO: tighten the screws } /* Check if $(D Args) is a set of maximum key value followed by valid predicates for $(D Trie) template having $(D Key) as the type of keys. */ template isValidArgsForTrie(Key, Args...) { static if(Args.length > 1) { enum isValidArgsForTrie = isValidPrefixForTrie!(Key, Args) || (isValidPrefixForTrie!(Key, Args[1..$]) && is(typeof(Args[0]) : Key)); } else enum isValidArgsForTrie = isValidPrefixForTrie!Args; } @property size_t sumOfIntegerTuple(ints...)() { size_t count=0; foreach(v; ints) count += v; return count; } /** A shorthand for creating a custom multi-level fixed Trie from a $(D CodepointSet). $(D sizes) are numbers of bits per level, with the most significant bits used first. Note: The sum of $(D sizes) must be equal 21. See_Also: $(LREF toTrie), which is even simpler. Example: --- { import std.stdio; auto set = unicode("Number"); auto trie = codepointSetTrie!(8, 5, 8)(set); writeln("Input code points to test:"); foreach(line; stdin.byLine) { int count=0; foreach(dchar ch; line) if(trie[ch])// is number count++; writefln("Contains %d number code points.", count); } } --- */ public template codepointSetTrie(sizes...) if(sumOfIntegerTuple!sizes == 21) { auto codepointSetTrie(Set)(Set set) if(isCodepointSet!Set) { auto builder = TrieBuilder!(bool, dchar, lastDchar+1, GetBitSlicing!(21, sizes))(false); foreach(ival; set.byInterval) builder.putRange(ival[0], ival[1], true); return builder.build(); } } /// Type of Trie generated by codepointSetTrie function. public template CodepointSetTrie(sizes...) if(sumOfIntegerTuple!sizes == 21) { alias Prefix = GetBitSlicing!(21, sizes); alias CodepointSetTrie = typeof(TrieBuilder!(bool, dchar, lastDchar+1, Prefix)(false).build()); } /** A slightly more general tool for building fixed $(D Trie) for the Unicode data. Specifically unlike $(D codepointSetTrie) it's allows creating mappings of $(D dchar) to an arbitrary type $(D T). Note: Overload taking $(D CodepointSet)s will naturally convert only to bool mapping $(D Trie)s. Example: --- // pick characters from the Greek script auto set = unicode.Greek; // a user-defined property (or an expensive function) // that we want to look up static uint luckFactor(dchar ch) { // here we consider a character lucky // if its code point has a lot of identical hex-digits // e.g. arabic letter DDAL (\u0688) has a "luck factor" of 2 ubyte[6] nibbles; // 6 4-bit chunks of code point uint value = ch; foreach(i; 0..6) { nibbles[i] = value & 0xF; value >>= 4; } uint luck; foreach(n; nibbles) luck = cast(uint)max(luck, count(nibbles[], n)); return luck; } // only unsigned built-ins are supported at the moment alias LuckFactor = BitPacked!(uint, 3); // create a temporary associative array (AA) LuckFactor[dchar] map; foreach(ch; set.byCodepoint) map[ch] = luckFactor(ch); // bits per stage are chosen randomly, fell free to optimize auto trie = codepointTrie!(LuckFactor, 8, 5, 8)(map); // from now on the AA is not needed foreach(ch; set.byCodepoint) assert(trie[ch] == luckFactor(ch)); // verify // CJK is not Greek, thus it has the default value assert(trie['\u4444'] == 0); // and here is a couple of quite lucky Greek characters: // Greek small letter epsilon with dasia assert(trie['\u1F11'] == 3); // Ancient Greek metretes sign assert(trie['\U00010181'] == 3); --- */ public template codepointTrie(T, sizes...) if(sumOfIntegerTuple!sizes == 21) { alias Prefix = GetBitSlicing!(21, sizes); static if(is(TypeOfBitPacked!T == bool)) { auto codepointTrie(Set)(in Set set) if(isCodepointSet!Set) { return codepointSetTrie(set); } } auto codepointTrie()(T[dchar] map, T defValue=T.init) { return buildTrie!(T, dchar, Prefix)(map, defValue); } // unsorted range of pairs auto codepointTrie(R)(R range, T defValue=T.init) if(isInputRange!R && is(typeof(ElementType!R.init[0]) : T) && is(typeof(ElementType!R.init[1]) : dchar)) { // build from unsorted array of pairs // TODO: expose index sorting functions for Trie return buildTrie!(T, dchar, Prefix)(range, defValue, true); } } unittest // codepointTrie example { // pick characters from the Greek script auto set = unicode.Greek; // a user-defined property (or an expensive function) // that we want to look up static uint luckFactor(dchar ch) { // here we consider a character lucky // if its code point has a lot of identical hex-digits // e.g. arabic letter DDAL (\u0688) has a "luck factor" of 2 ubyte[6] nibbles; // 6 4-bit chunks of code point uint value = ch; foreach(i; 0..6) { nibbles[i] = value & 0xF; value >>= 4; } uint luck; foreach(n; nibbles) luck = cast(uint)max(luck, count(nibbles[], n)); return luck; } // only unsigned built-ins are supported at the moment alias LuckFactor = BitPacked!(uint, 3); // create a temporary associative array (AA) LuckFactor[dchar] map; foreach(ch; set.byCodepoint) map[ch] = LuckFactor(luckFactor(ch)); // bits per stage are chosen randomly, fell free to optimize auto trie = codepointTrie!(LuckFactor, 8, 5, 8)(map); // from now on the AA is not needed foreach(ch; set.byCodepoint) assert(trie[ch] == luckFactor(ch)); // verify // CJK is not Greek, thus it has the default value assert(trie['\u4444'] == 0); // and here is a couple of quite lucky Greek characters: // Greek small letter epsilon with dasia assert(trie['\u1F11'] == 3); // Ancient Greek metretes sign assert(trie['\U00010181'] == 3); } /// Type of Trie as generated by codepointTrie function. public template CodepointTrie(T, sizes...) if(sumOfIntegerTuple!sizes == 21) { alias Prefix = GetBitSlicing!(21, sizes); alias CodepointTrie = typeof(TrieBuilder!(T, dchar, lastDchar+1, Prefix)(T.init).build()); } // @@@BUG multiSort can's access private symbols from uni public template cmpK0(alias Pred) { import std.typecons; static bool cmpK0(Value, Key) (Tuple!(Value, Key) a, Tuple!(Value, Key) b) { return Pred(a[1]) < Pred(b[1]); } } /* The most general utility for construction of $(D Trie)s short of using $(D TrieBuilder) directly. Provides a number of convenience overloads. $(D Args) is tuple of maximum key value followed by predicates to construct index from key. Alternatively if the first argument is not a value convertible to $(D Key) then the whole tuple of $(D Args) is treated as predicates and the maximum Key is deduced from predicates. */ public template buildTrie(Value, Key, Args...) if(isValidArgsForTrie!(Key, Args)) { static if(is(typeof(Args[0]) : Key)) // prefix starts with upper bound on Key { alias Prefix = Args[1..$]; } else alias Prefix = Args; alias getIndex = mapTrieIndex!(Prefix); // for multi-sort template GetComparators(size_t n) { static if(n > 0) alias GetComparators = TypeTuple!(GetComparators!(n-1), cmpK0!(Prefix[n-1])); else alias GetComparators = TypeTuple!(); } /* Build $(D Trie) from a range of a Key-Value pairs, assuming it is sorted by Key as defined by the following lambda: ------ (a, b) => mapTrieIndex!(Prefix)(a) < mapTrieIndex!(Prefix)(b) ------ Exception is thrown if it's detected that the above order doesn't hold. In other words $(LREF mapTrieIndex) should be a monotonically increasing function that maps $(D Key) to an integer. See also: $(XREF _algorithm, sort), $(XREF _range, SortedRange), $(XREF _algorithm, setUnion). */ auto buildTrie(Range)(Range range, Value filler=Value.init) if(isInputRange!Range && is(typeof(Range.init.front[0]) : Value) && is(typeof(Range.init.front[1]) : Key)) { auto builder = TrieBuilder!(Value, Key, Prefix)(filler); foreach(v; range) builder.putValue(v[1], v[0]); return builder.build(); } /* If $(D Value) is bool (or BitPacked!(bool, x)) then it's possible to build $(D Trie) from a range of open-right intervals of $(D Key)s. The requirement on the ordering of keys (and the behavior on the violation of it) is the same as for Key-Value range overload. Intervals denote ranges of !$(D filler) i.e. the opposite of filler. If no filler provided keys inside of the intervals map to true, and $(D filler) is false. */ auto buildTrie(Range)(Range range, Value filler=Value.init) if(is(TypeOfBitPacked!Value == bool) && isInputRange!Range && is(typeof(Range.init.front[0]) : Key) && is(typeof(Range.init.front[1]) : Key)) { auto builder = TrieBuilder!(Value, Key, Prefix)(filler); foreach(ival; range) builder.putRange(ival[0], ival[1], !filler); return builder.build(); } auto buildTrie(Range)(Range range, Value filler, bool unsorted) if(isInputRange!Range && is(typeof(Range.init.front[0]) : Value) && is(typeof(Range.init.front[1]) : Key)) { alias Comps = GetComparators!(Prefix.length); if(unsorted) multiSort!(Comps)(range); return buildTrie(range, filler); } /* If $(D Value) is bool (or BitPacked!(bool, x)) then it's possible to build $(D Trie) simply from an input range of $(D Key)s. The requirement on the ordering of keys (and the behavior on the violation of it) is the same as for Key-Value range overload. Keys found in range denote !$(D filler) i.e. the opposite of filler. If no filler provided keys map to true, and $(D filler) is false. */ auto buildTrie(Range)(Range range, Value filler=Value.init) if(is(TypeOfBitPacked!Value == bool) && isInputRange!Range && is(typeof(Range.init.front) : Key)) { auto builder = TrieBuilder!(Value, Key, Prefix)(filler); foreach(v; range) builder.putValue(v, !filler); return builder.build(); } /* If $(D Key) is unsigned integer $(D Trie) could be constructed from array of values where array index serves as key. */ auto buildTrie()(Value[] array, Value filler=Value.init) if(isUnsigned!Key) { auto builder = TrieBuilder!(Value, Key, Prefix)(filler); foreach(idx, v; array) builder.putValue(idx, v); return builder.build(); } /* Builds $(D Trie) from associative array. */ auto buildTrie(Key, Value)(Value[Key] map, Value filler=Value.init) { auto range = array(zip(map.values, map.keys)); return buildTrie(range, filler, true); // sort it } } /++ Convenience function to construct optimal configurations for packed Trie from any $(D set) of $(CODEPOINTS). The parameter $(D level) indicates the number of trie levels to use, allowed values are: 1, 2, 3 or 4. Levels represent different trade-offs speed-size wise. $(P Level 1 is fastest and the most memory hungry (a bit array). ) $(P Level 4 is the slowest and has the smallest footprint. ) See the $(S_LINK Synopsis, Synopsis) section for example. Note: Level 4 stays very practical (being faster and more predictable) compared to using direct lookup on the $(D set) itself. +/ public auto toTrie(size_t level, Set)(Set set) if(isCodepointSet!Set) { static if(level == 1) return codepointSetTrie!(21)(set); else static if(level == 2) return codepointSetTrie!(10, 11)(set); else static if(level == 3) return codepointSetTrie!(8, 5, 8)(set); else static if(level == 4) return codepointSetTrie!(6, 4, 4, 7)(set); else static assert(false, "Sorry, toTrie doesn't support levels > 4, use codepointSetTrie directly"); } /** $(P Builds a $(D Trie) with typically optimal speed-size trade-off and wraps it into a delegate of the following type: $(D bool delegate(dchar ch)). ) $(P Effectively this creates a 'tester' lambda suitable for algorithms like std.algorithm.find that take unary predicates. ) See the $(S_LINK Synopsis, Synopsis) section for example. */ public auto toDelegate(Set)(Set set) if(isCodepointSet!Set) { // 3 is very small and is almost as fast as 2-level (due to CPU caches?) auto t = toTrie!3(set); return (dchar ch) => t[ch]; } /** $(P Opaque wrapper around unsigned built-in integers and code unit (char/wchar/dchar) types. Parameter $(D sz) indicates that the value is confined to the range of [0, 2^^sz$(RPAREN). With this knowledge it can be packed more tightly when stored in certain data-structures like trie. ) Note: $(P The $(D BitPacked!(T, sz)) is implicitly convertible to $(D T) but not vise-versa. Users have to ensure the value fits in the range required and use the $(D cast) operator to perform the conversion.) */ struct BitPacked(T, size_t sz) if(isIntegral!T || is(T:dchar)) { enum bitSize = sz; T _value; alias _value this; } /* Depending on the form of the passed argument $(D bitSizeOf) returns the amount of bits required to represent a given type or a return type of a given functor. */ template bitSizeOf(Args...) if(Args.length == 1) { alias T = Args[0]; static if(__traits(compiles, { size_t val = T.bitSize; })) //(is(typeof(T.bitSize) : size_t)) { enum bitSizeOf = T.bitSize; } else static if(is(ReturnType!T dummy == BitPacked!(U, bits), U, size_t bits)) { enum bitSizeOf = bitSizeOf!(ReturnType!T); } else { enum bitSizeOf = T.sizeof*8; } } /** Tests if $(D T) is some instantiation of $(LREF BitPacked)!(U, x) and thus suitable for packing. */ template isBitPacked(T) { static if(is(T dummy == BitPacked!(U, bits), U, size_t bits)) enum isBitPacked = true; else enum isBitPacked = false; } /** Gives the type $(D U) from $(LREF BitPacked)!(U, x) or $(D T) itself for every other type. */ template TypeOfBitPacked(T) { static if(is(T dummy == BitPacked!(U, bits), U, size_t bits)) alias TypeOfBitPacked = U; else alias TypeOfBitPacked = T; } /* Wrapper, used in definition of custom data structures from $(D Trie) template. Applying it to a unary lambda function indicates that the returned value always fits within $(D bits) of bits. */ struct assumeSize(alias Fn, size_t bits) { enum bitSize = bits; static auto ref opCall(T)(auto ref T arg) { return Fn(arg); } } /* A helper for defining lambda function that yields a slice of certain bits from an unsigned integral value. The resulting lambda is wrapped in assumeSize and can be used directly with $(D Trie) template. */ struct sliceBits(size_t from, size_t to) { //for now bypass assumeSize, DMD has trouble inlining it enum bitSize = to-from; static auto opCall(T)(T x) out(result) { assert(result < (1<<to-from)); } body { static assert(from < to); return (x >> from) & ((1<<(to-from))-1); } } uint low_8(uint x) { return x&0xFF; } @safe pure nothrow uint midlow_8(uint x){ return (x&0xFF00)>>8; } alias lo8 = assumeSize!(low_8, 8); alias mlo8 = assumeSize!(midlow_8, 8); static assert(bitSizeOf!lo8 == 8); static assert(bitSizeOf!(sliceBits!(4, 7)) == 3); static assert(bitSizeOf!(BitPacked!(uint, 2)) == 2); template Sequence(size_t start, size_t end) { static if(start < end) alias Sequence = TypeTuple!(start, Sequence!(start+1, end)); else alias Sequence = TypeTuple!(); } //---- TRIE TESTS ---- unittest { static trieStats(TRIE)(TRIE t) { version(std_uni_stats) { import std.stdio; writeln("---TRIE FOOTPRINT STATS---"); foreach(i; Sequence!(0, t.table.dim) ) { writefln("lvl%s = %s bytes; %s pages" , i, t.bytes!i, t.pages!i); } writefln("TOTAL: %s bytes", t.bytes); version(none) { writeln("INDEX (excluding value level):"); foreach(i; Sequence!(0, t.table.dim-1) ) writeln(t.table.slice!(i)[0..t.table.length!i]); } writeln("---------------------------"); } } //@@@BUG link failure, lambdas not found by linker somehow (in case of trie2) // alias lo8 = assumeSize!(8, function (uint x) { return x&0xFF; }); // alias next8 = assumeSize!(7, function (uint x) { return (x&0x7F00)>>8; }); alias CodepointSet Set; auto set = Set('A','Z','a','z'); auto trie = buildTrie!(bool, uint, 256, lo8)(set.byInterval);// simple bool array for(int a='a'; a<'z';a++) assert(trie[a]); for(int a='A'; a<'Z';a++) assert(trie[a]); for(int a=0; a<'A'; a++) assert(!trie[a]); for(int a ='Z'; a<'a'; a++) assert(!trie[a]); trieStats(trie); auto redundant2 = Set( 1, 18, 256+2, 256+111, 512+1, 512+18, 768+2, 768+111); auto trie2 = buildTrie!(bool, uint, 1024, mlo8, lo8)(redundant2.byInterval); trieStats(trie2); foreach(e; redundant2.byCodepoint) assert(trie2[e], text(cast(uint)e, " - ", trie2[e])); foreach(i; 0..1024) { assert(trie2[i] == (i in redundant2)); } auto redundant3 = Set( 2, 4, 6, 8, 16, 2+16, 4+16, 16+6, 16+8, 16+16, 2+32, 4+32, 32+6, 32+8, ); enum max3 = 256; // sliceBits auto trie3 = buildTrie!(bool, uint, max3, sliceBits!(6,8), sliceBits!(4,6), sliceBits!(0,4) )(redundant3.byInterval); trieStats(trie3); foreach(i; 0..max3) assert(trie3[i] == (i in redundant3), text(cast(uint)i)); auto redundant4 = Set( 10, 64, 64+10, 128, 128+10, 256, 256+10, 512, 1000, 2000, 3000, 4000, 5000, 6000 ); enum max4 = 2^^16; auto trie4 = buildTrie!(bool, size_t, max4, sliceBits!(13, 16), sliceBits!(9, 13), sliceBits!(6, 9) , sliceBits!(0, 6) )(redundant4.byInterval); foreach(i; 0..max4){ if(i in redundant4) assert(trie4[i], text(cast(uint)i)); } trieStats(trie4); alias mapToS = mapTrieIndex!(useItemAt!(0, char)); string[] redundantS = ["tea", "start", "orange"]; redundantS.sort!((a,b) => mapToS(a) < mapToS(b))(); auto strie = buildTrie!(bool, string, useItemAt!(0, char))(redundantS); // using first char only assert(redundantS == ["orange", "start", "tea"]); assert(strie["test"], text(strie["test"])); assert(!strie["aea"]); assert(strie["s"]); // a bit size test auto a = array(map!(x => to!ubyte(x))(iota(0, 256))); auto bt = buildTrie!(bool, ubyte, sliceBits!(7, 8), sliceBits!(5, 7), sliceBits!(0, 5))(a); trieStats(bt); foreach(i; 0..256) assert(bt[cast(ubyte)i]); } template useItemAt(size_t idx, T) if(isIntegral!T || is(T: dchar)) { size_t impl(in T[] arr){ return arr[idx]; } alias useItemAt = assumeSize!(impl, 8*T.sizeof); } template useLastItem(T) { size_t impl(in T[] arr){ return arr[$-1]; } alias useLastItem = assumeSize!(impl, 8*T.sizeof); } template fullBitSize(Prefix...) { static if(Prefix.length > 0) enum fullBitSize = bitSizeOf!(Prefix[0])+fullBitSize!(Prefix[1..$]); else enum fullBitSize = 0; } template idxTypes(Key, size_t fullBits, Prefix...) { static if(Prefix.length == 1) {// the last level is value level, so no index once reduced to 1-level alias idxTypes = TypeTuple!(); } else { // Important note on bit packing // Each level has to hold enough of bits to address the next one // The bottom level is known to hold full bit width // thus it's size in pages is full_bit_width - size_of_last_prefix // Recourse on this notion alias idxTypes = TypeTuple!( idxTypes!(Key, fullBits - bitSizeOf!(Prefix[$-1]), Prefix[0..$-1]), BitPacked!(typeof(Prefix[$-2](Key.init)), fullBits - bitSizeOf!(Prefix[$-1])) ); } } //============================================================================ @trusted int comparePropertyName(Char1, Char2)(const(Char1)[] a, const(Char2)[] b) { alias low = std.ascii.toLower; return cmp( a.map!(x => low(x))() .filter!(x => !isWhite(x) && x != '-' && x != '_')(), b.map!(x => low(x))() .filter!(x => !isWhite(x) && x != '-' && x != '_')() ); } bool propertyNameLess(Char1, Char2)(const(Char1)[] a, const(Char2)[] b) { return comparePropertyName(a, b) < 0; } //============================================================================ // Utilities for compression of Unicode code point sets //============================================================================ @safe void compressTo(uint val, ref ubyte[] arr) pure nothrow { // not optimized as usually done 1 time (and not public interface) if(val < 128) arr ~= cast(ubyte)val; else if(val < (1<<13)) { arr ~= (0b1_00<<5) | cast(ubyte)(val>>8); arr ~= val & 0xFF; } else { assert(val < (1<<21)); arr ~= (0b1_01<<5) | cast(ubyte)(val>>16); arr ~= (val >> 8) & 0xFF; arr ~= val & 0xFF; } } @safe uint decompressFrom(const(ubyte)[] arr, ref size_t idx) pure { uint first = arr[idx++]; if(!(first & 0x80)) // no top bit -> [0..127] return first; uint extra = ((first>>5) & 1) + 1; // [1, 2] uint val = (first & 0x1F); enforce(idx + extra <= arr.length, "bad code point interval encoding"); foreach(j; 0..extra) val = (val<<8) | arr[idx+j]; idx += extra; return val; } package ubyte[] compressIntervals(Range)(Range intervals) if(isInputRange!Range && isIntegralPair!(ElementType!Range)) { ubyte[] storage; uint base = 0; // RLE encode foreach(val; intervals) { compressTo(val[0]-base, storage); base = val[0]; if(val[1] != lastDchar+1) // till the end of the domain so don't store it { compressTo(val[1]-base, storage); base = val[1]; } } return storage; } unittest { auto run = [tuple(80, 127), tuple(128, (1<<10)+128)]; ubyte[] enc = [cast(ubyte)80, 47, 1, (0b1_00<<5) | (1<<2), 0]; assert(compressIntervals(run) == enc); auto run2 = [tuple(0, (1<<20)+512+1), tuple((1<<20)+512+4, lastDchar+1)]; ubyte[] enc2 = [cast(ubyte)0, (0b1_01<<5) | (1<<4), 2, 1, 3]; // odd length-ed assert(compressIntervals(run2) == enc2); size_t idx = 0; assert(decompressFrom(enc, idx) == 80); assert(decompressFrom(enc, idx) == 47); assert(decompressFrom(enc, idx) == 1); assert(decompressFrom(enc, idx) == (1<<10)); idx = 0; assert(decompressFrom(enc2, idx) == 0); assert(decompressFrom(enc2, idx) == (1<<20)+512+1); assert(equalS(decompressIntervals(compressIntervals(run)), run)); assert(equalS(decompressIntervals(compressIntervals(run2)), run2)); } // Creates a range of $(D CodepointInterval) that lazily decodes compressed data. @safe package auto decompressIntervals(const(ubyte)[] data) { return DecompressedIntervals(data); } @trusted struct DecompressedIntervals { const(ubyte)[] _stream; size_t _idx; CodepointInterval _front; this(const(ubyte)[] stream) { _stream = stream; popFront(); } @property CodepointInterval front() { assert(!empty); return _front; } void popFront() { if(_idx == _stream.length) { _idx = size_t.max; return; } uint base = _front[1]; _front[0] = base + decompressFrom(_stream, _idx); if(_idx == _stream.length)// odd length ---> till the end _front[1] = lastDchar+1; else { base = _front[0]; _front[1] = base + decompressFrom(_stream, _idx); } } @property bool empty() const { return _idx == size_t.max; } @property DecompressedIntervals save() { return this; } } static assert(isInputRange!DecompressedIntervals); static assert(isForwardRange!DecompressedIntervals); //============================================================================ version(std_uni_bootstrap){} else { // helper for looking up code point sets @trusted ptrdiff_t findUnicodeSet(alias table, C)(in C[] name) { auto range = assumeSorted!((a,b) => propertyNameLess(a,b)) (table.map!"a.name"()); size_t idx = range.lowerBound(name).length; if(idx < range.length && comparePropertyName(range[idx], name) == 0) return idx; return -1; } // another one that loads it @trusted bool loadUnicodeSet(alias table, Set, C)(in C[] name, ref Set dest) { auto idx = findUnicodeSet!table(name); if(idx >= 0) { dest = Set(asSet(table[idx].compressed)); return true; } return false; } @trusted bool loadProperty(Set=CodepointSet, C) (in C[] name, ref Set target) { alias ucmp = comparePropertyName; // conjure cumulative properties by hand if(ucmp(name, "L") == 0 || ucmp(name, "Letter") == 0) { target |= asSet(uniProps.Lu); target |= asSet(uniProps.Ll); target |= asSet(uniProps.Lt); target |= asSet(uniProps.Lo); target |= asSet(uniProps.Lm); } else if(ucmp(name,"LC") == 0 || ucmp(name,"Cased Letter")==0) { target |= asSet(uniProps.Ll); target |= asSet(uniProps.Lu); target |= asSet(uniProps.Lt);// Title case } else if(ucmp(name, "M") == 0 || ucmp(name, "Mark") == 0) { target |= asSet(uniProps.Mn); target |= asSet(uniProps.Mc); target |= asSet(uniProps.Me); } else if(ucmp(name, "N") == 0 || ucmp(name, "Number") == 0) { target |= asSet(uniProps.Nd); target |= asSet(uniProps.Nl); target |= asSet(uniProps.No); } else if(ucmp(name, "P") == 0 || ucmp(name, "Punctuation") == 0) { target |= asSet(uniProps.Pc); target |= asSet(uniProps.Pd); target |= asSet(uniProps.Ps); target |= asSet(uniProps.Pe); target |= asSet(uniProps.Pi); target |= asSet(uniProps.Pf); target |= asSet(uniProps.Po); } else if(ucmp(name, "S") == 0 || ucmp(name, "Symbol") == 0) { target |= asSet(uniProps.Sm); target |= asSet(uniProps.Sc); target |= asSet(uniProps.Sk); target |= asSet(uniProps.So); } else if(ucmp(name, "Z") == 0 || ucmp(name, "Separator") == 0) { target |= asSet(uniProps.Zs); target |= asSet(uniProps.Zl); target |= asSet(uniProps.Zp); } else if(ucmp(name, "C") == 0 || ucmp(name, "Other") == 0) { target |= asSet(uniProps.Co); target |= asSet(uniProps.Lo); target |= asSet(uniProps.No); target |= asSet(uniProps.So); target |= asSet(uniProps.Po); } else if(ucmp(name, "graphical") == 0){ target |= asSet(uniProps.Alphabetic); target |= asSet(uniProps.Mn); target |= asSet(uniProps.Mc); target |= asSet(uniProps.Me); target |= asSet(uniProps.Nd); target |= asSet(uniProps.Nl); target |= asSet(uniProps.No); target |= asSet(uniProps.Pc); target |= asSet(uniProps.Pd); target |= asSet(uniProps.Ps); target |= asSet(uniProps.Pe); target |= asSet(uniProps.Pi); target |= asSet(uniProps.Pf); target |= asSet(uniProps.Po); target |= asSet(uniProps.Zs); target |= asSet(uniProps.Sm); target |= asSet(uniProps.Sc); target |= asSet(uniProps.Sk); target |= asSet(uniProps.So); } else if(ucmp(name, "any") == 0) target = Set(0,0x110000); else if(ucmp(name, "ascii") == 0) target = Set(0,0x80); else return loadUnicodeSet!(uniProps.tab)(name, target); return true; } // CTFE-only helper for checking property names at compile-time @safe bool isPrettyPropertyName(C)(in C[] name) { auto names = [ "L", "Letters", "LC", "Cased Letter", "M", "Mark", "N", "Number", "P", "Punctuation", "S", "Symbol", "Z", "Separator", "Graphical", "any", "ascii" ]; auto x = find!(x => comparePropertyName(x, name) == 0)(names); return !x.empty; } // ditto, CTFE-only, not optimized @safe private static bool findSetName(alias table, C)(in C[] name) { return findUnicodeSet!table(name) >= 0; } template SetSearcher(alias table, string kind) { /// Run-time checked search. static auto opCall(C)(in C[] name) if(is(C : dchar)) { CodepointSet set; if(loadUnicodeSet!table(name, set)) return set; throw new Exception("No unicode set for "~kind~" by name " ~name.to!string()~" was found."); } /// Compile-time checked search. static @property auto opDispatch(string name)() { static if(findSetName!table(name)) { CodepointSet set; loadUnicodeSet!table(name, set); return set; } else static assert(false, "No unicode set for "~kind~" by name " ~name~" was found."); } } /** A single entry point to lookup Unicode $(CODEPOINT) sets by name or alias of a block, script or general category. It uses well defined standard rules of property name lookup. This includes fuzzy matching of names, so that 'White_Space', 'white-SpAce' and 'whitespace' are all considered equal and yield the same set of white space $(CHARACTERS). */ @safe public struct unicode { /** Performs the lookup of set of $(CODEPOINTS) with compile-time correctness checking. This short-cut version combines 3 searches: across blocks, scripts, and common binary properties. Note that since scripts and blocks overlap the usual trick to disambiguate is used - to get a block use $(D unicode.InBlockName), to search a script use $(D unicode.ScriptName). See also $(LREF block), $(LREF script) and (not included in this search) $(LREF hangulSyllableType). Example: --- auto ascii = unicode.ASCII; assert(ascii['A']); assert(ascii['~']); assert(!ascii['\u00e0']); // matching is case-insensitive assert(ascii == unicode.ascII); assert(!ascii['à']); // underscores, '-' and whitespace in names are ignored too auto latin = unicode.in_latin1_Supplement; assert(latin['à']); assert(!latin['$']); // BTW Latin 1 Supplement is a block, hence "In" prefix assert(latin == unicode("In Latin 1 Supplement")); import std.exception; // run-time look up throws if no such set is found assert(collectException(unicode("InCyrilliac"))); --- */ static @property auto opDispatch(string name)() { static if(findAny(name)) return loadAny(name); else static assert(false, "No unicode set by name "~name~" was found."); } /** The same lookup across blocks, scripts, or binary properties, but performed at run-time. This version is provided for cases where $(D name) is not known beforehand; otherwise compile-time checked $(LREF opDispatch) is typically a better choice. See the $(S_LINK Unicode properties, table of properties) for available sets. */ static auto opCall(C)(in C[] name) if(is(C : dchar)) { return loadAny(name); } /** Narrows down the search for sets of $(CODEPOINTS) to all Unicode blocks. See also $(S_LINK Unicode properties, table of properties). Note: Here block names are unambiguous as no scripts are searched and thus to search use simply $(D unicode.block.BlockName) notation. See $(S_LINK Unicode properties, table of properties) for available sets. Example: --- // use .block for explicitness assert(unicode.block.Greek_and_Coptic == unicode.InGreek_and_Coptic); --- */ struct block { mixin SetSearcher!(blocks.tab, "block"); } /** Narrows down the search for sets of $(CODEPOINTS) to all Unicode scripts. See the $(S_LINK Unicode properties, table of properties) for available sets. Example: --- auto arabicScript = unicode.script.arabic; auto arabicBlock = unicode.block.arabic; // there is an intersection between script and block assert(arabicBlock['؁']); assert(arabicScript['؁']); // but they are different assert(arabicBlock != arabicScript); assert(arabicBlock == unicode.inArabic); assert(arabicScript == unicode.arabic); --- */ struct script { mixin SetSearcher!(scripts.tab, "script"); } /** Fetch a set of $(CODEPOINTS) that have the given hangul syllable type. Other non-binary properties (once supported) follow the same notation - $(D unicode.propertyName.propertyValue) for compile-time checked access and $(D unicode.propertyName(propertyValue)) for run-time checked one. See the $(S_LINK Unicode properties, table of properties) for available sets. Example: --- // L here is syllable type not Letter as in unicode.L short-cut auto leadingVowel = unicode.hangulSyllableType("L"); // check that some leading vowels are present foreach(vowel; '\u1110'..'\u115F') assert(leadingVowel[vowel]); assert(leadingVowel == unicode.hangulSyllableType.L); --- */ struct hangulSyllableType { mixin SetSearcher!(hangul.tab, "hangul syllable type"); } private: alias ucmp = comparePropertyName; static bool findAny(string name) { return isPrettyPropertyName(name) || findSetName!(uniProps.tab)(name) || findSetName!(scripts.tab)(name) || (ucmp(name[0..2],"In") == 0 && findSetName!(blocks.tab)(name[2..$])); } static auto loadAny(Set=CodepointSet, C)(in C[] name) { Set set; bool loaded = loadProperty(name, set) || loadUnicodeSet!(scripts.tab)(name, set) || (ucmp(name[0..2],"In") == 0 && loadUnicodeSet!(blocks.tab)(name[2..$], set)); if(loaded) return set; throw new Exception("No unicode set by name "~name.to!string()~" was found."); } // FIXME: re-disable once the compiler is fixed // Disabled to prevent the mistake of creating instances of this pseudo-struct. //@disable ~this(); } unittest { auto ascii = unicode.ASCII; assert(ascii['A']); assert(ascii['~']); assert(!ascii['\u00e0']); // matching is case-insensitive assert(ascii == unicode.ascII); assert(!ascii['à']); // underscores, '-' and whitespace in names are ignored too auto latin = unicode.Inlatin1_Supplement; assert(latin['à']); assert(!latin['$']); // BTW Latin 1 Supplement is a block, hence "In" prefix assert(latin == unicode("In Latin 1 Supplement")); import std.exception; // R-T look up throws if no such set is found assert(collectException(unicode("InCyrilliac"))); assert(unicode.block.Greek_and_Coptic == unicode.InGreek_and_Coptic); // L here is explicitly syllable type not "Letter" as in unicode.L auto leadingVowel = unicode.hangulSyllableType("L"); // check that some leading vowels are present foreach(vowel; '\u1110'..'\u115F'+1) assert(leadingVowel[vowel]); assert(leadingVowel == unicode.hangulSyllableType.L); auto arabicScript = unicode.script.arabic; auto arabicBlock = unicode.block.arabic; // there is an intersection between script and block assert(arabicBlock['؁']); assert(arabicScript['؁']); // but they are different assert(arabicBlock != arabicScript); assert(arabicBlock == unicode.inArabic); assert(arabicScript == unicode.arabic); } unittest { assert(unicode("InHebrew") == asSet(blocks.Hebrew)); assert(unicode("separator") == (asSet(uniProps.Zs) | asSet(uniProps.Zl) | asSet(uniProps.Zp))); assert(unicode("In-Kharoshthi") == asSet(blocks.Kharoshthi)); } enum EMPTY_CASE_TRIE = ushort.max;// from what gen_uni uses internally // control - '\r' enum controlSwitch = ` case '\u0000':..case '\u0008':case '\u000E':..case '\u001F':case '\u007F':..case '\u0084':case '\u0086':..case '\u009F': case '\u0009':..case '\u000C': case '\u0085': `; // TODO: redo the most of hangul stuff algorithmically in case of Graphemes too // kill unrolled switches private static bool isRegionalIndicator(dchar ch) { return ch >= '\U0001F1E6' && ch <= '\U0001F1FF'; } template genericDecodeGrapheme(bool getValue) { alias graphemeExtend = graphemeExtendTrie; alias spacingMark = mcTrie; static if(getValue) alias Value = Grapheme; else alias Value = void; Value genericDecodeGrapheme(Input)(ref Input range) { enum GraphemeState { Start, CR, RI, L, V, LVT } static if(getValue) Grapheme grapheme; auto state = GraphemeState.Start; enum eat = q{ static if(getValue) grapheme ~= ch; range.popFront(); }; dchar ch; assert(!range.empty, "Attempting to decode grapheme from an empty " ~ Input.stringof); while(!range.empty) { ch = range.front; final switch(state) with(GraphemeState) { case Start: mixin(eat); if(ch == '\r') state = CR; else if(isRegionalIndicator(ch)) state = RI; else if(isHangL(ch)) state = L; else if(hangLV[ch] || isHangV(ch)) state = V; else if(hangLVT[ch]) state = LVT; else if(isHangT(ch)) state = LVT; else { switch(ch) { mixin(controlSwitch); goto L_End; default: goto L_End_Extend; } } break; case CR: if(ch == '\n') mixin(eat); goto L_End_Extend; case RI: if(isRegionalIndicator(ch)) mixin(eat); else goto L_End_Extend; break; case L: if(isHangL(ch)) mixin(eat); else if(isHangV(ch) || hangLV[ch]) { state = V; mixin(eat); } else if(hangLVT[ch]) { state = LVT; mixin(eat); } else goto L_End_Extend; break; case V: if(isHangV(ch)) mixin(eat); else if(isHangT(ch)) { state = LVT; mixin(eat); } else goto L_End_Extend; break; case LVT: if(isHangT(ch)) { mixin(eat); } else goto L_End_Extend; break; } } L_End_Extend: while(!range.empty) { ch = range.front; // extend & spacing marks if(!graphemeExtend[ch] && !spacingMark[ch]) break; mixin(eat); } L_End: static if(getValue) return grapheme; } } @trusted: public: // Public API continues /++ Returns the length of grapheme cluster starting at $(D index). Both the resulting length and the $(D index) are measured in $(S_LINK Code unit, code units). Example: --- // ASCII as usual is 1 code unit, 1 code point etc. assert(graphemeStride(" ", 1) == 1); // A + combing ring above string city = "A\u030Arhus"; size_t first = graphemeStride(city, 0); assert(first == 3); //\u030A has 2 UTF-8 code units assert(city[0..first] == "A\u030A"); assert(city[first..$] == "rhus"); --- +/ size_t graphemeStride(C)(in C[] input, size_t index) if(is(C : dchar)) { auto src = input[index..$]; auto n = src.length; genericDecodeGrapheme!(false)(src); return n - src.length; } // for now tested separately see test_grapheme.d unittest { assert(graphemeStride(" ", 1) == 1); // A + combing ring above string city = "A\u030Arhus"; size_t first = graphemeStride(city, 0); assert(first == 3); //\u030A has 2 UTF-8 code units assert(city[0..first] == "A\u030A"); assert(city[first..$] == "rhus"); } /++ Reads one full grapheme cluster from an input range of dchar $(D inp). For examples see the $(LREF Grapheme) below. Note: This function modifies $(D inp) and thus $(D inp) must be an L-value. +/ Grapheme decodeGrapheme(Input)(ref Input inp) if(isInputRange!Input && is(Unqual!(ElementType!Input) == dchar)) { return genericDecodeGrapheme!true(inp); } unittest { Grapheme gr; string s = " \u0020\u0308 "; gr = decodeGrapheme(s); assert(gr.length == 1 && gr[0] == ' '); gr = decodeGrapheme(s); assert(gr.length == 2 && equalS(gr[0..2], " \u0308")); s = "\u0300\u0308\u1100"; assert(equalS(decodeGrapheme(s)[], "\u0300\u0308")); assert(equalS(decodeGrapheme(s)[], "\u1100")); s = "\u11A8\u0308\uAC01"; assert(equalS(decodeGrapheme(s)[], "\u11A8\u0308")); assert(equalS(decodeGrapheme(s)[], "\uAC01")); } /++ $(P Iterate a string by grapheme.) $(P Useful for doing string manipulation that needs to be aware of graphemes.) See_Also: $(LREF byCodePoint) +/ // TODO: Bidirectional access auto byGrapheme(Range)(Range range) if(isInputRange!Range && is(Unqual!(ElementType!Range) == dchar)) { static struct Result { private Range _range; private Grapheme _front; bool empty() @property { return _front.length == 0; } Grapheme front() @property { return _front; } void popFront() { _front = _range.empty ? Grapheme.init : _range.decodeGrapheme(); } static if(isForwardRange!Range) { Result save() @property { return Result(_range.save, _front); } } } auto result = Result(range); result.popFront(); return result; } /// unittest { auto text = "noe\u0308l"; // noël using e + combining diaeresis assert(text.walkLength == 5); // 5 code points auto gText = text.byGrapheme; assert(gText.walkLength == 4); // 4 graphemes assert(gText.take(3).equal("noe\u0308".byGrapheme)); assert(gText.drop(3).equal("l".byGrapheme)); } // For testing non-forward-range input ranges version(unittest) private static struct InputRangeString { private string s; bool empty() @property { return s.empty; } dchar front() @property { return s.front; } void popFront() { s.popFront(); } } unittest { assert("".byGrapheme.walkLength == 0); auto reverse = "le\u0308on"; assert(reverse.walkLength == 5); auto gReverse = reverse.byGrapheme; assert(gReverse.walkLength == 4); foreach(text; TypeTuple!("noe\u0308l"c, "noe\u0308l"w, "noe\u0308l"d)) { assert(text.walkLength == 5); static assert(isForwardRange!(typeof(text))); auto gText = text.byGrapheme; static assert(isForwardRange!(typeof(gText))); assert(gText.walkLength == 4); assert(gText.array.retro.equal(gReverse)); } auto nonForwardRange = InputRangeString("noe\u0308l").byGrapheme; static assert(!isForwardRange!(typeof(nonForwardRange))); assert(nonForwardRange.walkLength == 4); } /++ $(P Lazily transform a range of $(LREF Grapheme)s to a range of code points.) $(P Useful for converting the result to a string after doing operations on graphemes.) $(P Acts as the identity function when given a range of code points.) +/ // TODO: Propagate bidirectional access auto byCodePoint(Range)(Range range) if(isInputRange!Range && is(Unqual!(ElementType!Range) == Grapheme)) { static struct Result { private Range _range; private size_t i = 0; bool empty() @property { return _range.empty; } dchar front() @property { return _range.front[i]; } void popFront() { ++i; if(i >= _range.front.length) { _range.popFront(); i = 0; } } static if(isForwardRange!Range) { Result save() @property { return Result(_range.save, i); } } } return Result(range); } /// Ditto Range byCodePoint(Range)(Range range) if(isInputRange!Range && is(Unqual!(ElementType!Range) == dchar)) { return range; } /// unittest { import std.string : text; string s = "noe\u0308l"; // noël // reverse it and convert the result to a string string reverse = s.byGrapheme .array .retro .byCodePoint .text; assert(reverse == "le\u0308on"); // lëon } unittest { assert("".byGrapheme.byCodePoint.equal("")); string text = "noe\u0308l"; static assert(is(typeof(text.byCodePoint) == string)); auto gText = InputRangeString(text).byGrapheme; static assert(!isForwardRange!(typeof(gText))); auto cpText = gText.byCodePoint; static assert(!isForwardRange!(typeof(cpText))); assert(cpText.walkLength == text.walkLength); } /++ $(P A structure designed to effectively pack $(CHARACTERS) of a $(CLUSTER). ) $(P $(D Grapheme) has value semantics so 2 copies of a $(D Grapheme) always refer to distinct objects. In most actual scenarios a $(D Grapheme) fits on the stack and avoids memory allocation overhead for all but quite long clusters. ) Example: --- import std.algorithm; string bold = "ku\u0308hn"; // note that decodeGrapheme takes parameter by ref // slicing a grapheme yields a range of dchar assert(decodeGrapheme(bold)[].equal("k")); // the next grapheme is 2 characters long auto wideOne = decodeGrapheme(bold); assert(wideOne.length == 2); assert(wideOne[].equal("u\u0308")); // the usual range manipulation is possible assert(wideOne[].filter!isMark.equal("\u0308")); --- $(P See also $(LREF decodeGrapheme), $(LREF graphemeStride). ) +/ @trusted struct Grapheme { public: this(C)(in C[] chars...) if(is(C : dchar)) { this ~= chars; } this(Input)(Input seq) if(!isDynamicArray!Input && isInputRange!Input && is(ElementType!Input : dchar)) { this ~= seq; } /// Gets a $(CODEPOINT) at the given index in this cluster. dchar opIndex(size_t index) const pure nothrow { assert(index < length); return read24(isBig ? ptr_ : small_.ptr, index); } /++ Writes a $(CODEPOINT) $(D ch) at given index in this cluster. Warning: Use of this facility may invalidate grapheme cluster, see also $(LREF Grapheme.valid). Example: --- auto g = Grapheme("A\u0302"); assert(g[0] == 'A'); assert(g.valid); g[1] = '~'; // ASCII tilda is not a combining mark assert(g[1] == '~'); assert(!g.valid); --- +/ void opIndexAssign(dchar ch, size_t index) pure nothrow { assert(index < length); write24(isBig ? ptr_ : small_.ptr, ch, index); } /++ Random-access range over Grapheme's $(CHARACTERS). Warning: Invalidates when this Grapheme leaves the scope, attempts to use it then would lead to memory corruption. +/ @system auto opSlice(size_t a, size_t b) pure nothrow { return sliceOverIndexed(a, b, &this); } /// ditto @system auto opSlice() pure nothrow { return sliceOverIndexed(0, length, &this); } /// Grapheme cluster length in $(CODEPOINTS). @property size_t length() const pure nothrow { return isBig ? len_ : slen_ & 0x7F; } /++ Append $(CHARACTER) $(D ch) to this grapheme. Warning: Use of this facility may invalidate grapheme cluster, see also $(D valid). Example: --- auto g = Grapheme("A"); assert(g.valid); g ~= '\u0301'; assert(g[].equal("A\u0301")); assert(g.valid); g ~= "B"; // not a valid grapheme cluster anymore assert(!g.valid); // still could be useful though assert(g[].equal("A\u0301B")); --- See also $(LREF Grapheme.valid) below. +/ ref opOpAssign(string op)(dchar ch) { static if(op == "~") { if(!isBig) { if(slen_ + 1 > small_cap) convertToBig();// & fallthrough to "big" branch else { write24(small_.ptr, ch, smallLength); slen_++; return this; } } assert(isBig); if(len_ + 1 > cap_) { cap_ += grow; ptr_ = cast(ubyte*)enforce(realloc(ptr_, 3*(cap_+1))); } write24(ptr_, ch, len_++); return this; } else static assert(false, "No operation "~op~" defined for Grapheme"); } /// Append all $(CHARACTERS) from the input range $(D inp) to this Grapheme. ref opOpAssign(string op, Input)(Input inp) if(isInputRange!Input && is(ElementType!Input : dchar)) { static if(op == "~") { foreach(dchar ch; inp) this ~= ch; return this; } else static assert(false, "No operation "~op~" defined for Grapheme"); } /++ True if this object contains valid extended grapheme cluster. Decoding primitives of this module always return a valid $(D Grapheme). Appending to and direct manipulation of grapheme's $(CHARACTERS) may render it no longer valid. Certain applications may chose to use Grapheme as a "small string" of any $(CODEPOINTS) and ignore this property entirely. +/ @property bool valid()() /*const*/ { auto r = this[]; genericDecodeGrapheme!false(r); return r.length == 0; } this(this) { if(isBig) {// dup it auto raw_cap = 3*(cap_+1); auto p = cast(ubyte*)enforce(malloc(raw_cap)); p[0..raw_cap] = ptr_[0..raw_cap]; ptr_ = p; } } ~this() { if(isBig) { free(ptr_); } } private: enum small_bytes = ((ubyte*).sizeof+3*size_t.sizeof-1); // "out of the blue" grow rate, needs testing // (though graphemes are typically small < 9) enum grow = 20; enum small_cap = small_bytes/3; enum small_flag = 0x80, small_mask = 0x7F; // 16 bytes in 32bits, should be enough for the majority of cases union { struct { ubyte* ptr_; size_t cap_; size_t len_; size_t padding_; } struct { ubyte[small_bytes] small_; ubyte slen_; } } void convertToBig() { size_t k = smallLength; ubyte* p = cast(ubyte*)enforce(malloc(3*(grow+1))); for(int i=0; i<k; i++) write24(p, read24(small_.ptr, i), i); // now we can overwrite small array data ptr_ = p; len_ = slen_; assert(grow > len_); cap_ = grow; setBig(); } void setBig(){ slen_ |= small_flag; } @property size_t smallLength() pure nothrow { return slen_ & small_mask; } @property ubyte isBig() const pure nothrow { return slen_ & small_flag; } } static assert(Grapheme.sizeof == size_t.sizeof*4); // verify the example unittest { import std.algorithm; string bold = "ku\u0308hn"; // note that decodeGrapheme takes parameter by ref auto first = decodeGrapheme(bold); assert(first.length == 1); assert(first[0] == 'k'); // the next grapheme is 2 characters long auto wideOne = decodeGrapheme(bold); // slicing a grapheme yields a random-access range of dchar assert(wideOne[].equalS("u\u0308")); assert(wideOne.length == 2); static assert(isRandomAccessRange!(typeof(wideOne[]))); // all of the usual range manipulation is possible assert(wideOne[].filter!isMark().equalS("\u0308")); auto g = Grapheme("A"); assert(g.valid); g ~= '\u0301'; assert(g[].equalS("A\u0301")); assert(g.valid); g ~= "B"; // not a valid grapheme cluster anymore assert(!g.valid); // still could be useful though assert(g[].equalS("A\u0301B")); } unittest { auto g = Grapheme("A\u0302"); assert(g[0] == 'A'); assert(g.valid); g[1] = '~'; // ASCII tilda is not a combining mark assert(g[1] == '~'); assert(!g.valid); } unittest { // not valid clusters (but it just a test) auto g = Grapheme('a', 'b', 'c', 'd', 'e'); assert(g[0] == 'a'); assert(g[1] == 'b'); assert(g[2] == 'c'); assert(g[3] == 'd'); assert(g[4] == 'e'); g[3] = 'Й'; assert(g[2] == 'c'); assert(g[3] == 'Й', text(g[3], " vs ", 'Й')); assert(g[4] == 'e'); assert(!g.valid); g ~= 'ц'; g ~= '~'; assert(g[0] == 'a'); assert(g[1] == 'b'); assert(g[2] == 'c'); assert(g[3] == 'Й'); assert(g[4] == 'e'); assert(g[5] == 'ц'); assert(g[6] == '~'); assert(!g.valid); Grapheme copy = g; copy[0] = 'X'; copy[1] = '-'; assert(g[0] == 'a' && copy[0] == 'X'); assert(g[1] == 'b' && copy[1] == '-'); assert(equalS(g[2..g.length], copy[2..copy.length])); copy = Grapheme("АБВГДЕЁЖЗИКЛМ"); assert(equalS(copy[0..8], "АБВГДЕЁЖ"), text(copy[0..8])); copy ~= "xyz"; assert(equalS(copy[13..15], "xy"), text(copy[13..15])); assert(!copy.valid); Grapheme h; foreach(dchar v; iota(cast(int)'A', cast(int)'Z'+1).map!"cast(dchar)a"()) h ~= v; assert(equalS(h[], iota(cast(int)'A', cast(int)'Z'+1))); } /++ $(P Does basic case-insensitive comparison of strings $(D str1) and $(D str2). This function uses simpler comparison rule thus achieving better performance then $(LREF icmp). However keep in mind the warning below.) Warning: This function only handles 1:1 $(CODEPOINT) mapping and thus is not sufficient for certain alphabets like German, Greek and few others. Example: --- assert(sicmp("Август", "авгусТ") == 0); // Greek also works as long as there is no 1:M mapping in sight assert(sicmp("ΌΎ", "όύ") == 0); // things like the following won't get matched as equal // Greek small letter iota with dialytika and tonos assert(sicmp("ΐ", "\u03B9\u0308\u0301") != 0); // while icmp has no problem with that assert(icmp("ΐ", "\u03B9\u0308\u0301") == 0); assert(icmp("ΌΎ", "όύ") == 0); --- +/ int sicmp(S1, S2)(S1 str1, S2 str2) if(isForwardRange!S1 && is(Unqual!(ElementType!S1) == dchar) && isForwardRange!S2 && is(Unqual!(ElementType!S2) == dchar)) { import std.utf : decode; alias sTable = simpleCaseTable; size_t ridx=0; foreach(dchar lhs; str1) { if(ridx == str2.length) return 1; dchar rhs = std.utf.decode(str2, ridx); int diff = lhs - rhs; if(!diff) continue; size_t idx = simpleCaseTrie[lhs]; size_t idx2 = simpleCaseTrie[rhs]; // simpleCaseTrie is packed index table if(idx != EMPTY_CASE_TRIE) { if(idx2 != EMPTY_CASE_TRIE) {// both cased chars // adjust idx --> start of bucket idx = idx - sTable[idx].n; idx2 = idx2 - sTable[idx2].n; if(idx == idx2)// one bucket, equivalent chars continue; else// not the same bucket diff = sTable[idx].ch - sTable[idx2].ch; } else diff = sTable[idx - sTable[idx].n].ch - rhs; } else if(idx2 != EMPTY_CASE_TRIE) { diff = lhs - sTable[idx2 - sTable[idx2].n].ch; } // one of chars is not cased at all return diff; } return ridx == str2.length ? 0 : -1; } // overloads for the most common cases to reduce compile time @safe pure /*TODO nothrow*/ { int sicmp(const(char)[] str1, const(char)[] str2) { return sicmp!(const(char)[], const(char)[])(str1, str2); } int sicmp(const(wchar)[] str1, const(wchar)[] str2) { return sicmp!(const(wchar)[], const(wchar)[])(str1, str2); } int sicmp(const(dchar)[] str1, const(dchar)[] str2) { return sicmp!(const(dchar)[], const(dchar)[])(str1, str2); } } private int fullCasedCmp(Range)(dchar lhs, dchar rhs, ref Range rtail) @trusted pure /*TODO nothrow*/ { alias fTable = fullCaseTable; size_t idx = fullCaseTrie[lhs]; // fullCaseTrie is packed index table if(idx == EMPTY_CASE_TRIE) return lhs; size_t start = idx - fTable[idx].n; size_t end = fTable[idx].size + start; assert(fTable[start].entry_len == 1); for(idx=start; idx<end; idx++) { auto entryLen = fTable[idx].entry_len; if(entryLen == 1) { if(fTable[idx].seq[0] == rhs) { return 0; } } else {// OK it's a long chunk, like 'ss' for German dstring seq = fTable[idx].seq[0..entryLen]; if(rhs == seq[0] && rtail.skipOver(seq[1..$])) { // note that this path modifies rtail // iff we managed to get there return 0; } } } return fTable[start].seq[0]; // new remapped character for accurate diffs } /++ $(P Does case insensitive comparison of $(D str1) and $(D str2). Follows the rules of full case-folding mapping. This includes matching as equal german ß with "ss" and other 1:M $(CODEPOINT) mappings unlike $(LREF sicmp). The cost of $(D icmp) being pedantically correct is slightly worse performance. ) Example: --- assert(icmp("Rußland", "Russland") == 0); assert(icmp("ᾩ -> \u1F70\u03B9", "\u1F61\u03B9 -> ᾲ") == 0); --- +/ int icmp(S1, S2)(S1 str1, S2 str2) if(isForwardRange!S1 && is(Unqual!(ElementType!S1) == dchar) && isForwardRange!S2 && is(Unqual!(ElementType!S2) == dchar)) { for(;;) { if(str1.empty) return str2.empty ? 0 : -1; dchar lhs = str1.front; if(str2.empty) return 1; dchar rhs = str2.front; str1.popFront(); str2.popFront(); int diff = lhs - rhs; if(!diff) continue; // first try to match lhs to <rhs,right-tail> sequence int cmpLR = fullCasedCmp(lhs, rhs, str2); if(!cmpLR) continue; // then rhs to <lhs,left-tail> sequence int cmpRL = fullCasedCmp(rhs, lhs, str1); if(!cmpRL) continue; // cmpXX contain remapped codepoints // to obtain stable ordering of icmp diff = cmpLR - cmpRL; return diff; } } // overloads for the most common cases to reduce compile time @safe pure /*TODO nothrow*/ { int icmp(const(char)[] str1, const(char)[] str2) { return icmp!(const(char)[], const(char)[])(str1, str2); } int icmp(const(wchar)[] str1, const(wchar)[] str2) { return icmp!(const(wchar)[], const(wchar)[])(str1, str2); } int icmp(const(dchar)[] str1, const(dchar)[] str2) { return icmp!(const(dchar)[], const(dchar)[])(str1, str2); } } unittest { assertCTFEable!( { foreach(cfunc; TypeTuple!(icmp, sicmp)) { foreach(S1; TypeTuple!(string, wstring, dstring)) foreach(S2; TypeTuple!(string, wstring, dstring)) { assert(cfunc("".to!S1(), "".to!S2()) == 0); assert(cfunc("A".to!S1(), "".to!S2()) > 0); assert(cfunc("".to!S1(), "0".to!S2()) < 0); assert(cfunc("abc".to!S1(), "abc".to!S2()) == 0); assert(cfunc("abcd".to!S1(), "abc".to!S2()) > 0); assert(cfunc("abc".to!S1(), "abcd".to!S2()) < 0); assert(cfunc("Abc".to!S1(), "aBc".to!S2()) == 0); assert(cfunc("авГуст".to!S1(), "АВгУСТ".to!S2()) == 0); // Check example: assert(cfunc("Август".to!S1(), "авгусТ".to!S2()) == 0); assert(cfunc("ΌΎ".to!S1(), "όύ".to!S2()) == 0); } // check that the order is properly agnostic to the case auto strs = [ "Apple", "ORANGE", "orAcle", "amp", "banana"]; sort!((a,b) => cfunc(a,b) < 0)(strs); assert(strs == ["amp", "Apple", "banana", "orAcle", "ORANGE"]); } assert(icmp("ßb", "ssa") > 0); // Check example: assert(icmp("Russland", "Rußland") == 0); assert(icmp("ᾩ -> \u1F70\u03B9", "\u1F61\u03B9 -> ᾲ") == 0); assert(icmp("ΐ"w, "\u03B9\u0308\u0301") == 0); assert(sicmp("ΐ", "\u03B9\u0308\u0301") != 0); //bugzilla 11057 assert( icmp("K", "L") < 0 ); }); } /++ $(P Returns the $(S_LINK Combining class, combining class) of $(D ch).) Example: --- // shorten the code alias CC = combiningClass; // combining tilda assert(CC('\u0303') == 230); // combining ring below assert(CC('\u0325') == 220); // the simple consequence is that "tilda" should be // placed after a "ring below" in a sequence --- +/ ubyte combiningClass(dchar ch) { return combiningClassTrie[ch]; } unittest { foreach(ch; 0..0x80) assert(combiningClass(ch) == 0); assert(combiningClass('\u05BD') == 22); assert(combiningClass('\u0300') == 230); assert(combiningClass('\u0317') == 220); assert(combiningClass('\u1939') == 222); } /// Unicode character decomposition type. enum UnicodeDecomposition { /// Canonical decomposition. The result is canonically equivalent sequence. Canonical, /** Compatibility decomposition. The result is compatibility equivalent sequence. Note: Compatibility decomposition is a $(B lossy) conversion, typically suitable only for fuzzy matching and internal processing. */ Compatibility }; /** Shorthand aliases for character decomposition type, passed as a template parameter to $(LREF decompose). */ enum { Canonical = UnicodeDecomposition.Canonical, Compatibility = UnicodeDecomposition.Compatibility }; /++ Try to canonically compose 2 $(CHARACTERS). Returns the composed $(CHARACTER) if they do compose and dchar.init otherwise. The assumption is that $(D first) comes before $(D second) in the original text, usually meaning that the first is a starter. Note: Hangul syllables are not covered by this function. See $(D composeJamo) below. Example: --- assert(compose('A','\u0308') == '\u00C4'); assert(compose('A', 'B') == dchar.init); assert(compose('C', '\u0301') == '\u0106'); // note that the starter is the first one // thus the following doesn't compose assert(compose('\u0308', 'A') == dchar.init); --- +/ public dchar compose(dchar first, dchar second) { import std.internal.unicode_comp; size_t packed = compositionJumpTrie[first]; if(packed == ushort.max) return dchar.init; // unpack offset and length size_t idx = packed & composeIdxMask, cnt = packed >> composeCntShift; // TODO: optimize this micro binary search (no more then 4-5 steps) auto r = compositionTable[idx..idx+cnt].map!"a.rhs"().assumeSorted(); auto target = r.lowerBound(second).length; if(target == cnt) return dchar.init; auto entry = compositionTable[idx+target]; if(entry.rhs != second) return dchar.init; return entry.composed; } /++ Returns a full $(S_LINK Canonical decomposition, Canonical) (by default) or $(S_LINK Compatibility decomposition, Compatibility) decomposition of $(CHARACTER) $(D ch). If no decomposition is available returns a $(LREF Grapheme) with the $(D ch) itself. Note: This function also decomposes hangul syllables as prescribed by the standard. See also $(LREF decomposeHangul) for a restricted version that takes into account only hangul syllables but no other decompositions. Example: --- import std.algorithm; assert(decompose('Ĉ')[].equal("C\u0302")); assert(decompose('D')[].equal("D")); assert(decompose('\uD4DC')[].equal("\u1111\u1171\u11B7")); assert(decompose!Compatibility('¹').equal("1")); --- +/ public Grapheme decompose(UnicodeDecomposition decompType=Canonical)(dchar ch) { import std.internal.unicode_decomp; static if(decompType == Canonical) { alias table = decompCanonTable; alias mapping = canonMappingTrie; } else static if(decompType == Compatibility) { alias table = decompCompatTable; alias mapping = compatMappingTrie; } ushort idx = mapping[ch]; if(!idx) // not found, check hangul arithmetic decomposition return decomposeHangul(ch); auto decomp = table[idx..$].until(0); return Grapheme(decomp); } unittest { // verify examples assert(compose('A','\u0308') == '\u00C4'); assert(compose('A', 'B') == dchar.init); assert(compose('C', '\u0301') == '\u0106'); // note that the starter is the first one // thus the following doesn't compose assert(compose('\u0308', 'A') == dchar.init); import std.algorithm; assert(decompose('Ĉ')[].equalS("C\u0302")); assert(decompose('D')[].equalS("D")); assert(decompose('\uD4DC')[].equalS("\u1111\u1171\u11B7")); assert(decompose!Compatibility('¹')[].equalS("1")); } //---------------------------------------------------------------------------- // Hangul specific composition/decomposition enum jamoSBase = 0xAC00; enum jamoLBase = 0x1100; enum jamoVBase = 0x1161; enum jamoTBase = 0x11A7; enum jamoLCount = 19, jamoVCount = 21, jamoTCount = 28; enum jamoNCount = jamoVCount * jamoTCount; enum jamoSCount = jamoLCount * jamoNCount; // Tests if $(D ch) is a Hangul leading consonant jamo. bool isJamoL(dchar ch) { // first cmp rejects ~ 1M code points above leading jamo range return ch < jamoLBase+jamoLCount && ch >= jamoLBase; } // Tests if $(D ch) is a Hangul vowel jamo. bool isJamoT(dchar ch) { // first cmp rejects ~ 1M code points above trailing jamo range // Note: ch == jamoTBase doesn't indicate trailing jamo (TIndex must be > 0) return ch < jamoTBase+jamoTCount && ch > jamoTBase; } // Tests if $(D ch) is a Hangul trailnig consonant jamo. bool isJamoV(dchar ch) { // first cmp rejects ~ 1M code points above vowel range return ch < jamoVBase+jamoVCount && ch >= jamoVBase; } int hangulSyllableIndex(dchar ch) { int idxS = cast(int)ch - jamoSBase; return idxS >= 0 && idxS < jamoSCount ? idxS : -1; } // internal helper: compose hangul syllables leaving dchar.init in holes void hangulRecompose(dchar[] seq) { for(size_t idx = 0; idx + 1 < seq.length; ) { if(isJamoL(seq[idx]) && isJamoV(seq[idx+1])) { int indexL = seq[idx] - jamoLBase; int indexV = seq[idx+1] - jamoVBase; int indexLV = indexL * jamoNCount + indexV * jamoTCount; if(idx + 2 < seq.length && isJamoT(seq[idx+2])) { seq[idx] = jamoSBase + indexLV + seq[idx+2] - jamoTBase; seq[idx+1] = dchar.init; seq[idx+2] = dchar.init; idx += 3; } else { seq[idx] = jamoSBase + indexLV; seq[idx+1] = dchar.init; idx += 2; } } else idx++; } } //---------------------------------------------------------------------------- public: /** Decomposes a Hangul syllable. If $(D ch) is not a composed syllable then this function returns $(LREF Grapheme) containing only $(D ch) as is. Example: --- import std.algorithm; assert(decomposeHangul('\uD4DB')[].equal("\u1111\u1171\u11B6")); --- */ Grapheme decomposeHangul(dchar ch) { int idxS = cast(int)ch - jamoSBase; if(idxS < 0 || idxS >= jamoSCount) return Grapheme(ch); int idxL = idxS / jamoNCount; int idxV = (idxS % jamoNCount) / jamoTCount; int idxT = idxS % jamoTCount; int partL = jamoLBase + idxL; int partV = jamoVBase + idxV; if(idxT > 0) // there is a trailling consonant (T); <L,V,T> decomposition return Grapheme(partL, partV, jamoTBase + idxT); else // <L, V> decomposition return Grapheme(partL, partV); } /++ Try to compose hangul syllable out of a leading consonant ($(D lead)), a $(D vowel) and optional $(D trailing) consonant jamos. On success returns the composed LV or LVT hangul syllable. If any of $(D lead) and $(D vowel) are not a valid hangul jamo of the respective $(CHARACTER) class returns dchar.init. Example: --- assert(composeJamo('\u1111', '\u1171', '\u11B6') == '\uD4DB'); // leaving out T-vowel, or passing any codepoint // that is not trailing consonant composes an LV-syllable assert(composeJamo('\u1111', '\u1171') == '\uD4CC'); assert(composeJamo('\u1111', '\u1171', ' ') == '\uD4CC'); assert(composeJamo('\u1111', 'A') == dchar.init); assert(composeJamo('A', '\u1171') == dchar.init); --- +/ dchar composeJamo(dchar lead, dchar vowel, dchar trailing=dchar.init) { if(!isJamoL(lead)) return dchar.init; int indexL = lead - jamoLBase; if(!isJamoV(vowel)) return dchar.init; int indexV = vowel - jamoVBase; int indexLV = indexL * jamoNCount + indexV * jamoTCount; dchar syllable = jamoSBase + indexLV; return isJamoT(trailing) ? syllable + (trailing - jamoTBase) : syllable; } unittest { static void testDecomp(UnicodeDecomposition T)(dchar ch, string r) { Grapheme g = decompose!T(ch); assert(equalS(g[], r), text(g[], " vs ", r)); } testDecomp!Canonical('\u1FF4', "\u03C9\u0301\u0345"); testDecomp!Canonical('\uF907', "\u9F9C"); testDecomp!Compatibility('\u33FF', "\u0067\u0061\u006C"); testDecomp!Compatibility('\uA7F9', "\u0153"); // check examples assert(decomposeHangul('\uD4DB')[].equalS("\u1111\u1171\u11B6")); assert(composeJamo('\u1111', '\u1171', '\u11B6') == '\uD4DB'); assert(composeJamo('\u1111', '\u1171') == '\uD4CC'); // leave out T-vowel assert(composeJamo('\u1111', '\u1171', ' ') == '\uD4CC'); assert(composeJamo('\u1111', 'A') == dchar.init); assert(composeJamo('A', '\u1171') == dchar.init); } /** Enumeration type for normalization forms, passed as template parameter for functions like $(LREF normalize). */ enum NormalizationForm { NFC, NFD, NFKC, NFKD } enum { /** Shorthand aliases from values indicating normalization forms. */ NFC = NormalizationForm.NFC, ///ditto NFD = NormalizationForm.NFD, ///ditto NFKC = NormalizationForm.NFKC, ///ditto NFKD = NormalizationForm.NFKD }; /++ Returns $(D input) string normalized to the chosen form. Form C is used by default. For more information on normalization forms see the $(S_LINK Normalization, normalization section). Note: In cases where the string in question is already normalized, it is returned unmodified and no memory allocation happens. Example: --- // any encoding works wstring greet = "Hello world"; assert(normalize(greet) is greet); // the same exact slice // An example of a character with all 4 forms being different: // Greek upsilon with acute and hook symbol (code point 0x03D3) assert(normalize!NFC("ϓ") == "\u03D3"); assert(normalize!NFD("ϓ") == "\u03D2\u0301"); assert(normalize!NFKC("ϓ") == "\u038E"); assert(normalize!NFKD("ϓ") == "\u03A5\u0301"); --- +/ inout(C)[] normalize(NormalizationForm norm=NFC, C)(inout(C)[] input) { auto anchors = splitNormalized!norm(input); if(anchors[0] == input.length && anchors[1] == input.length) return input; dchar[] decomposed; decomposed.reserve(31); ubyte[] ccc; ccc.reserve(31); auto app = appender!(C[])(); do { app.put(input[0..anchors[0]]); foreach(dchar ch; input[anchors[0]..anchors[1]]) static if(norm == NFD || norm == NFC) { foreach(dchar c; decompose!Canonical(ch)[]) decomposed ~= c; } else // NFKD & NFKC { foreach(dchar c; decompose!Compatibility(ch)[]) decomposed ~= c; } ccc.length = decomposed.length; size_t firstNonStable = 0; ubyte lastClazz = 0; foreach(idx, dchar ch; decomposed) { auto clazz = combiningClass(ch); ccc[idx] = clazz; if(clazz == 0 && lastClazz != 0) { // found a stable code point after unstable ones sort!("a[0] < b[0]", SwapStrategy.stable) (zip(ccc[firstNonStable..idx], decomposed[firstNonStable..idx])); firstNonStable = decomposed.length; } else if(clazz != 0 && lastClazz == 0) { // found first unstable code point after stable ones firstNonStable = idx; } lastClazz = clazz; } sort!("a[0] < b[0]", SwapStrategy.stable) (zip(ccc[firstNonStable..$], decomposed[firstNonStable..$])); static if(norm == NFC || norm == NFKC) { size_t idx = 0; auto first = countUntil(ccc, 0); if(first >= 0) // no starters?? no recomposition { for(;;) { auto second = recompose(first, decomposed, ccc); if(second == decomposed.length) break; first = second; } // 2nd pass for hangul syllables hangulRecompose(decomposed); } } static if(norm == NFD || norm == NFKD) app.put(decomposed); else { auto clean = remove!("a == dchar.init", SwapStrategy.stable)(decomposed); app.put(decomposed[0 .. clean.length]); } // reset variables decomposed.length = 0; decomposed.assumeSafeAppend(); ccc.length = 0; ccc.assumeSafeAppend(); input = input[anchors[1]..$]; // and move on anchors = splitNormalized!norm(input); }while(anchors[0] != input.length); app.put(input[0..anchors[0]]); return cast(inout(C)[])app.data; } unittest { assert(normalize!NFD("abc\uF904def") == "abc\u6ED1def", text(normalize!NFD("abc\uF904def"))); assert(normalize!NFKD("2¹⁰") == "210", normalize!NFKD("2¹⁰")); assert(normalize!NFD("Äffin") == "A\u0308ffin"); // check example // any encoding works wstring greet = "Hello world"; assert(normalize(greet) is greet); // the same exact slice // An example of a character with all 4 forms being different: // Greek upsilon with acute and hook symbol (code point 0x03D3) assert(normalize!NFC("ϓ") == "\u03D3"); assert(normalize!NFD("ϓ") == "\u03D2\u0301"); assert(normalize!NFKC("ϓ") == "\u038E"); assert(normalize!NFKD("ϓ") == "\u03A5\u0301"); } // canonically recompose given slice of code points, works in-place and mutates data private size_t recompose(size_t start, dchar[] input, ubyte[] ccc) { assert(input.length == ccc.length); int accumCC = -1;// so that it's out of 0..255 range bool foundSolidStarter = false; // writefln("recomposing %( %04x %)", input); // first one is always a starter thus we start at i == 1 size_t i = start+1; for(; ; ) { if(i == input.length) break; int curCC = ccc[i]; // In any character sequence beginning with a starter S // a character C is blocked from S if and only if there // is some character B between S and C, and either B // is a starter or it has the same or higher combining class as C. //------------------------ // Applying to our case: // S is input[0] // accumCC is the maximum CCC of characters between C and S, // as ccc are sorted // C is input[i] if(curCC > accumCC) { dchar comp = compose(input[start], input[i]); if(comp != dchar.init) { input[start] = comp; input[i] = dchar.init;// put a sentinel // current was merged so its CCC shouldn't affect // composing with the next one } else { // if it was a starter then accumCC is now 0, end of loop accumCC = curCC; if(accumCC == 0) break; } } else{ // ditto here accumCC = curCC; if(accumCC == 0) break; } i++; } return i; } // returns tuple of 2 indexes that delimit: // normalized text, piece that needs normalization and // the rest of input starting with stable code point private auto splitNormalized(NormalizationForm norm, C)(const(C)[] input) { auto result = input; ubyte lastCC = 0; foreach(idx, dchar ch; input) { static if(norm == NFC) if(ch < 0x0300) { lastCC = 0; continue; } ubyte CC = combiningClass(ch); if(lastCC > CC && CC != 0) { return seekStable!norm(idx, input); } if(notAllowedIn!norm(ch)) { return seekStable!norm(idx, input); } lastCC = CC; } return tuple(input.length, input.length); } private auto seekStable(NormalizationForm norm, C)(size_t idx, in C[] input) { import std.utf : codeLength; auto br = input[0..idx]; size_t region_start = 0;// default for(;;) { if(br.empty)// start is 0 break; dchar ch = br.back; if(combiningClass(ch) == 0 && allowedIn!norm(ch)) { region_start = br.length - std.utf.codeLength!C(ch); break; } br.popFront(); } ///@@@BUG@@@ can't use find: " find is a nested function and can't be used..." size_t region_end=input.length;// end is $ by default foreach(i, dchar ch; input[idx..$]) { if(combiningClass(ch) == 0 && allowedIn!norm(ch)) { region_end = i+idx; break; } } // writeln("Region to normalize: ", input[region_start..region_end]); return tuple(region_start, region_end); } /** Tests if dchar $(D ch) is always allowed (Quick_Check=YES) in normalization form $(D norm). --- // e.g. Cyrillic is always allowed, so is ASCII assert(allowedIn!NFC('я')); assert(allowedIn!NFD('я')); assert(allowedIn!NFKC('я')); assert(allowedIn!NFKD('я')); assert(allowedIn!NFC('Z')); --- */ public bool allowedIn(NormalizationForm norm)(dchar ch) { return !notAllowedIn!norm(ch); } // not user friendly name but more direct private bool notAllowedIn(NormalizationForm norm)(dchar ch) { static if(norm == NFC) alias qcTrie = nfcQCTrie; else static if(norm == NFD) alias qcTrie = nfdQCTrie; else static if(norm == NFKC) alias qcTrie = nfkcQCTrie; else static if(norm == NFKD) alias qcTrie = nfkdQCTrie; else static assert("Unknown normalization form "~norm); return qcTrie[ch]; } unittest { assert(allowedIn!NFC('я')); assert(allowedIn!NFD('я')); assert(allowedIn!NFKC('я')); assert(allowedIn!NFKD('я')); assert(allowedIn!NFC('Z')); } } version(std_uni_bootstrap) { // old version used for bootstrapping of gen_uni.d that generates // up to date optimal versions of all of isXXX functions @safe pure nothrow public bool isWhite(dchar c) { return std.ascii.isWhite(c) || c == lineSep || c == paraSep || c == '\u0085' || c == '\u00A0' || c == '\u1680' || c == '\u180E' || (c >= '\u2000' && c <= '\u200A') || c == '\u202F' || c == '\u205F' || c == '\u3000'; } } else { // trusted -> avoid bounds check @trusted pure nothrow ushort toLowerIndex(dchar c) { alias trie = toLowerIndexTrie; return trie[c]; } // trusted -> avoid bounds check @trusted pure nothrow dchar toLowerTab(size_t idx) { return toLowerTable[idx]; } // trusted -> avoid bounds check @trusted pure nothrow ushort toTitleIndex(dchar c) { alias trie = toTitleIndexTrie; return trie[c]; } // trusted -> avoid bounds check @trusted pure nothrow dchar toTitleTab(size_t idx) { return toTitleTable[idx]; } // trusted -> avoid bounds check @trusted pure nothrow ushort toUpperIndex(dchar c) { alias trie = toUpperIndexTrie; return trie[c]; } // trusted -> avoid bounds check @trusted pure nothrow dchar toUpperTab(size_t idx) { return toUpperTable[idx]; } public: /++ Whether or not $(D c) is a Unicode whitespace $(CHARACTER). (general Unicode category: Part of C0(tab, vertical tab, form feed, carriage return, and linefeed characters), Zs, Zl, Zp, and NEL(U+0085)) +/ @safe pure nothrow public bool isWhite(dchar c) { return isWhiteGen(c); // call pregenerated binary search } /++ Return whether $(D c) is a Unicode lowercase $(CHARACTER). +/ @safe pure nothrow bool isLower(dchar c) { if(std.ascii.isASCII(c)) return std.ascii.isLower(c); return lowerCaseTrie[c]; } @safe unittest { foreach(v; 0..0x80) assert(std.ascii.isLower(v) == isLower(v)); assert(isLower('я')); assert(isLower('й')); assert(!isLower('Ж')); // Greek HETA assert(!isLower('\u0370')); assert(isLower('\u0371')); assert(!isLower('\u039C')); // capital MU assert(isLower('\u03B2')); // beta // from extended Greek assert(!isLower('\u1F18')); assert(isLower('\u1F00')); foreach(v; unicode.lowerCase.byCodepoint) assert(isLower(v) && !isUpper(v)); } /++ Return whether $(D c) is a Unicode uppercase $(CHARACTER). +/ @safe pure nothrow bool isUpper(dchar c) { if(std.ascii.isASCII(c)) return std.ascii.isUpper(c); return upperCaseTrie[c]; } @safe unittest { foreach(v; 0..0x80) assert(std.ascii.isLower(v) == isLower(v)); assert(!isUpper('й')); assert(isUpper('Ж')); // Greek HETA assert(isUpper('\u0370')); assert(!isUpper('\u0371')); assert(isUpper('\u039C')); // capital MU assert(!isUpper('\u03B2')); // beta // from extended Greek assert(!isUpper('\u1F00')); assert(isUpper('\u1F18')); foreach(v; unicode.upperCase.byCodepoint) assert(isUpper(v) && !isLower(v)); } /++ If $(D c) is a Unicode uppercase $(CHARACTER), then its lowercase equivalent is returned. Otherwise $(D c) is returned. Warning: certain alphabets like German and Greek have no 1:1 upper-lower mapping. Use overload of toLower which takes full string instead. +/ @safe pure nothrow dchar toLower(dchar c) { // optimize ASCII case if(c < 0xAA) { if(c < 'A') return c; if(c <= 'Z') return c + 32; return c; } size_t idx = toLowerIndex(c); if(idx < MAX_SIMPLE_LOWER) { return toLowerTab(idx); } return c; } //TODO: Hidden for now, needs better API. //Other transforms could use better API as well, but this one is a new primitive. @safe pure nothrow private dchar toTitlecase(dchar c) { // optimize ASCII case if(c < 0xAA) { if(c < 'a') return c; if(c <= 'z') return c - 32; return c; } size_t idx = toTitleIndex(c); if(idx < MAX_SIMPLE_TITLE) { return toTitleTab(idx); } return c; } private alias UpperTriple = TypeTuple!(toUpperIndex, MAX_SIMPLE_UPPER, toUpperTab); private alias LowerTriple = TypeTuple!(toLowerIndex, MAX_SIMPLE_LOWER, toLowerTab); // generic toUpper/toLower on whole string, creates new or returns as is private S toCase(alias indexFn, uint maxIdx, alias tableFn, S)(S s) @trusted pure if(isSomeString!S) { foreach(i, dchar cOuter; s) { ushort idx = indexFn(cOuter); if(idx == ushort.max) continue; auto result = s[0 .. i].dup; foreach(dchar c; s[i .. $]) { idx = indexFn(c); if(idx == ushort.max) result ~= c; else if(idx < maxIdx) { c = tableFn(idx); result ~= c; } else { auto val = tableFn(idx); // unpack length + codepoint uint len = val>>24; result ~= cast(dchar)(val & 0xFF_FFFF); foreach(j; idx+1..idx+len) result ~= tableFn(j); } } return cast(S) result; } return s; } // TODO: helper, I wish std.utf was more flexible (and stright) private size_t encodeTo(char[] buf, size_t idx, dchar c) @trusted pure { if (c <= 0x7F) { buf[idx] = cast(char)c; idx++; } else if (c <= 0x7FF) { buf[idx] = cast(char)(0xC0 | (c >> 6)); buf[idx+1] = cast(char)(0x80 | (c & 0x3F)); idx += 2; } else if (c <= 0xFFFF) { buf[idx] = cast(char)(0xE0 | (c >> 12)); buf[idx+1] = cast(char)(0x80 | ((c >> 6) & 0x3F)); buf[idx+2] = cast(char)(0x80 | (c & 0x3F)); idx += 3; } else if (c <= 0x10FFFF) { buf[idx] = cast(char)(0xF0 | (c >> 18)); buf[idx+1] = cast(char)(0x80 | ((c >> 12) & 0x3F)); buf[idx+2] = cast(char)(0x80 | ((c >> 6) & 0x3F)); buf[idx+3] = cast(char)(0x80 | (c & 0x3F)); idx += 4; } else assert(0); return idx; } unittest { char[] s = "abcd".dup; size_t i = 0; i = encodeTo(s, i, 'X'); assert(s == "Xbcd"); i = encodeTo(s, i, cast(dchar)'\u00A9'); assert(s == "X\xC2\xA9d"); } // TODO: helper, I wish std.utf was more flexible (and stright) private size_t encodeTo(wchar[] buf, size_t idx, dchar c) @trusted pure { import std.utf; if (c <= 0xFFFF) { if (0xD800 <= c && c <= 0xDFFF) throw (new UTFException("Encoding an isolated surrogate code point in UTF-16")).setSequence(c); buf[idx] = cast(wchar)c; idx++; } else if (c <= 0x10FFFF) { buf[idx] = cast(wchar)((((c - 0x10000) >> 10) & 0x3FF) + 0xD800); buf[idx+1] = cast(wchar)(((c - 0x10000) & 0x3FF) + 0xDC00); idx += 2; } else assert(0); return idx; } private size_t encodeTo(dchar[] buf, size_t idx, dchar c) @trusted pure { buf[idx] = c; idx++; return idx; } private void toCaseInPlace(alias indexFn, uint maxIdx, alias tableFn, C)(ref C[] s) @trusted pure if (is(C == char) || is(C == wchar) || is(C == dchar)) { import std.utf; size_t curIdx = 0; size_t destIdx = 0; alias slowToCase = toCaseInPlaceAlloc!(indexFn, maxIdx, tableFn); size_t lastUnchanged = 0; // in-buffer move of bytes to a new start index // the trick is that it may not need to copy at all static size_t moveTo(C[] str, size_t dest, size_t from, size_t to) { // Interestingly we may just bump pointer for a while // then have to copy if a re-cased char was smaller the original // later we may regain pace with char that got bigger // In the end it sometimes flip-flops between the 2 cases below if(dest == from) return to; // got to copy foreach(C c; str[from..to]) str[dest++] = c; return dest; } while(curIdx != s.length) { size_t startIdx = curIdx; dchar ch = decode(s, curIdx); // TODO: special case for ASCII auto caseIndex = indexFn(ch); if(caseIndex == ushort.max) // unchanged, skip over { continue; } else if(caseIndex < maxIdx) // 1:1 codepoint mapping { // previous cased chars had the same length as uncased ones // thus can just adjust pointer destIdx = moveTo(s, destIdx, lastUnchanged, startIdx); lastUnchanged = curIdx; dchar cased = tableFn(caseIndex); auto casedLen = codeLength!C(cased); if(casedLen + destIdx > curIdx) // no place to fit cased char { // switch to slow codepath, where we allocate return slowToCase(s, startIdx, destIdx); } else { destIdx = encodeTo(s, destIdx, cased); } } else // 1:m codepoint mapping, slow codepath { destIdx = moveTo(s, destIdx, lastUnchanged, startIdx); lastUnchanged = curIdx; return slowToCase(s, startIdx, destIdx); } assert(destIdx <= curIdx); } if(lastUnchanged != s.length) { destIdx = moveTo(s, destIdx, lastUnchanged, s.length); } s = s[0..destIdx]; } // helper to precalculate size of case-converted string private template toCaseLength(alias indexFn, uint maxIdx, alias tableFn) { size_t toCaseLength(C)(in C[] str) { import std.utf; size_t codeLen = 0; size_t lastNonTrivial = 0; size_t curIdx = 0; while(curIdx != str.length) { size_t startIdx = curIdx; dchar ch = decode(str, curIdx); ushort caseIndex = indexFn(ch); if(caseIndex == ushort.max) continue; else if(caseIndex < maxIdx) { codeLen += startIdx - lastNonTrivial; lastNonTrivial = curIdx; dchar cased = tableFn(caseIndex); codeLen += codeLength!C(cased); } else { codeLen += startIdx - lastNonTrivial; lastNonTrivial = curIdx; auto val = tableFn(caseIndex); auto len = val>>24; dchar cased = val & 0xFF_FFFF; codeLen += codeLength!C(cased); foreach(j; caseIndex+1..caseIndex+len) codeLen += codeLength!C(tableFn(j)); } } if(lastNonTrivial != str.length) codeLen += str.length - lastNonTrivial; return codeLen; } } unittest { import std.conv; alias toLowerLength = toCaseLength!(LowerTriple); assert(toLowerLength("abcd") == 4); assert(toLowerLength("аБВгд456") == 10+3); } // slower code path that preallocates and then copies // case-converted stuf to the new string private template toCaseInPlaceAlloc(alias indexFn, uint maxIdx, alias tableFn) { void toCaseInPlaceAlloc(C)(ref C[] s, size_t curIdx, size_t destIdx) @trusted pure if (is(C == char) || is(C == wchar) || is(C == dchar)) { import std.utf : decode; alias caseLength = toCaseLength!(indexFn, maxIdx, tableFn); auto trueLength = destIdx + caseLength(s[curIdx..$]); C[] ns = new C[trueLength]; ns[0..destIdx] = s[0..destIdx]; size_t lastUnchanged = curIdx; while(curIdx != s.length) { size_t startIdx = curIdx; // start of current codepoint dchar ch = decode(s, curIdx); auto caseIndex = indexFn(ch); if(caseIndex == ushort.max) // skip over { continue; } else if(caseIndex < maxIdx) // 1:1 codepoint mapping { dchar cased = tableFn(caseIndex); auto toCopy = startIdx - lastUnchanged; ns[destIdx .. destIdx+toCopy] = s[lastUnchanged .. startIdx]; lastUnchanged = curIdx; destIdx += toCopy; destIdx = encodeTo(ns, destIdx, cased); } else // 1:m codepoint mapping, slow codepath { auto toCopy = startIdx - lastUnchanged; ns[destIdx .. destIdx+toCopy] = s[lastUnchanged .. startIdx]; lastUnchanged = curIdx; destIdx += toCopy; auto val = tableFn(caseIndex); // unpack length + codepoint uint len = val>>24; destIdx = encodeTo(ns, destIdx, cast(dchar)(val & 0xFF_FFFF)); foreach(j; caseIndex+1..caseIndex+len) destIdx = encodeTo(ns, destIdx, tableFn(j)); } } if(lastUnchanged != s.length) { auto toCopy = s.length - lastUnchanged; ns[destIdx..destIdx+toCopy] = s[lastUnchanged..$]; destIdx += toCopy; } assert(ns.length == destIdx); s = ns; } } /++ Converts $(D s) to lowercase (by performing Unicode lowercase mapping) in place. For a few characters string length may increase after the transformation, in such a case the function reallocates exactly once. If $(D s) does not have any uppercase characters, then $(D s) is unaltered. +/ void toLowerInPlace(C)(ref C[] s) @trusted pure if (is(C == char) || is(C == wchar) || is(C == dchar)) { toCaseInPlace!(LowerTriple)(s); } // overloads for the most common cases to reduce compile time @safe pure /*TODO nothrow*/ { void toLowerInPlace(ref char[] s) { toLowerInPlace!char(s); } void toLowerInPlace(ref wchar[] s) { toLowerInPlace!wchar(s); } void toLowerInPlace(ref dchar[] s) { toLowerInPlace!dchar(s); } } /++ Converts $(D s) to uppercase (by performing Unicode uppercase mapping) in place. For a few characters string length may increase after the transformation, in such a case the function reallocates exactly once. If $(D s) does not have any lowercase characters, then $(D s) is unaltered. +/ void toUpperInPlace(C)(ref C[] s) @trusted pure if (is(C == char) || is(C == wchar) || is(C == dchar)) { toCaseInPlace!(UpperTriple)(s); } // overloads for the most common cases to reduce compile time/code size @safe pure /*TODO nothrow*/ { void toUpperInPlace(ref char[] s) { toUpperInPlace!char(s); } void toUpperInPlace(ref wchar[] s) { toUpperInPlace!wchar(s); } void toUpperInPlace(ref dchar[] s) { toUpperInPlace!dchar(s); } } /++ Returns a string which is identical to $(D s) except that all of its characters are converted to lowercase (by preforming Unicode lowercase mapping). If none of $(D s) characters were affected, then $(D s) itself is returned. +/ S toLower(S)(S s) @trusted pure if(isSomeString!S) { return toCase!(LowerTriple)(s); } // overloads for the most common cases to reduce compile time @safe pure /*TODO nothrow*/ { string toLower(string s) { return toLower!string(s); } wstring toLower(wstring s) { return toLower!wstring(s); } dstring toLower(dstring s) { return toLower!dstring(s); } } @trusted unittest //@@@BUG std.format is not @safe { import std.string : format; foreach(ch; 0..0x80) assert(std.ascii.toLower(ch) == toLower(ch)); assert(toLower('Я') == 'я'); assert(toLower('Δ') == 'δ'); foreach(ch; unicode.upperCase.byCodepoint) { dchar low = ch.toLower(); assert(low == ch || isLower(low), format("%s -> %s", ch, low)); } assert(toLower("АЯ") == "ая"); assert("\u1E9E".toLower == "\u00df"); assert("\u00df".toUpper == "SS"); } //bugzilla 9629 unittest { wchar[] test = "hello þ world"w.dup; auto piece = test[6..7]; toUpperInPlace(piece); assert(test == "hello Þ world"); } unittest { string s1 = "FoL"; string s2 = toLower(s1); assert(cmp(s2, "fol") == 0, s2); assert(s2 != s1); char[] s3 = s1.dup; toLowerInPlace(s3); assert(s3 == s2); s1 = "A\u0100B\u0101d"; s2 = toLower(s1); s3 = s1.dup; assert(cmp(s2, "a\u0101b\u0101d") == 0); assert(s2 !is s1); toLowerInPlace(s3); assert(s3 == s2); s1 = "A\u0460B\u0461d"; s2 = toLower(s1); s3 = s1.dup; assert(cmp(s2, "a\u0461b\u0461d") == 0); assert(s2 !is s1); toLowerInPlace(s3); assert(s3 == s2); s1 = "\u0130"; s2 = toLower(s1); s3 = s1.dup; assert(s2 == "i\u0307"); assert(s2 !is s1); toLowerInPlace(s3); assert(s3 == s2); // Test on wchar and dchar strings. assert(toLower("Some String"w) == "some string"w); assert(toLower("Some String"d) == "some string"d); } /++ If $(D c) is a Unicode lowercase $(CHARACTER), then its uppercase equivalent is returned. Otherwise $(D c) is returned. Warning: Certain alphabets like German and Greek have no 1:1 upper-lower mapping. Use overload of toUpper which takes full string instead. +/ @safe pure nothrow dchar toUpper(dchar c) { // optimize ASCII case if(c < 0xAA) { if(c < 'a') return c; if(c <= 'z') return c - 32; return c; } size_t idx = toUpperIndex(c); if(idx < MAX_SIMPLE_UPPER) { return toUpperTab(idx); } return c; } @trusted unittest { import std.string : format; foreach(ch; 0..0x80) assert(std.ascii.toUpper(ch) == toUpper(ch)); assert(toUpper('я') == 'Я'); assert(toUpper('δ') == 'Δ'); foreach(ch; unicode.lowerCase.byCodepoint) { dchar up = ch.toUpper(); assert(up == ch || isUpper(up), format("%s -> %s", ch, up)); } } /++ Returns a string which is identical to $(D s) except that all of its characters are converted to uppercase (by preforming Unicode uppercase mapping). If none of $(D s) characters were affected, then $(D s) itself is returned. +/ S toUpper(S)(S s) @trusted pure if(isSomeString!S) { return toCase!(UpperTriple)(s); } // overloads for the most common cases to reduce compile time @safe pure /*TODO nothrow*/ { string toUpper(string s) { return toUpper!string(s); } wstring toUpper(wstring s) { return toUpper!wstring(s); } dstring toUpper(dstring s) { return toUpper!dstring(s); } } unittest { string s1 = "FoL"; string s2; char[] s3; s2 = toUpper(s1); s3 = s1.dup; toUpperInPlace(s3); assert(s3 == s2, s3); assert(cmp(s2, "FOL") == 0); assert(s2 !is s1); s1 = "a\u0100B\u0101d"; s2 = toUpper(s1); s3 = s1.dup; toUpperInPlace(s3); assert(s3 == s2); assert(cmp(s2, "A\u0100B\u0100D") == 0); assert(s2 !is s1); s1 = "a\u0460B\u0461d"; s2 = toUpper(s1); s3 = s1.dup; toUpperInPlace(s3); assert(s3 == s2); assert(cmp(s2, "A\u0460B\u0460D") == 0); assert(s2 !is s1); } unittest { static void doTest(C)(const(C)[] s, const(C)[] trueUp, const(C)[] trueLow) { import std.string : format; string diff = "src: %( %x %)\nres: %( %x %)\ntru: %( %x %)"; auto low = s.toLower() , up = s.toUpper(); auto lowInp = s.dup, upInp = s.dup; lowInp.toLowerInPlace(); upInp.toUpperInPlace(); assert(low == trueLow, format(diff, low, trueLow)); assert(up == trueUp, format(diff, up, trueUp)); assert(lowInp == trueLow, format(diff, cast(ubyte[])s, cast(ubyte[])lowInp, cast(ubyte[])trueLow)); assert(upInp == trueUp, format(diff, cast(ubyte[])s, cast(ubyte[])upInp, cast(ubyte[])trueUp)); } foreach(S; TypeTuple!(dstring, wstring, string)) { S easy = "123"; S good = "abCФеж"; S awful = "\u0131\u023f\u2126"; S wicked = "\u0130\u1FE2"; auto options = [easy, good, awful, wicked]; S[] lower = ["123", "abcфеж", "\u0131\u023f\u03c9", "i\u0307\u1Fe2"]; S[] upper = ["123", "ABCФЕЖ", "I\u2c7e\u2126", "\u0130\u03A5\u0308\u0300"]; foreach(val; TypeTuple!(easy, good)) { auto e = val.dup; auto g = e; e.toUpperInPlace(); assert(e is g); e.toLowerInPlace(); assert(e is g); } foreach(i, v; options) { doTest(v, upper[i], lower[i]); } // a few combinatorial runs foreach(i; 0..options.length) foreach(j; i..options.length) foreach(k; j..options.length) { auto sample = options[i] ~ options[j] ~ options[k]; auto sample2 = options[k] ~ options[j] ~ options[i]; doTest(sample, upper[i] ~ upper[j] ~ upper[k], lower[i] ~ lower[j] ~ lower[k]); doTest(sample2, upper[k] ~ upper[j] ~ upper[i], lower[k] ~ lower[j] ~ lower[i]); } } } /++ Returns whether $(D c) is a Unicode alphabetic $(CHARACTER) (general Unicode category: Alphabetic). +/ @safe pure nothrow bool isAlpha(dchar c) { // optimization if(c < 0xAA) { size_t x = c - 'A'; if(x <= 'Z' - 'A') return true; else { x = c - 'a'; if(x <= 'z'-'a') return true; } return false; } return alphaTrie[c]; } @safe unittest { auto alpha = unicode("Alphabetic"); foreach(ch; alpha.byCodepoint) assert(isAlpha(ch)); foreach(ch; 0..0x4000) assert((ch in alpha) == isAlpha(ch)); } /++ Returns whether $(D c) is a Unicode mark (general Unicode category: Mn, Me, Mc). +/ @safe pure nothrow bool isMark(dchar c) { return markTrie[c]; } @safe unittest { auto mark = unicode("Mark"); foreach(ch; mark.byCodepoint) assert(isMark(ch)); foreach(ch; 0..0x4000) assert((ch in mark) == isMark(ch)); } /++ Returns whether $(D c) is a Unicode numerical $(CHARACTER) (general Unicode category: Nd, Nl, No). +/ @safe pure nothrow bool isNumber(dchar c) { return numberTrie[c]; } @safe unittest { auto n = unicode("N"); foreach(ch; n.byCodepoint) assert(isNumber(ch)); foreach(ch; 0..0x4000) assert((ch in n) == isNumber(ch)); } /++ Returns whether $(D c) is a Unicode punctuation $(CHARACTER) (general Unicode category: Pd, Ps, Pe, Pc, Po, Pi, Pf). +/ @safe pure nothrow bool isPunctuation(dchar c) { return punctuationTrie[c]; } unittest { assert(isPunctuation('\u0021')); assert(isPunctuation('\u0028')); assert(isPunctuation('\u0029')); assert(isPunctuation('\u002D')); assert(isPunctuation('\u005F')); assert(isPunctuation('\u00AB')); assert(isPunctuation('\u00BB')); foreach(ch; unicode("P").byCodepoint) assert(isPunctuation(ch)); } /++ Returns whether $(D c) is a Unicode symbol $(CHARACTER) (general Unicode category: Sm, Sc, Sk, So). +/ @safe pure nothrow bool isSymbol(dchar c) { return symbolTrie[c]; } unittest { import std.string; assert(isSymbol('\u0024')); assert(isSymbol('\u002B')); assert(isSymbol('\u005E')); assert(isSymbol('\u00A6')); foreach(ch; unicode("S").byCodepoint) assert(isSymbol(ch), format("%04x", ch)); } /++ Returns whether $(D c) is a Unicode space $(CHARACTER) (general Unicode category: Zs) Note: This doesn't include '\n', '\r', \t' and other non-space $(CHARACTER). For commonly used less strict semantics see $(LREF isWhite). +/ @safe pure nothrow bool isSpace(dchar c) { return isSpaceGen(c); } unittest { assert(isSpace('\u0020')); auto space = unicode.Zs; foreach(ch; space.byCodepoint) assert(isSpace(ch)); foreach(ch; 0..0x1000) assert(isSpace(ch) == space[ch]); } /++ Returns whether $(D c) is a Unicode graphical $(CHARACTER) (general Unicode category: L, M, N, P, S, Zs). +/ @safe pure nothrow bool isGraphical(dchar c) { return graphicalTrie[c]; } unittest { auto set = unicode("Graphical"); import std.string; foreach(ch; set.byCodepoint) assert(isGraphical(ch), format("%4x", ch)); foreach(ch; 0..0x4000) assert((ch in set) == isGraphical(ch)); } /++ Returns whether $(D c) is a Unicode control $(CHARACTER) (general Unicode category: Cc). +/ @safe pure nothrow bool isControl(dchar c) { return isControlGen(c); } unittest { assert(isControl('\u0000')); assert(isControl('\u0081')); assert(!isControl('\u0100')); auto cc = unicode.Cc; foreach(ch; cc.byCodepoint) assert(isControl(ch)); foreach(ch; 0..0x1000) assert(isControl(ch) == cc[ch]); } /++ Returns whether $(D c) is a Unicode formatting $(CHARACTER) (general Unicode category: Cf). +/ @safe pure nothrow bool isFormat(dchar c) { return isFormatGen(c); } unittest { assert(isFormat('\u00AD')); foreach(ch; unicode("Format").byCodepoint) assert(isFormat(ch)); } // code points for private use, surrogates are not likely to change in near feature // if need be they can be generated from unicode data as well /++ Returns whether $(D c) is a Unicode Private Use $(CODEPOINT) (general Unicode category: Co). +/ @safe pure nothrow bool isPrivateUse(dchar c) { return (0x00_E000 <= c && c <= 0x00_F8FF) || (0x0F_0000 <= c && c <= 0x0F_FFFD) || (0x10_0000 <= c && c <= 0x10_FFFD); } /++ Returns whether $(D c) is a Unicode surrogate $(CODEPOINT) (general Unicode category: Cs). +/ @safe pure nothrow bool isSurrogate(dchar c) { return (0xD800 <= c && c <= 0xDFFF); } /++ Returns whether $(D c) is a Unicode high surrogate (lead surrogate). +/ @safe pure nothrow bool isSurrogateHi(dchar c) { return (0xD800 <= c && c <= 0xDBFF); } /++ Returns whether $(D c) is a Unicode low surrogate (trail surrogate). +/ @safe pure nothrow bool isSurrogateLo(dchar c) { return (0xDC00 <= c && c <= 0xDFFF); } /++ Returns whether $(D c) is a Unicode non-character i.e. a $(CODEPOINT) with no assigned abstract character. (general Unicode category: Cn) +/ @safe pure nothrow bool isNonCharacter(dchar c) { return nonCharacterTrie[c]; } unittest { auto set = unicode("Cn"); foreach(ch; set.byCodepoint) assert(isNonCharacter(ch)); } private: // load static data from pre-generated tables into usable datastructures @safe auto asSet(const (ubyte)[] compressed) { return CodepointSet(decompressIntervals(compressed)); } @safe pure nothrow auto asTrie(T...)(in TrieEntry!T e) { return const(CodepointTrie!T)(e.offsets, e.sizes, e.data); } @safe pure nothrow @property { // It's important to use auto return here, so that the compiler // only runs semantic on the return type if the function gets // used. Also these are functions rather than templates to not // increase the object size of the caller. auto lowerCaseTrie() { static immutable res = asTrie(lowerCaseTrieEntries); return res; } auto upperCaseTrie() { static immutable res = asTrie(upperCaseTrieEntries); return res; } auto simpleCaseTrie() { static immutable res = asTrie(simpleCaseTrieEntries); return res; } auto fullCaseTrie() { static immutable res = asTrie(fullCaseTrieEntries); return res; } auto alphaTrie() { static immutable res = asTrie(alphaTrieEntries); return res; } auto markTrie() { static immutable res = asTrie(markTrieEntries); return res; } auto numberTrie() { static immutable res = asTrie(numberTrieEntries); return res; } auto punctuationTrie() { static immutable res = asTrie(punctuationTrieEntries); return res; } auto symbolTrie() { static immutable res = asTrie(symbolTrieEntries); return res; } auto graphicalTrie() { static immutable res = asTrie(graphicalTrieEntries); return res; } auto nonCharacterTrie() { static immutable res = asTrie(nonCharacterTrieEntries); return res; } //normalization quick-check tables auto nfcQCTrie() { import std.internal.unicode_norm; static immutable res = asTrie(nfcQCTrieEntries); return res; } auto nfdQCTrie() { import std.internal.unicode_norm; static immutable res = asTrie(nfdQCTrieEntries); return res; } auto nfkcQCTrie() { import std.internal.unicode_norm; static immutable res = asTrie(nfkcQCTrieEntries); return res; } auto nfkdQCTrie() { import std.internal.unicode_norm; static immutable res = asTrie(nfkdQCTrieEntries); return res; } //grapheme breaking algorithm tables auto mcTrie() { import std.internal.unicode_grapheme; static immutable res = asTrie(mcTrieEntries); return res; } auto graphemeExtendTrie() { import std.internal.unicode_grapheme; static immutable res = asTrie(graphemeExtendTrieEntries); return res; } auto hangLV() { import std.internal.unicode_grapheme; static immutable res = asTrie(hangulLVTrieEntries); return res; } auto hangLVT() { import std.internal.unicode_grapheme; static immutable res = asTrie(hangulLVTTrieEntries); return res; } // tables below are used for composition/decomposition auto combiningClassTrie() { import std.internal.unicode_comp; static immutable res = asTrie(combiningClassTrieEntries); return res; } auto compatMappingTrie() { import std.internal.unicode_decomp; static immutable res = asTrie(compatMappingTrieEntries); return res; } auto canonMappingTrie() { import std.internal.unicode_decomp; static immutable res = asTrie(canonMappingTrieEntries); return res; } auto compositionJumpTrie() { import std.internal.unicode_comp; static immutable res = asTrie(compositionJumpTrieEntries); return res; } //case conversion tables auto toUpperIndexTrie() { static immutable res = asTrie(toUpperIndexTrieEntries); return res; } auto toLowerIndexTrie() { static immutable res = asTrie(toLowerIndexTrieEntries); return res; } auto toTitleIndexTrie() { static immutable res = asTrie(toTitleIndexTrieEntries); return res; } } }// version(!std_uni_bootstrap)
D
/Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Intermediates.noindex/StreamsApp.build/Debug-iphonesimulator/StreamsApp.build/Objects-normal/x86_64/AppDelegate.o : /Users/mac/Documents/StreamsApp/StreamsApp/AppDelegate.swift /Users/mac/Documents/StreamsApp/StreamsApp/StreamViewController/PostTableViewCell/PostTableViewCell.swift /Users/mac/Documents/StreamsApp/StreamsApp/StreamViewController/StreamViewController.swift /Users/mac/Documents/StreamsApp/StreamsApp/StreamViewController/NewPostViewController/NewPostViewController.swift /Users/mac/Documents/StreamsApp/StreamsApp/StreamViewController/UserHeaderView/UserHeaderView.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/DateToolsSwift/DateToolsSwift.framework/Modules/DateToolsSwift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreLocation.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/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/MBProgressHUD/MBProgressHUD.framework/Headers/MBProgressHUD.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFACL.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/MBProgressHUD/MBProgressHUD.framework/Headers/MBProgressHUD-umbrella.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/Parse-umbrella.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/Bolts-umbrella.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/DateToolsSwift/DateToolsSwift.framework/Headers/DateToolsSwift-umbrella.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFGeneric.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFCloud+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFFile+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPush+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFUser+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFAnonymousUtils+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFObject+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFQuery+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFTextField.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFCloud.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFCancellationTokenSource.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFTaskCompletionSource.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFFile.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFRole.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPurchase.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/Parse.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFUserAuthenticationDelegate.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFLogInView_Private.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFConfig.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFSubclassing.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPush.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFTask.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFTableViewCell.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPurchaseTableViewCell.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFCollectionViewCell.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFCancellationToken.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPolygon.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFSession.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFRelation.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFInstallation.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFCancellationTokenRegistration.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/ParseClientConfiguration.h /Users/mac/Documents/StreamsApp/StreamsApp-Bridging-Header.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFDecoder.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFEncoder.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFNetworkActivityIndicatorManager.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFFileUploadController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFProductTableViewController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFQueryTableViewController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFLogInViewController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFQueryCollectionViewController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFSignUpViewController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFUser.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFExecutor.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFAnalytics.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFAnonymousUtils.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFObject+Subclass.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/Bolts.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFConstants.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/ParseUIConstants.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFCloud+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFFile+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFConfig+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPush+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFUser+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFObject+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFQuery+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFObject.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFProduct.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/DateToolsSwift/DateToolsSwift.framework/Headers/DateToolsSwift-Swift.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFFileUploadResult.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFGeoPoint.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFImageView.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFLogInView.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFSignUpView.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFQuery.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/MBProgressHUD/MBProgressHUD.framework/Modules/module.modulemap /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Modules/module.modulemap /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Modules/module.modulemap /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/DateToolsSwift/DateToolsSwift.framework/Modules/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/CoreLocation.framework/Headers/CoreLocation.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/StoreKit.framework/Headers/StoreKit.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/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Intermediates.noindex/StreamsApp.build/Debug-iphonesimulator/StreamsApp.build/Objects-normal/x86_64/AppDelegate~partial.swiftmodule : /Users/mac/Documents/StreamsApp/StreamsApp/AppDelegate.swift /Users/mac/Documents/StreamsApp/StreamsApp/StreamViewController/PostTableViewCell/PostTableViewCell.swift /Users/mac/Documents/StreamsApp/StreamsApp/StreamViewController/StreamViewController.swift /Users/mac/Documents/StreamsApp/StreamsApp/StreamViewController/NewPostViewController/NewPostViewController.swift /Users/mac/Documents/StreamsApp/StreamsApp/StreamViewController/UserHeaderView/UserHeaderView.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/DateToolsSwift/DateToolsSwift.framework/Modules/DateToolsSwift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreLocation.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/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/MBProgressHUD/MBProgressHUD.framework/Headers/MBProgressHUD.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFACL.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/MBProgressHUD/MBProgressHUD.framework/Headers/MBProgressHUD-umbrella.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/Parse-umbrella.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/Bolts-umbrella.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/DateToolsSwift/DateToolsSwift.framework/Headers/DateToolsSwift-umbrella.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFGeneric.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFCloud+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFFile+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPush+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFUser+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFAnonymousUtils+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFObject+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFQuery+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFTextField.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFCloud.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFCancellationTokenSource.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFTaskCompletionSource.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFFile.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFRole.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPurchase.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/Parse.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFUserAuthenticationDelegate.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFLogInView_Private.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFConfig.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFSubclassing.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPush.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFTask.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFTableViewCell.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPurchaseTableViewCell.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFCollectionViewCell.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFCancellationToken.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPolygon.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFSession.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFRelation.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFInstallation.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFCancellationTokenRegistration.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/ParseClientConfiguration.h /Users/mac/Documents/StreamsApp/StreamsApp-Bridging-Header.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFDecoder.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFEncoder.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFNetworkActivityIndicatorManager.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFFileUploadController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFProductTableViewController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFQueryTableViewController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFLogInViewController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFQueryCollectionViewController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFSignUpViewController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFUser.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFExecutor.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFAnalytics.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFAnonymousUtils.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFObject+Subclass.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/Bolts.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFConstants.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/ParseUIConstants.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFCloud+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFFile+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFConfig+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPush+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFUser+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFObject+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFQuery+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFObject.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFProduct.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/DateToolsSwift/DateToolsSwift.framework/Headers/DateToolsSwift-Swift.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFFileUploadResult.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFGeoPoint.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFImageView.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFLogInView.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFSignUpView.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFQuery.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/MBProgressHUD/MBProgressHUD.framework/Modules/module.modulemap /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Modules/module.modulemap /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Modules/module.modulemap /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/DateToolsSwift/DateToolsSwift.framework/Modules/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/CoreLocation.framework/Headers/CoreLocation.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/StoreKit.framework/Headers/StoreKit.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/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Intermediates.noindex/StreamsApp.build/Debug-iphonesimulator/StreamsApp.build/Objects-normal/x86_64/AppDelegate~partial.swiftdoc : /Users/mac/Documents/StreamsApp/StreamsApp/AppDelegate.swift /Users/mac/Documents/StreamsApp/StreamsApp/StreamViewController/PostTableViewCell/PostTableViewCell.swift /Users/mac/Documents/StreamsApp/StreamsApp/StreamViewController/StreamViewController.swift /Users/mac/Documents/StreamsApp/StreamsApp/StreamViewController/NewPostViewController/NewPostViewController.swift /Users/mac/Documents/StreamsApp/StreamsApp/StreamViewController/UserHeaderView/UserHeaderView.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/DateToolsSwift/DateToolsSwift.framework/Modules/DateToolsSwift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreLocation.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/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/MBProgressHUD/MBProgressHUD.framework/Headers/MBProgressHUD.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFACL.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/MBProgressHUD/MBProgressHUD.framework/Headers/MBProgressHUD-umbrella.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/Parse-umbrella.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/Bolts-umbrella.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/DateToolsSwift/DateToolsSwift.framework/Headers/DateToolsSwift-umbrella.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFGeneric.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFCloud+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFFile+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPush+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFUser+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFAnonymousUtils+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFObject+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFQuery+Deprecated.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFTextField.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFCloud.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFCancellationTokenSource.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFTaskCompletionSource.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFFile.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFRole.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPurchase.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/Parse.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFUserAuthenticationDelegate.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFLogInView_Private.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFConfig.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFSubclassing.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPush.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFTask.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFTableViewCell.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPurchaseTableViewCell.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFCollectionViewCell.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFCancellationToken.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPolygon.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFSession.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFRelation.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFInstallation.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFCancellationTokenRegistration.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/ParseClientConfiguration.h /Users/mac/Documents/StreamsApp/StreamsApp-Bridging-Header.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFDecoder.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFEncoder.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFNetworkActivityIndicatorManager.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFFileUploadController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFProductTableViewController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFQueryTableViewController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFLogInViewController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFQueryCollectionViewController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFSignUpViewController.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFUser.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/BFExecutor.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFAnalytics.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFAnonymousUtils.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFObject+Subclass.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Headers/Bolts.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFConstants.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/ParseUIConstants.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFCloud+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFFile+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFConfig+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFPush+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFUser+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFObject+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFQuery+Synchronous.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFObject.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFProduct.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/DateToolsSwift/DateToolsSwift.framework/Headers/DateToolsSwift-Swift.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFFileUploadResult.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFGeoPoint.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFImageView.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFLogInView.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFSignUpView.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Headers/PFQuery.h /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/MBProgressHUD/MBProgressHUD.framework/Modules/module.modulemap /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Parse/Parse.framework/Modules/module.modulemap /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/Bolts/Bolts.framework/Modules/module.modulemap /Users/mac/Documents/StreamsApp/DerivedData/StreamsApp/Build/Products/Debug-iphonesimulator/DateToolsSwift/DateToolsSwift.framework/Modules/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/CoreLocation.framework/Headers/CoreLocation.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/StoreKit.framework/Headers/StoreKit.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 perfontain.managers.gui.select; import std, perfontain; public import perfontain.managers.gui.select.box, perfontain.managers.gui.select.popup; class Selector : GUIElement { this(GUIElement p, bool followMouse = true) { super(p); _followMouse = followMouse; } void select(int) {} private: mixin publicProperty!(int, `selected`, `-1`); void doSelect(int idx) { select(_selected = idx); } bool _followMouse; } class Selectable : GUIElement { this(Selector p, int n = 0) { super(p, Vector2s.init, Win.captureFocus); idx = n; } override void draw(Vector2s p) const { auto s = selector; if(s._followMouse ? flags.hasMouse : s.selected == idx) { drawQuad(p + pos, size, Color(0xa3, 0xdb, 0xfb, 0xff)); } super.draw(p); } override void onPress(Vector2s, bool v) { if(flags.hasMouse && !v) { selector.doSelect(idx); } } int idx; private: inout selector() { return firstParent!Selector; } }
D
/* 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. */ module flow.engine.impl.bpmn.deployer.ParsedDeploymentBuilderFactory; import hunt.collection.Map; import flow.common.api.repository.EngineDeployment; import flow.engine.impl.bpmn.parser.BpmnParser; import flow.engine.impl.bpmn.deployer.ParsedDeploymentBuilder; class ParsedDeploymentBuilderFactory { protected BpmnParser bpmnParser; public BpmnParser getBpmnParser() { return bpmnParser; } public void setBpmnParser(BpmnParser bpmnParser) { this.bpmnParser = bpmnParser; } public ParsedDeploymentBuilder getBuilderForDeployment(EngineDeployment deployment) { return getBuilderForDeploymentAndSettings(deployment, null); } public ParsedDeploymentBuilder getBuilderForDeploymentAndSettings(EngineDeployment deployment, Map!(string, Object) deploymentSettings) { return new ParsedDeploymentBuilder(deployment, bpmnParser, deploymentSettings); } }
D
module wrapper; private { import derelict.openal.al; } public { import buffer; import capture; import source; } ALCdevice* device; ALCcontext* context; void init() { device = alcOpenDevice(null); context = alcCreateContext(device, null); alcMakeContextCurrent(context); } void exit() { alcMakeContextCurrent(null); alcDestroyContext(context); alcCloseDevice(device); }
D
module UnrealScript.Engine.SequenceObject; import ScriptClasses; import UnrealScript.Helpers; import UnrealScript.Engine.WorldInfo; import UnrealScript.Core.UObject; import UnrealScript.Engine.Sequence; extern(C++) interface SequenceObject : UObject { public extern(D): private static __gshared ScriptClass mStaticClass; @property final static ScriptClass StaticClass() { mixin(MGSCC("Class Engine.SequenceObject")); } private static __gshared SequenceObject mDefaultProperties; @property final static SequenceObject DefaultProperties() { mixin(MGDPC("SequenceObject", "SequenceObject Engine.Default__SequenceObject")); } static struct Functions { private static __gshared { ScriptFunction mGetObjClassVersion; ScriptFunction mScriptLog; ScriptFunction mGetWorldInfo; ScriptFunction mIsValidLevelSequenceObject; ScriptFunction mIsPastingIntoLevelSequenceAllowed; } public @property static final { ScriptFunction GetObjClassVersion() { mixin(MGF("mGetObjClassVersion", "Function Engine.SequenceObject.GetObjClassVersion")); } ScriptFunction ScriptLog() { mixin(MGF("mScriptLog", "Function Engine.SequenceObject.ScriptLog")); } ScriptFunction GetWorldInfo() { mixin(MGF("mGetWorldInfo", "Function Engine.SequenceObject.GetWorldInfo")); } ScriptFunction IsValidLevelSequenceObject() { mixin(MGF("mIsValidLevelSequenceObject", "Function Engine.SequenceObject.IsValidLevelSequenceObject")); } ScriptFunction IsPastingIntoLevelSequenceAllowed() { mixin(MGF("mIsPastingIntoLevelSequenceAllowed", "Function Engine.SequenceObject.IsPastingIntoLevelSequenceAllowed")); } } } @property final { auto ref { int ObjInstanceVersion() { mixin(MGPC("int", 60)); } ScriptArray!(ScriptString) ObjRemoveInProject() { mixin(MGPC("ScriptArray!(ScriptString)", 100)); } int DrawHeight() { mixin(MGPC("int", 136)); } int DrawWidth() { mixin(MGPC("int", 132)); } ScriptString ObjComment() { mixin(MGPC("ScriptString", 116)); } UObject.Color ObjColor() { mixin(MGPC("UObject.Color", 112)); } ScriptString ObjCategory() { mixin(MGPC("ScriptString", 88)); } ScriptString ObjName() { mixin(MGPC("ScriptString", 76)); } int ObjPosY() { mixin(MGPC("int", 72)); } int ObjPosX() { mixin(MGPC("int", 68)); } Sequence ParentSequence() { mixin(MGPC("Sequence", 64)); } } bool bSuppressAutoComment() { mixin(MGBPC(128, 0x10)); } bool bSuppressAutoComment(bool val) { mixin(MSBPC(128, 0x10)); } bool bOutputObjCommentToScreen() { mixin(MGBPC(128, 0x8)); } bool bOutputObjCommentToScreen(bool val) { mixin(MSBPC(128, 0x8)); } bool bDrawLast() { mixin(MGBPC(128, 0x4)); } bool bDrawLast(bool val) { mixin(MSBPC(128, 0x4)); } bool bDrawFirst() { mixin(MGBPC(128, 0x2)); } bool bDrawFirst(bool val) { mixin(MSBPC(128, 0x2)); } bool bDeletable() { mixin(MGBPC(128, 0x1)); } bool bDeletable(bool val) { mixin(MSBPC(128, 0x1)); } } final: static int GetObjClassVersion() { ubyte params[4]; params[] = 0; StaticClass.ProcessEvent(Functions.GetObjClassVersion, params.ptr, cast(void*)0); return *cast(int*)params.ptr; } void ScriptLog(ScriptString LogText, bool* bWarning = null) { ubyte params[16]; params[] = 0; *cast(ScriptString*)params.ptr = LogText; if (bWarning !is null) *cast(bool*)&params[12] = *bWarning; (cast(ScriptObject)this).ProcessEvent(Functions.ScriptLog, params.ptr, cast(void*)0); } WorldInfo GetWorldInfo() { ubyte params[4]; params[] = 0; (cast(ScriptObject)this).ProcessEvent(Functions.GetWorldInfo, params.ptr, cast(void*)0); return *cast(WorldInfo*)params.ptr; } bool IsValidLevelSequenceObject() { ubyte params[4]; params[] = 0; (cast(ScriptObject)this).ProcessEvent(Functions.IsValidLevelSequenceObject, params.ptr, cast(void*)0); return *cast(bool*)params.ptr; } bool IsPastingIntoLevelSequenceAllowed() { ubyte params[4]; params[] = 0; (cast(ScriptObject)this).ProcessEvent(Functions.IsPastingIntoLevelSequenceAllowed, params.ptr, cast(void*)0); return *cast(bool*)params.ptr; } }
D
/afs/cern.ch/work/m/mmittal/private/MyAnalysisCode/RootCoreBin/obj/x86_64-slc6-gcc49-opt/MadGraphME/obj/CPPProcess_P0_Sigma_sm_hVBF_ZZ_4l_sm_uux_epemepemuux.o /afs/cern.ch/work/m/mmittal/private/MyAnalysisCode/RootCoreBin/obj/x86_64-slc6-gcc49-opt/MadGraphME/obj/CPPProcess_P0_Sigma_sm_hVBF_ZZ_4l_sm_uux_epemepemuux.d : /afs/cern.ch/work/m/mmittal/private/MyAnalysisCode/MadGraphME/Root/CPPProcess_P0_Sigma_sm_hVBF_ZZ_4l_sm_uux_epemepemuux.cxx /afs/cern.ch/work/m/mmittal/private/MyAnalysisCode/MadGraphME/cmt/../MadGraphME/CPPProcess_P0_Sigma_sm_hVBF_ZZ_4l_sm_uux_epemepemuux.h /afs/cern.ch/work/m/mmittal/private/MyAnalysisCode/MadGraphME/cmt/../MadGraphME/Parameters_sm.h /afs/cern.ch/work/m/mmittal/private/MyAnalysisCode/MadGraphME/cmt/../MadGraphME/read_slha.h /afs/cern.ch/work/m/mmittal/private/MyAnalysisCode/MadGraphME/cmt/../MadGraphME/HelAmps_sm.h
D
/* TEST_OUTPUT: --- fail_compilation/diag10169.d(12): Deprecation: `imports.a10169.B.x` is not visible from module `diag10169` fail_compilation/diag10169.d(12): Error: struct `imports.a10169.B` member `x` is not accessible --- */ import imports.a10169; void main() { auto a = B.init.x; }
D
module veda.mstorage.nanomsg_channel; import core.thread, std.stdio, std.format, std.datetime, std.concurrency, std.conv, std.outbuffer, std.string, std.uuid, std.path, std.json; import veda.core.common.context, veda.core.util.utils, veda.util.tools, veda.onto.onto, veda.core.impl.thread_context, veda.core.common.define; import kaleidic.nanomsg.nano, veda.mstorage.server; // ////// Logger /////////////////////////////////////////// import veda.common.logger; Logger _log; Logger log() { if (_log is null) _log = new Logger("veda-core-mstorage", "log", "N-CHANNEL"); return _log; } // ////// ////// /////////////////////////////////////////// void nanomsg_channel(string thread_name) { int sock; string url = "tcp://127.0.0.1:9112\0"; try { Context context; core.thread.Thread.getThis().name = thread_name; sock = nn_socket(AF_SP, NN_REP); if (sock < 0) { log.trace("ERR! cannot create socket"); return; } if (nn_bind(sock, cast(char *)url) < 0) { log.trace("ERR! cannot bind to socket, url=%s", url); return; } log.trace("success bind to %s", url); if (context is null) context = PThreadContext.create_new("cfg:standart_node", thread_name, individuals_db_path, log, null, null, null, null); // SEND ready receive((Tid tid_response_reciever) { send(tid_response_reciever, true); }); while (true) { try { char *buf = cast(char *)0; int bytes = nn_recv(sock, &buf, NN_MSG, 0); if (bytes >= 0) { string req = cast(string)buf[ 0..bytes ]; //log.trace("RECEIVED [%d](%s)", bytes, req); string rep; if (req[ 0 ] == '{') { //log.trace ("is json"); rep = execute_json(req, context); } else { //log.trace ("is binobj"); rep = execute_binobj(req, context); } nn_freemsg(buf); bytes = nn_send(sock, cast(char *)rep, rep.length + 1, 0); // log.trace("SENDING (%s) %d bytes", rep, bytes); } } catch (Throwable tr) { log.trace("ERR! MAIN LOOP", tr.info); } } } finally { writeln("exit form thread ", thread_name); } }
D
liberality in bestowing gifts
D
module sailhandler; import core.thread; import core.sync.condition; import core.sync.mutex; import std.conv, std.math; import saillog, config; import hardware.hardware; class SailHandler { this() { SailLog.Notify("Starting ",typeof(this).stringof," instantiation in ",Thread.getThis().name," thread..."); //Get configuration m_nMaxTension = Hardware.Get!Sail(DeviceID.Sail).max; m_bEnabled = true; m_stopCond = new Condition(new Mutex); //Start the thread m_thread = new Thread(&ThreadFunction); m_thread.name(typeof(this).stringof); m_thread.isDaemon(true); m_thread.start(); SailLog.Success(typeof(this).stringof~" instantiated in ",Thread.getThis().name," thread"); } ~this(){ SailLog.Critical("Destroying ",typeof(this).stringof); m_stop = true; m_stopCond.notifyAll; m_thread.join(); } @property{ bool enabled()const{return m_bEnabled;} void enabled(bool b){m_bEnabled = b;} } private: Thread m_thread; shared bool m_stop = false; Condition m_stopCond; bool m_bEnabled; void ThreadFunction(){ while(!m_stop){ try{ debug(thread){ SailLog.Post("Running "~typeof(this).stringof~" thread"); } if(m_bEnabled) AdjustSail(); }catch(Throwable t){ SailLog.Critical("In thread ",m_thread.name,": ",t.toString); } synchronized(m_stopCond.mutex) m_stopCond.wait(dur!("msecs")(Config.Get!uint("SailHandler", "Period"))); } } /** Do a sail adjustment, to match the wind direction */ void AdjustSail(){ float fWind = abs(Hardware.Get!WindDir(DeviceID.WindDir).value); auto sail = Hardware.Get!Sail(DeviceID.Sail); auto roll = Hardware.Get!Roll(DeviceID.Roll).value; if(fWind<25){ sail.value = m_nMaxTension; } else{ //Linear function sail.value = to!(typeof(sail.value))(m_nMaxTension-(m_nMaxTension-sail.min)*(fWind-25)/(180-25)); } auto danger = Config.Get!float("SailHandler", "Danger"); //Handling m_nMaxTension (safety max tension) if(abs(roll)>danger){ ubyte nDelta = Config.Get!ubyte("SailHandler", "Delta"); //Reduce max tension, minimum to sail.max/4 if(m_nMaxTension-sail.max/4 >= nDelta) m_nMaxTension-=nDelta; else m_nMaxTension = sail.max/4; SailLog.Warning("Roll is too dangerous (",roll,"°), reducing sail max tension to ",m_nMaxTension); } else if(m_nMaxTension!=sail.max && abs(roll)<danger/2.0){ ubyte nDelta = Config.Get!ubyte("SailHandler", "Delta"); //Reduce max tension, minimum to sail.max/4 if(sail.max - m_nMaxTension >= nDelta) m_nMaxTension+=nDelta; else m_nMaxTension = sail.max; SailLog.Notify("Roll seems safe (",roll,"°), raising sail max tension to ",m_nMaxTension); } } ubyte m_nMaxTension; } unittest { import decisioncenter; auto dec = DecisionCenter.Get(); auto sh = dec.sailhandler; auto wind = Hardware.Get!WindDir(DeviceID.WindDir); auto sail = Hardware.Get!Sail(DeviceID.Sail); auto roll = Hardware.Get!Roll(DeviceID.Roll); assert(sh.enabled==true); dec.enabled = false; sh.enabled = false; Thread.sleep(dur!("msecs")(100)); wind.isemulated = true; wind.value = 20; sh.AdjustSail(); assert(sail.value==sail.max); wind.value = wind.max; sh.AdjustSail(); assert(sail.value==sail.min); wind.value = wind.min; sh.AdjustSail(); assert(sail.value==sail.min); //Roll danger roll.isemulated = true; roll.value = 0.0; auto delta = Config.Get!ubyte("SailHandler", "Delta"); auto danger = Config.Get!float("SailHandler", "Danger"); sh.AdjustSail(); assert(sh.m_nMaxTension==sail.max); roll.value = danger+1.0; sh.AdjustSail(); assert(sh.m_nMaxTension==sail.max-1*delta); sh.AdjustSail(); assert(sh.m_nMaxTension==sail.max-2*delta); sh.AdjustSail(); assert(sh.m_nMaxTension==sail.max-3*delta); roll.value = danger-1.0; sh.AdjustSail(); assert(sh.m_nMaxTension==sail.max-3*delta); sh.AdjustSail(); assert(sh.m_nMaxTension==sail.max-3*delta); roll.value = danger/2.0-1.0; sh.AdjustSail(); assert(sh.m_nMaxTension==sail.max-2*delta); sh.AdjustSail(); assert(sh.m_nMaxTension==sail.max-1*delta); sh.AdjustSail(); sh.AdjustSail(); sh.AdjustSail(); assert(sh.m_nMaxTension==sail.max); roll.value = danger+1.0; foreach(int i ; 0..100)sh.AdjustSail(); assert(sail.max/4-delta<=sh.m_nMaxTension && sh.m_nMaxTension<=sail.max/4); SailLog.Notify("SailHandler unittest done"); }
D
/** * Copyright © Novelate 2020 * License: MIT (https://github.com/Novelate/NovelateEngine/blob/master/LICENSE) * Author: Jacob Jensen (bausshf) * Website: https://novelate.com/ * ------ * Novelate is a free and open-source visual novel engine and framework written in the D programming language. * It can be used freely for both personal and commercial projects. * ------ * Module Description: * This is the module for displaying the main menu. */ module novelate.mainmenu; import std.conv : to; import dsfml.window : Keyboard, Mouse; import dsfml.system : Vector2f; import novelate.config; import novelate.imagecomponent; import novelate.animatedimage; import novelate.media; import novelate.label; import novelate.colormanager; import novelate.layer; import novelate.core : getLayer, LayerType, changeScreen, Screen; import novelate.state : exitGame, playScene; public alias MouseButton = Mouse.Button; public alias Key = Keyboard.Key; package(novelate): /// Shows the main menu. void showMainMenu() { auto backgroundLayer = getLayer(LayerType.background); { auto oldBackground = cast(ImageComponent)backgroundLayer.getComponent("background"); if (oldBackground) { backgroundLayer.addComponent(oldBackground, "background_old"); backgroundLayer.removeComponent("background"); oldBackground.fadeOut(20); } } { auto oldBackground = cast(AnimatedImage)backgroundLayer.getComponent("background"); if (oldBackground) { backgroundLayer.addComponent(oldBackground, "background_old"); backgroundLayer.removeComponent("background"); oldBackground.fadeOut(20); } } auto backgroundFrames = config.menuBackground; if (backgroundFrames && backgroundFrames.frames && backgroundFrames.frames.length) { string[] backgroundImages = []; auto frameSpeed = backgroundFrames.frames[0].nextFrameTime; foreach (frame; backgroundFrames.frames) { backgroundImages ~= getMediaFile(frame.image).relativePath(backgroundLayer.width); } if (backgroundImages && backgroundImages.length) { auto image = new AnimatedImage(backgroundImages); image.animationSpeed = frameSpeed; image.fadeIn(20); image.fadedIn = () { backgroundLayer.removeComponent("background_old"); }; image.fullScreen = true; image.refresh(backgroundLayer.width, backgroundLayer.height); backgroundLayer.addComponent(image, "background"); } } auto frontLayer = getLayer(LayerType.front); auto logoFrames = config.menuLogoImage; if (logoFrames && logoFrames.frames && logoFrames.frames.length) { string[] logoImages = []; auto frameSpeed = logoFrames.frames[0].nextFrameTime; foreach (frame; logoFrames.frames) { logoImages ~= getMediaFile(frame.image).relativePath(frontLayer.width); } if (logoImages && logoImages.length) { auto image = new AnimatedImage(logoImages); image.animationSpeed = frameSpeed; image.fadeIn(20); image.position = Vector2f(config.menuLogoImageX800, config.menuLogoImageY800); frontLayer.addComponent(image, "logo"); } } AltValue!(ptrdiff_t, string) menuBoxOffsetX; AltValue!(ptrdiff_t, string) menuBoxOffsetY; if (backgroundLayer.width == 800) { menuBoxOffsetX = config.menuBox_X800; menuBoxOffsetY = config.menuBox_Y800; } else if (backgroundLayer.width == 1024) { menuBoxOffsetX = config.menuBox_X1024; menuBoxOffsetY = config.menuBox_Y1024; } else if (backgroundLayer.width == 1280) { menuBoxOffsetX = config.menuBox_X1280; menuBoxOffsetY = config.menuBox_Y1280; } ptrdiff_t offsetX = 0; ptrdiff_t offsetY = 0; if (menuBoxOffsetX.value2 && menuBoxOffsetX.value2.length) { switch (menuBoxOffsetX.value2) { case "C": case "Center": offsetX = (backgroundLayer.width / 2); break; default: break; } } else { offsetX = menuBoxOffsetX.value1; } Label[] labels = []; labels ~= createLabel(config.menuItem_Play.text, (b, ref s) { changeScreen(Screen.scene, [playScene]); }, offsetX); labels ~= createLabel(config.menuItem_Load.text, (b, ref s) { changeScreen(Screen.load); }, offsetX); labels ~= createLabel(config.menuItem_Save.text, (b, ref s) { changeScreen(Screen.save); }, offsetX); labels ~= createLabel(config.menuItem_About.text, (b, ref s) { changeScreen(Screen.about); }, offsetX); labels ~= createLabel(config.menuItem_Characters.text, (b, ref s) { changeScreen(Screen.characters); }, offsetX); labels ~= createLabel(config.menuItem_Exit.text, (b, ref s) { exitGame = true; }, offsetX); if (menuBoxOffsetY.value2 && menuBoxOffsetY.value2.length) { size_t totalHeight = 0; foreach (label; labels) { totalHeight += label.height; totalHeight += cast(size_t)(cast(double)label.fontSize * 0.5); } switch (menuBoxOffsetY.value2) { case "B": case "Bottom": totalHeight += cast(size_t)(cast(double)labels[0].fontSize * 1.5); offsetY = (backgroundLayer.height - totalHeight); break; case "T": case "Top": offsetY = cast(ptrdiff_t)(cast(double)labels[0].fontSize * 1.5); break; case "C": case "Center": offsetY = cast(ptrdiff_t)((backgroundLayer.height / 2) - (totalHeight / 2)); break; default: break; } } else { offsetY = menuBoxOffsetY.value1; } foreach (label; labels) { label.position = Vector2f(label.x, offsetY); offsetY += label.height; offsetY += cast(size_t)(cast(double)label.fontSize * 0.5); getLayer(LayerType.dialogueBoxInteraction) .addComponent(label, to!string(label.text)); } } /** * Creates a label for the menu. * Params: * text = The text of the label. * mouseRelease = Handler for when the label is pressed. * offsetX = The x offset of the label. */ private Label createLabel(string text, void delegate(MouseButton button, ref bool stopEvent) mouseRelease, ptrdiff_t offsetX) { auto label = new Label; label.color = colorFromString(config.defaultDialogueColor); label.fontSize = 48; if (config.defaultFont && config.defaultFont.length) { label.fontName = config.defaultFont; } label.text = to!dstring(text); label.position = Vector2f(offsetX - (label.width / 2), 50000); label.mouseRelease = mouseRelease; return label; }
D
module app; import std.stdio; import std.typecons; import lbfgsd; void main() { auto solver = new SimpleSolver!(float, 2); solver.options.linesearch.maxIterations = 1000; solver.options.maxIterations = 2000; //solver.options.estimateStepSize = false; LeastSquareLossFunc fn; foreach (i; 0 .. 20) { import std.random : uniform; // (x, 3x - 1 + random) fn.data ~= tuple(float(i), float(3f * i - 1 + uniform(-0.1f, 0.1f))); } solver.setAutoDiffCost(fn); auto x = new float[2]; x[] = 0; auto result = solver.solve(x); writeln("iterations : ", result.iterations.length); writeln("last 10 steps :"); import std.range : tail; foreach (i, iter; result.iterations.tail(10)) { writeln(i, " : ", iter); } writeln("-----"); writeln(result.status); writeln(x); writeln(fn(x)); //writeln(result.lastCost); } struct LeastSquareLossFunc { Tuple!(float, float)[] data; auto opCall(T)(const scope T[] ab) { const A = ab[0]; const B = ab[1]; auto result = T(0); foreach (d; data) { const t = A * d[0] + B; result += square(d[1] - t); } return result; } }
D
// Generated by gnome-h2d.rb <http://github.com/ddude/gnome.d>. module gmodule.d; public { import gmodule.gmodule; }
D
instance Grd_2504_PatrolGRD (Npc_Default) { //-------- primary data -------- name = "Strażnik"; npctype = npctype_main; guild = GIL_GRD; level = 16; voice = 9; id = 2504; //-------- abilities -------- attribute[ATR_STRENGTH] = 60; attribute[ATR_DEXTERITY] = 40; attribute[ATR_MANA_MAX] = 0; attribute[ATR_MANA] = 0; attribute[ATR_HITPOINTS_MAX]= self.level*12+90; attribute[ATR_HITPOINTS_MAX]= self.level*12+90; //-------- visuals -------- // animations Mdl_SetVisual (self,"HUMANS.MDS"); Mdl_ApplyOverlayMds (self,"Humans_Militia.mds"); // body mesh ,bdytex,skin,head mesh ,headtex,teethtex,ruestung Mdl_SetVisualBody (self,"hum_body_Naked0",0,1,"Hum_Head_Bald",53,1,GRD_ARMOR_M); B_Scale (self); Mdl_SetModelFatness(self,0); //-------- Talente -------- Npc_SetTalentSkill (self,NPC_TALENT_1H,1); //-------- inventory -------- EquipItem (self,GRD_MW_02); //pousuwalem kusze bo zaczynal nas atakowac z kuszy EquipItem (self,GRD_RW_01); CreateInvItems (self,ItAmBolt,30); CreateInvItems (self,ItMinugget,24); CreateInvItems (self,ItMiJoint_1,1); CreateInvItems (self,ItFo_Potion_Health_01,2); CreateInvItems (self,ItFo_Potion_Health_02,1); //------------- ai ------------- B_InitNPCAddins(self); fight_tactic = FAI_HUMAN_STRONG; daily_routine = Rtn_start_2504; }; FUNC VOID Rtn_start_2504 () { //Sleep /* TA_Guard (00,00,00,12,"OW_PATH_067"); TA_Guard (00,12,00,24,"OW_PATH_068"); TA_Guard (00,24,00,36,"NC_PATH55"); TA_Guard (00,36,00,48,"NC_PATH068"); TA_Guard (00,48,01,00,"NC_PATH79"); TA_Guard (01,00,01,12,"NC_PATH81"); TA_Guard (01,12,01,24,"NC_PATH52"); TA_Guard (01,24,01,36,"NC_PATH53"); TA_Guard (01,36,01,48,"NC_PATH68"); TA_Guard (01,48,02,00,"NC_PATH78_A"); TA_Guard (02,00,02,12,"NC_PATH098"); TA_Guard (02,12,02,24,"NC_PATH82"); TA_Guard (02,24,02,36,"NC_PATH84"); TA_Guard (02,36,02,48,"NC_PATH54"); TA_Guard (02,48,03,00,"PATH_OC_NC_27"); TA_Guard (03,00,03,12,"OW_PATH_067"); TA_Guard (03,12,03,24,"OW_PATH_068"); TA_Guard (03,24,03,36,"NC_PATH55"); TA_Guard (03,36,03,48,"NC_PATH068"); TA_Guard (03,48,04,00,"NC_PATH79"); TA_Guard (04,00,04,12,"NC_PATH81"); TA_Guard (04,12,04,24,"NC_PATH52"); TA_Guard (04,24,04,36,"NC_PATH53"); TA_Guard (04,36,04,48,"NC_PATH68"); TA_Guard (04,48,05,00,"NC_PATH78_A"); TA_Guard (05,00,05,12,"NC_PATH098"); TA_Guard (05,12,05,24,"NC_PATH82"); TA_Guard (05,24,05,36,"NC_PATH84"); TA_Guard (05,36,05,48,"NC_PATH54"); TA_Guard (05,48,06,00,"PATH_OC_NC_27"); */ TA_SitCampfire (00,00,06,00,"NC_PATH_PEASANT_OUTSIDE8"); TA_Guard (06,00,06,12,"OW_PATH_067"); TA_Guard (06,12,06,24,"OW_PATH_068"); TA_Guard (06,24,06,36,"NC_PATH068"); TA_Guard (06,36,06,48,"NC_PATH68"); TA_Guard (06,48,07,00,"NC_PATH79"); TA_Guard (07,00,07,12,"NC_PATH81"); TA_Guard (07,12,07,24,"NC_PATH52"); TA_Guard (07,24,07,36,"NC_PATH53"); TA_Guard (07,36,07,48,"NC_PATH68"); TA_Guard (07,48,08,00,"NC_PATH78_A"); TA_Guard (08,00,08,12,"NC_PATH098"); TA_Guard (08,12,08,24,"NC_PATH82"); TA_Guard (08,24,08,36,"NC_PATH84"); TA_Guard (08,36,08,48,"NC_PATH54"); TA_Guard (08,48,09,00,"PATH_OC_NC_27"); TA_Guard (09,00,09,12,"OW_PATH_067"); TA_Guard (09,12,09,24,"OW_PATH_068"); TA_Guard (09,24,09,36,"NC_PATH55"); TA_Guard (09,36,09,48,"NC_PATH068"); TA_Guard (09,48,10,00,"NC_PATH79"); TA_Guard (10,00,10,12,"NC_PATH81"); TA_Guard (10,12,10,24,"NC_PATH52"); TA_Guard (10,24,10,36,"NC_PATH53"); TA_Guard (10,36,10,48,"NC_PATH68"); TA_Guard (10,48,11,00,"NC_PATH78_A"); TA_Guard (11,00,11,12,"NC_PATH098"); TA_Guard (11,12,11,24,"NC_PATH82"); TA_Guard (11,24,11,36,"NC_PATH84"); TA_Guard (11,36,11,48,"NC_PATH54"); TA_Guard (11,48,12,00,"PATH_OC_NC_27"); TA_Guard (12,00,12,12,"OW_PATH_067"); TA_Guard (12,12,12,24,"OW_PATH_068"); TA_Guard (12,24,12,36,"NC_PATH55"); TA_Guard (12,36,12,48,"NC_PATH068"); TA_Guard (12,48,13,00,"NC_PATH79"); TA_Guard (13,00,13,12,"NC_PATH81"); TA_Guard (13,12,13,24,"NC_PATH52"); TA_Guard (13,24,13,36,"NC_PATH53"); TA_Guard (13,36,13,48,"NC_PATH68"); TA_Guard (13,48,14,00,"NC_PATH78_A"); TA_Guard (14,00,14,12,"NC_PATH098"); TA_Guard (14,12,14,24,"NC_PATH82"); TA_Guard (14,24,14,36,"NC_PATH84"); TA_Guard (14,36,14,48,"NC_PATH54"); TA_Guard (14,48,15,00,"PATH_OC_NC_27"); TA_Guard (15,00,15,12,"OW_PATH_067"); TA_Guard (15,12,15,24,"OW_PATH_068"); TA_Guard (15,24,15,36,"NC_PATH55"); TA_Guard (15,36,15,48,"NC_PATH068"); TA_Guard (15,48,16,00,"NC_PATH79"); TA_Guard (16,00,16,12,"NC_PATH81"); TA_Guard (16,12,16,24,"NC_PATH52"); TA_Guard (16,24,16,36,"NC_PATH53"); TA_Guard (16,36,16,48,"NC_PATH68"); TA_Guard (16,48,17,00,"NC_PATH78_A"); TA_Guard (17,00,17,12,"NC_PATH098"); TA_Guard (17,12,17,24,"NC_PATH82"); TA_Guard (17,24,17,36,"NC_PATH84"); TA_Guard (17,36,17,48,"NC_PATH54"); TA_Guard (17,48,18,00,"PATH_OC_NC_27"); TA_Guard (18,00,18,12,"OW_PATH_067"); TA_Guard (18,12,18,24,"OW_PATH_068"); TA_Guard (18,24,18,36,"NC_PATH55"); TA_Guard (18,36,18,48,"NC_PATH068"); TA_Guard (18,48,18,00,"NC_PATH79"); TA_Guard (19,00,19,12,"NC_PATH81"); TA_Guard (19,12,19,24,"NC_PATH52"); TA_Guard (19,24,19,36,"NC_PATH53"); TA_Guard (19,36,19,48,"NC_PATH68"); TA_Guard (19,48,19,00,"NC_PATH78_A"); TA_Guard (20,00,20,12,"NC_PATH098"); TA_Guard (20,12,20,24,"NC_PATH82"); TA_Guard (20,24,20,36,"NC_PATH84"); TA_Guard (20,36,20,48,"NC_PATH54"); TA_Guard (20,48,21,00,"PATH_OC_NC_27"); TA_Guard (21,00,21,12,"OW_PATH_067"); TA_Guard (21,12,21,24,"OW_PATH_068"); TA_Guard (21,24,21,36,"NC_PATH55"); TA_Guard (21,36,21,48,"NC_PATH068"); TA_Guard (21,48,21,00,"NC_PATH79"); TA_Guard (21,00,22,12,"NC_PATH81"); TA_Guard (22,12,22,24,"NC_PATH52"); TA_Guard (22,24,22,36,"NC_PATH53"); TA_Guard (22,36,22,48,"NC_PATH68"); TA_Guard (22,48,22,00,"NC_PATH78_A"); TA_Guard (23,00,23,12,"NC_PATH098"); TA_Guard (23,12,23,24,"NC_PATH82"); TA_Guard (23,24,23,36,"NC_PATH84"); TA_Guard (23,36,23,48,"NC_PATH54"); TA_Guard (23,48,00,00,"PATH_OC_NC_27"); }; FUNC VOID Rtn_NC1_2504 () { TA_HostileGuard (00,00,00,12,"NC_HUT05_MOVEMENT"); TA_HostileGuard (00,12,00,24,"NC_HUT05_MOVEMENT"); };
D
instance GRD_263_Asghan (Npc_Default) { //-------- primary data -------- name = "Asghan"; npctype = npctype_main; guild = GIL_GRD; level = 20; voice = 6; id = 263; flags = NPC_FLAG_IMMORTAL; //-------- abilities -------- attribute[ATR_STRENGTH] = 100; attribute[ATR_DEXTERITY] = 80; attribute[ATR_MANA_MAX] = 0; attribute[ATR_MANA] = 0; attribute[ATR_HITPOINTS_MAX]= 280; attribute[ATR_HITPOINTS] = 280; //-------- visuals -------- // animations Mdl_SetVisual (self,"HUMANS.MDS"); Mdl_ApplyOverlayMds (self,"Humans_Militia.mds"); // body mesh ,bdytex,skin,head mesh ,headtex,teethtex,ruestung Mdl_SetVisualBody (self,"hum_body_Naked0",0,1,"Hum_Head_FatBald",15,1,GRD_ARMOR_H); B_Scale (self); Mdl_SetModelFatness(self,0); fight_tactic = FAI_HUMAN_STRONG; //-------- Talente -------- Npc_SetTalentSkill (self,NPC_TALENT_1H,2); Npc_SetTalentSkill (self,NPC_TALENT_2H,1); Npc_SetTalentSkill (self,NPC_TALENT_CROSSBOW,1); //-------- inventory -------- EquipItem (self,GRD_MW_02U); EquipItem (self,ItRw_Crossbow_01); CreateInvItems (self,ItAmBolt,30); CreateInvItem (self,ItFoMutton); CreateInvItems (self,ItMiNugget,20); CreateInvItem (self,ItFo_Potion_Health_01); CreateInvItem (self,ItLsTorch); //-------------Daily Routine------------- /*B_InitNPCAddins(self);*/ daily_routine = Rtn_start_263; Npc_SetPermAttitude(self,ATT_NEUTRAL); }; FUNC VOID Rtn_start_263 () { TA_Stay(00,00,12,00,"OCR_NORTHGATE_RAMP_ATOP"); TA_Stay(12,00,24,00,"OCR_NORTHGATE_RAMP_ATOP"); }; FUNC VOID Rtn_opengate_263 () { TA_Stay (00,00,12,00,"OM_CAVE3_18"); TA_Stay (12,00,24,00,"OM_CAVE3_18"); }; FUNC VOID Rtn_WAIT_263 () { TA_Stay (00,00,12,00,"OC2"); TA_Stay (12,00,24,00,"OC2"); }; FUNC VOID Rtn_FOLLOW_263 () { TA_FollowPC (0,00,12,00,"FP_ROAM_OW_SNAPPER_OW_ORC"); TA_FollowPC (12,00,0,00,"FP_ROAM_OW_SNAPPER_OW_ORC"); }; FUNC VOID Rtn_NC1_263 () { TA_StandAround (00,00,12,00,"NC_TAVERN_ROOM07"); TA_StandAround (12,00,24,00,"NC_TAVERN_ROOM07"); };
D
module doogle.controls.layout; public import doogle.controls.layout_def; version(Windows) { alias Layout_Def Layout; }
D
module org.serviio.library.online.WebResourceParser; import java.lang.Long; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.serviio.config.Configuration; import org.serviio.library.entities.OnlineRepository; import org.serviio.library.local.metadata.ImageDescriptor; import org.serviio.library.metadata.InvalidMetadataException; import org.serviio.library.metadata.MediaFileType; import org.serviio.library.online.metadata.WebResource; import org.serviio.util.ObjectValidator; import org.serviio.util.StringUtils; import org.serviio.library.online.AbstractOnlineItemParser; import org.serviio.library.online.WebResourceItem; import org.serviio.library.online.WebResourceUrlExtractor; import org.serviio.library.online.WebResourceContainer; static import org.serviio.library.online.metadata.WebResourceItem; public class WebResourceParser : AbstractOnlineItemParser { public WebResource parse(URL resourceUrl, Long onlineRepositoryId, MediaFileType fileType) { log.debug_(String.format("Parsing web resource '%s'", cast(Object[])[ resourceUrl ])); WebResource resource = new WebResource(onlineRepositoryId); WebResourceUrlExtractor suitablePlugin = cast(WebResourceUrlExtractor)findSuitableExtractorPlugin(resourceUrl, OnlineRepository.OnlineRepositoryType.WEB_RESOURCE); if (suitablePlugin !is null) { WebResourceContainer container = null; try { container = suitablePlugin.parseWebResource(resourceUrl, Configuration.getMaxNumberOfItemsForOnlineFeeds().intValue()); } catch (Throwable e) { throw new IOException(String.format("Unexpected error while invoking plugin (%s): %s", cast(Object[])[ suitablePlugin.getExtractorName(), e.getMessage() ]), e); } if (container !is null) { resource.setTitle(StringUtils.trim(container.getTitle())); resource.setDomain(resourceUrl.getHost()); resource.setUsedExtractor(suitablePlugin); setContainerThumbnail(resource, container); if (container.getItems() !is null) { int itemOrder = 1; for (int i = 0; (i < container.getItems().size()) && (isAlive); i++) { bool added = addResourceItem(resource, fileType, cast(WebResourceItem)container.getItems().get(i), itemOrder, suitablePlugin); if (added) { itemOrder++; } } } } else { log.warn("Plugin returned null container"); return null; } } else { throw new InvalidMetadataException(String.format("No plugin for web resource %s has been found.", cast(Object[])[ resourceUrl.toString() ])); } return resource; } private bool addResourceItem(WebResource resource, MediaFileType fileType, WebResourceItem item, int order, WebResourceUrlExtractor suitablePlugin) { org.serviio.library.online.metadata.WebResourceItem resourceItem = new org.serviio.library.online.metadata.WebResourceItem(resource, order); try { resourceItem.setDate(item.getReleaseDate()); resourceItem.setTitle(StringUtils.trim(item.getTitle())); try { extractContentUrlViaPlugin(suitablePlugin, resourceItem, item); } catch (Throwable e) { log.debug_(String.format("Unexpected error during url extractor plugin invocation (%s) for item %s: %s", cast(Object[])[ suitablePlugin.getExtractorName(), resourceItem.getTitle(), e.getMessage() ])); return false; } if (fileType == resourceItem.getType()) { resourceItem.fillInUnknownEntries(); resourceItem.validateMetadata(); log.debug_(String.format("Added resource item %s: '%s' (%s)", cast(Object[])[ Integer.valueOf(order), resourceItem.getTitle(), resourceItem.getContentUrl() ])); resource.getItems().add(resourceItem); return true; } log.debug_(String.format("Skipping web resource item '%s' because it's not of type %s", cast(Object[])[ resourceItem.getTitle(), fileType ])); return false; } catch (InvalidMetadataException e) { log.debug_(String.format("Cannot add item of web resource %s because of invalid metadata. Message: %s", cast(Object[])[ resource.getTitle(), e.getMessage() ])); } return false; } private void extractContentUrlViaPlugin(WebResourceUrlExtractor urlExtractor, org.serviio.library.online.metadata.WebResourceItem.WebResourceItem resourceItem, WebResourceItem extractedItem) { ContentURLContainer extractedUrl = urlExtractor.extractItemUrl(extractedItem); applyContentUrlOnItem(extractedUrl, resourceItem, urlExtractor); resourceItem.getAdditionalInfo().putAll(extractedItem.getAdditionalInfo()); } private void setContainerThumbnail(WebResource resource, WebResourceContainer container) { if ((container !is null) && (ObjectValidator.isNotEmpty(container.getThumbnailUrl()))) try { ImageDescriptor thumbnail = new ImageDescriptor(new URL(container.getThumbnailUrl())); resource.setThumbnail(thumbnail); } catch (MalformedURLException e) { log.warn(String.format("Malformed url of a web resource thumbnail (%s), skipping this thumbnail", cast(Object[])[ container.getThumbnailUrl() ])); } } } /* Location: D:\Program Files\Serviio\lib\serviio.jar * Qualified Name: org.serviio.library.online.WebResourceParser * JD-Core Version: 0.6.2 */
D
/******************************************** * Encode and decode UTF-8, UTF-16 and UTF-32 strings. * * For Win32 systems, the C wchar_t type is UTF-16 and corresponds to the D * wchar type. * For Posix systems, the C wchar_t type is UTF-32 and corresponds to * the D utf.dchar type. * * UTF character support is restricted to (\u0000 &lt;= character &lt;= \U0010FFFF). * * See_Also: * $(LINK2 http://en.wikipedia.org/wiki/Unicode, Wikipedia)<br> * $(LINK http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8)<br> * $(LINK http://anubis.dkuug.dk/JTC1/SC2/WG2/docs/n1335) * Macros: * WIKI = Phobos/StdUtf * * Copyright: Copyright Digital Mars 2003 - 2009. * License: $(WEB www.boost.org/LICENSE_1_0.txt, Boost License 1.0). * Authors: Walter Bright, Sean Kelly */ /* Copyright Digital Mars 2003 - 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.util.utf; extern (C) void onUnicodeError( string msg, size_t idx, string file = __FILE__, size_t line = __LINE__ ); /******************************* * Test if c is a valid UTF-32 character. * * \uFFFE and \uFFFF are considered valid by this function, * as they are permitted for internal use by an application, * but they are not allowed for interchange by the Unicode standard. * * Returns: true if it is, false if not. */ bool isValidDchar(dchar c) { /* Note: FFFE and FFFF are specifically permitted by the * Unicode standard for application internal use, but are not * allowed for interchange. * (thanks to Arcane Jill) */ return c < 0xD800 || (c > 0xDFFF && c <= 0x10FFFF /*&& c != 0xFFFE && c != 0xFFFF*/); } unittest { debug(utf) printf("utf.isValidDchar.unittest\n"); assert(isValidDchar(cast(dchar)'a') == true); assert(isValidDchar(cast(dchar)0x1FFFFF) == false); } static immutable UTF8stride = [ cast(ubyte) 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4,5,5,5,5,6,6,0xFF,0xFF, ]; /** * stride() returns the length of a UTF-8 sequence starting at index i * in string s. * Returns: * The number of bytes in the UTF-8 sequence or * 0xFF meaning s[i] is not the start of of UTF-8 sequence. */ uint stride(in char[] s, size_t i) { return UTF8stride[s[i]]; } /** * stride() returns the length of a UTF-16 sequence starting at index i * in string s. */ uint stride(in wchar[] s, size_t i) { uint u = s[i]; return 1 + (u >= 0xD800 && u <= 0xDBFF); } /** * stride() returns the length of a UTF-32 sequence starting at index i * in string s. * Returns: The return value will always be 1. */ uint stride(in dchar[] s, size_t i) { return 1; } /******************************************* * Given an index i into an array of characters s[], * and assuming that index i is at the start of a UTF character, * determine the number of UCS characters up to that index i. */ size_t toUCSindex(in char[] s, size_t i) { size_t n; size_t j; for (j = 0; j < i; ) { j += stride(s, j); n++; } if (j > i) { onUnicodeError("invalid UTF-8 sequence", j); } return n; } /** ditto */ size_t toUCSindex(in wchar[] s, size_t i) { size_t n; size_t j; for (j = 0; j < i; ) { j += stride(s, j); n++; } if (j > i) { onUnicodeError("invalid UTF-16 sequence", j); } return n; } /** ditto */ size_t toUCSindex(in dchar[] s, size_t i) { return i; } /****************************************** * Given a UCS index n into an array of characters s[], return the UTF index. */ size_t toUTFindex(in char[] s, size_t n) { size_t i; while (n--) { uint j = UTF8stride[s[i]]; if (j == 0xFF) onUnicodeError("invalid UTF-8 sequence", i); i += j; } return i; } /** ditto */ size_t toUTFindex(in wchar[] s, size_t n) { size_t i; while (n--) { wchar u = s[i]; i += 1 + (u >= 0xD800 && u <= 0xDBFF); } return i; } /** ditto */ size_t toUTFindex(in dchar[] s, size_t n) { return n; } /* =================== Decode ======================= */ /*************** * Decodes and returns character starting at s[idx]. idx is advanced past the * decoded character. If the character is not well formed, a UtfException is * thrown and idx remains unchanged. */ dchar decode(in char[] s, ref size_t idx) in { assert(idx >= 0 && idx < s.length); } out (result) { assert(isValidDchar(result)); } body { size_t len = s.length; dchar V; size_t i = idx; char u = s[i]; if (u & 0x80) { uint n; char u2; /* The following encodings are valid, except for the 5 and 6 byte * combinations: * 0xxxxxxx * 110xxxxx 10xxxxxx * 1110xxxx 10xxxxxx 10xxxxxx * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx * 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx * 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx */ for (n = 1; ; n++) { if (n > 4) goto Lerr; // only do the first 4 of 6 encodings if (((u << n) & 0x80) == 0) { if (n == 1) goto Lerr; break; } } // Pick off (7 - n) significant bits of B from first byte of octet V = cast(dchar)(u & ((1 << (7 - n)) - 1)); if (i + (n - 1) >= len) goto Lerr; // off end of string /* The following combinations are overlong, and illegal: * 1100000x (10xxxxxx) * 11100000 100xxxxx (10xxxxxx) * 11110000 1000xxxx (10xxxxxx 10xxxxxx) * 11111000 10000xxx (10xxxxxx 10xxxxxx 10xxxxxx) * 11111100 100000xx (10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx) */ u2 = s[i + 1]; if ((u & 0xFE) == 0xC0 || (u == 0xE0 && (u2 & 0xE0) == 0x80) || (u == 0xF0 && (u2 & 0xF0) == 0x80) || (u == 0xF8 && (u2 & 0xF8) == 0x80) || (u == 0xFC && (u2 & 0xFC) == 0x80)) goto Lerr; // overlong combination for (uint j = 1; j != n; j++) { u = s[i + j]; if ((u & 0xC0) != 0x80) goto Lerr; // trailing bytes are 10xxxxxx V = (V << 6) | (u & 0x3F); } if (!isValidDchar(V)) goto Lerr; i += n; } else { V = cast(dchar) u; i++; } idx = i; return V; Lerr: onUnicodeError("invalid UTF-8 sequence", i); return V; // dummy return } unittest { size_t i; dchar c; debug(utf) printf("utf.decode.unittest\n"); static s1 = "abcd"c; i = 0; c = decode(s1, i); assert(c == cast(dchar)'a'); assert(i == 1); c = decode(s1, i); assert(c == cast(dchar)'b'); assert(i == 2); static s2 = "\xC2\xA9"c; i = 0; c = decode(s2, i); assert(c == cast(dchar)'\u00A9'); assert(i == 2); static s3 = "\xE2\x89\xA0"c; i = 0; c = decode(s3, i); assert(c == cast(dchar)'\u2260'); assert(i == 3); static s4 = [ "\xE2\x89"c[], // too short "\xC0\x8A", "\xE0\x80\x8A", "\xF0\x80\x80\x8A", "\xF8\x80\x80\x80\x8A", "\xFC\x80\x80\x80\x80\x8A", ]; for (int j = 0; j < s4.length; j++) { try { i = 0; c = decode(s4[j], i); assert(0); } catch (Throwable o) { i = 23; } assert(i == 23); } } /** ditto */ dchar decode(in wchar[] s, ref size_t idx) in { assert(idx >= 0 && idx < s.length); } out (result) { assert(isValidDchar(result)); } body { string msg; dchar V; size_t i = idx; uint u = s[i]; if (u & ~0x7F) { if (u >= 0xD800 && u <= 0xDBFF) { uint u2; if (i + 1 == s.length) { msg = "surrogate UTF-16 high value past end of string"; goto Lerr; } u2 = s[i + 1]; if (u2 < 0xDC00 || u2 > 0xDFFF) { msg = "surrogate UTF-16 low value out of range"; goto Lerr; } u = ((u - 0xD7C0) << 10) + (u2 - 0xDC00); i += 2; } else if (u >= 0xDC00 && u <= 0xDFFF) { msg = "unpaired surrogate UTF-16 value"; goto Lerr; } else if (u == 0xFFFE || u == 0xFFFF) { msg = "illegal UTF-16 value"; goto Lerr; } else i++; } else { i++; } idx = i; return cast(dchar)u; Lerr: onUnicodeError(msg, i); return cast(dchar)u; // dummy return } /** ditto */ dchar decode(in dchar[] s, ref size_t idx) in { assert(idx >= 0 && idx < s.length); } body { size_t i = idx; dchar c = s[i]; if (!isValidDchar(c)) goto Lerr; idx = i + 1; return c; Lerr: onUnicodeError("invalid UTF-32 value", i); return c; // dummy return } /* =================== Encode ======================= */ /******************************* * Encodes character c and appends it to array s[]. */ void encode(ref char[] s, dchar c) in { assert(isValidDchar(c)); } body { char[] r = s; if (c <= 0x7F) { r ~= cast(char) c; } else { char[4] buf; uint L; if (c <= 0x7FF) { buf[0] = cast(char)(0xC0 | (c >> 6)); buf[1] = cast(char)(0x80 | (c & 0x3F)); L = 2; } else if (c <= 0xFFFF) { buf[0] = cast(char)(0xE0 | (c >> 12)); buf[1] = cast(char)(0x80 | ((c >> 6) & 0x3F)); buf[2] = cast(char)(0x80 | (c & 0x3F)); L = 3; } else if (c <= 0x10FFFF) { buf[0] = cast(char)(0xF0 | (c >> 18)); buf[1] = cast(char)(0x80 | ((c >> 12) & 0x3F)); buf[2] = cast(char)(0x80 | ((c >> 6) & 0x3F)); buf[3] = cast(char)(0x80 | (c & 0x3F)); L = 4; } else { assert(0); } r ~= buf[0 .. L]; } s = r; } unittest { debug(utf) printf("utf.encode.unittest\n"); char[] s = "abcd".dup; encode(s, cast(dchar)'a'); assert(s.length == 5); assert(s == "abcda"); encode(s, cast(dchar)'\u00A9'); assert(s.length == 7); assert(s == "abcda\xC2\xA9"); //assert(s == "abcda\u00A9"); // BUG: fix compiler encode(s, cast(dchar)'\u2260'); assert(s.length == 10); assert(s == "abcda\xC2\xA9\xE2\x89\xA0"); } /** ditto */ void encode(ref wchar[] s, dchar c) in { assert(isValidDchar(c)); } body { wchar[] r = s; if (c <= 0xFFFF) { r ~= cast(wchar) c; } else { wchar[2] buf; buf[0] = cast(wchar) ((((c - 0x10000) >> 10) & 0x3FF) + 0xD800); buf[1] = cast(wchar) (((c - 0x10000) & 0x3FF) + 0xDC00); r ~= buf; } s = r; } /** ditto */ void encode(ref dchar[] s, dchar c) in { assert(isValidDchar(c)); } body { s ~= c; } /** Returns the code length of $(D c) in the encoding using $(D C) as a code point. The code is returned in character count, not in bytes. */ ubyte codeLength(C)(dchar c) { static if (C.sizeof == 1) { if (c <= 0x7F) return 1; if (c <= 0x7FF) return 2; if (c <= 0xFFFF) return 3; if (c <= 0x10FFFF) return 4; assert(false); } else static if (C.sizeof == 2) { return c <= 0xFFFF ? 1 : 2; } else { static assert(C.sizeof == 4); return 1; } } /* =================== Validation ======================= */ /*********************************** Checks to see if string is well formed or not. $(D S) can be an array of $(D char), $(D wchar), or $(D dchar). Throws a $(D UtfException) if it is not. Use to check all untrusted input for correctness. */ void validate(S)(in S s) { auto len = s.length; for (size_t i = 0; i < len; ) { decode(s, i); } } /* =================== Conversion to UTF8 ======================= */ char[] toUTF8(out char[4] buf, dchar c) in { assert(isValidDchar(c)); } body { if (c <= 0x7F) { buf[0] = cast(char) c; return buf[0 .. 1]; } else if (c <= 0x7FF) { buf[0] = cast(char)(0xC0 | (c >> 6)); buf[1] = cast(char)(0x80 | (c & 0x3F)); return buf[0 .. 2]; } else if (c <= 0xFFFF) { buf[0] = cast(char)(0xE0 | (c >> 12)); buf[1] = cast(char)(0x80 | ((c >> 6) & 0x3F)); buf[2] = cast(char)(0x80 | (c & 0x3F)); return buf[0 .. 3]; } else if (c <= 0x10FFFF) { buf[0] = cast(char)(0xF0 | (c >> 18)); buf[1] = cast(char)(0x80 | ((c >> 12) & 0x3F)); buf[2] = cast(char)(0x80 | ((c >> 6) & 0x3F)); buf[3] = cast(char)(0x80 | (c & 0x3F)); return buf[0 .. 4]; } assert(0); } /******************* * Encodes string s into UTF-8 and returns the encoded string. */ string toUTF8(string s) in { validate(s); } body { return s; } /** ditto */ string toUTF8(in wchar[] s) { char[] r; size_t i; size_t slen = s.length; r.length = slen; for (i = 0; i < slen; i++) { wchar c = s[i]; if (c <= 0x7F) r[i] = cast(char)c; // fast path for ascii else { r.length = i; foreach (dchar c; s[i .. slen]) { encode(r, c); } break; } } return cast(string)r; } /** ditto */ string toUTF8(in dchar[] s) { char[] r; size_t i; size_t slen = s.length; r.length = slen; for (i = 0; i < slen; i++) { dchar c = s[i]; if (c <= 0x7F) r[i] = cast(char)c; // fast path for ascii else { r.length = i; foreach (dchar d; s[i .. slen]) { encode(r, d); } break; } } return cast(string)r; } /* =================== Conversion to UTF16 ======================= */ wchar[] toUTF16(out wchar[2] buf, dchar c) in { assert(isValidDchar(c)); } body { if (c <= 0xFFFF) { buf[0] = cast(wchar) c; return buf[0 .. 1]; } else { buf[0] = cast(wchar) ((((c - 0x10000) >> 10) & 0x3FF) + 0xD800); buf[1] = cast(wchar) (((c - 0x10000) & 0x3FF) + 0xDC00); return buf[0 .. 2]; } } /**************** * Encodes string s into UTF-16 and returns the encoded string. * toUTF16z() is suitable for calling the 'W' functions in the Win32 API that take * an LPWSTR or LPCWSTR argument. */ wstring toUTF16(in char[] s) { wchar[] r; size_t slen = s.length; r.length = slen; r.length = 0; for (size_t i = 0; i < slen; ) { dchar c = s[i]; if (c <= 0x7F) { i++; r ~= cast(wchar)c; } else { c = decode(s, i); encode(r, c); } } return cast(wstring)r; } alias const(wchar)* wptr; /** ditto */ wptr toUTF16z(in char[] s) { wchar[] r; size_t slen = s.length; r.length = slen + 1; r.length = 0; for (size_t i = 0; i < slen; ) { dchar c = s[i]; if (c <= 0x7F) { i++; r ~= cast(wchar)c; } else { c = decode(s, i); encode(r, c); } } r ~= '\000'; return r.ptr; } /** ditto */ wstring toUTF16(wstring s) in { validate(s); } body { return s; } /** ditto */ wstring toUTF16(in dchar[] s) { wchar[] r; size_t slen = s.length; r.length = slen; r.length = 0; for (size_t i = 0; i < slen; i++) { encode(r, s[i]); } return cast(wstring)r; } /* =================== Conversion to UTF32 ======================= */ /***** * Encodes string s into UTF-32 and returns the encoded string. */ dstring toUTF32(in char[] s) { dchar[] r; size_t slen = s.length; size_t j = 0; r.length = slen; // r[] will never be longer than s[] for (size_t i = 0; i < slen; ) { dchar c = s[i]; if (c >= 0x80) c = decode(s, i); else i++; // c is ascii, no need for decode r[j++] = c; } return cast(dstring)r[0 .. j]; } /** ditto */ dstring toUTF32(in wchar[] s) { dchar[] r; size_t slen = s.length; size_t j = 0; r.length = slen; // r[] will never be longer than s[] for (size_t i = 0; i < slen; ) { dchar c = s[i]; if (c >= 0x80) c = decode(s, i); else i++; // c is ascii, no need for decode r[j++] = c; } return cast(dstring)r[0 .. j]; } /** ditto */ dstring toUTF32(dstring s) in { validate(s); } body { return s; } /* ================================ tests ================================== */ unittest { debug(utf) printf("utf.toUTF.unittest\n"); auto c = "hello"c[]; auto w = toUTF16(c); assert(w == "hello"); auto d = toUTF32(c); assert(d == "hello"); c = toUTF8(w); assert(c == "hello"); d = toUTF32(w); assert(d == "hello"); c = toUTF8(d); assert(c == "hello"); w = toUTF16(d); assert(w == "hello"); c = "hel\u1234o"; w = toUTF16(c); assert(w == "hel\u1234o"); d = toUTF32(c); assert(d == "hel\u1234o"); c = toUTF8(w); assert(c == "hel\u1234o"); d = toUTF32(w); assert(d == "hel\u1234o"); c = toUTF8(d); assert(c == "hel\u1234o"); w = toUTF16(d); assert(w == "hel\u1234o"); c = "he\U000BAAAAllo"; w = toUTF16(c); //foreach (wchar c; w) printf("c = x%x\n", c); //foreach (wchar c; cast(wstring)"he\U000BAAAAllo") printf("c = x%x\n", c); assert(w == "he\U000BAAAAllo"); d = toUTF32(c); assert(d == "he\U000BAAAAllo"); c = toUTF8(w); assert(c == "he\U000BAAAAllo"); d = toUTF32(w); assert(d == "he\U000BAAAAllo"); c = toUTF8(d); assert(c == "he\U000BAAAAllo"); w = toUTF16(d); assert(w == "he\U000BAAAAllo"); wchar[2] buf; auto ret = toUTF16(buf, '\U000BAAAA'); assert(ret == "\U000BAAAA"); }
D
the fluid (red in vertebrates) that is pumped through the body by the heart and contains plasma, blood cells, and platelets temperament or disposition a dissolute man in fashionable society the descendants of one individual people viewed as members of a group smear with blood, as in a hunting initiation rite, where the face of a person is smeared with the blood of the kill
D
$NetBSD$ Stolen from https://github.com/nrTQgc/druntime/tree/netbsd --- runtime/druntime/src/core/sys/posix/fcntl.d.orig 2020-05-07 08:52:15.234684078 +0000 +++ runtime/druntime/src/core/sys/posix/fcntl.d @@ -462,6 +462,59 @@ else version( DragonFlyBSD ) //int fcntl(int, int, ...); /*defined below*/ //int flock(int, int); } +else version( NetBSD ) +{ + enum F_DUPFD = 0; + enum F_GETFD = 1; + enum F_SETFD = 2; + enum F_GETFL = 3; + enum F_SETFL = 4; + enum F_GETOWN = 5; + enum F_SETOWN = 6; + enum F_GETLK = 7; + enum F_SETLK = 8; + enum F_SETLKW = 9; + enum F_CLOSEM = 10; + enum F_MAXFD = 11; + enum F_DUPFD_CLOEXEC= 12; + enum F_GETNOSIGPIPE = 13; + enum F_SETNOSIGPIPE = 14; + + enum FD_CLOEXEC = 1; + + enum F_RDLCK = 1; + enum F_UNLCK = 2; + enum F_WRLCK = 3; + + enum O_CREAT = 0x0200; + enum O_EXCL = 0x0800; + enum O_NOCTTY = 0x8000; + enum O_TRUNC = 0x0400; + + enum O_RDONLY = 0x0000; + enum O_WRONLY = 0x0001; + enum O_RDWR = 0x0002; + enum O_ACCMODE = 0x0003; + + enum O_NONBLOCK = 0x0004; + enum O_APPEND = 0x0008; + enum O_SYNC = 0x0080; + //enum O_DSYNC + //enum O_RSYNC + + struct flock + { + off_t l_start; + off_t l_len; + pid_t l_pid; + short l_type; + short l_whence; + } + + + int creat(in char*, mode_t); + int open(in char*, int, ...); +} else version (Solaris) { enum F_DUPFD = 0;
D
import mysql.common; import mysql.connection; import mysql.result; import mysql.db; import std.stdio; ulong testExce(Connection cn,string sql){ auto cmd = Command(cn); cmd.sql = sql; ulong rowsAffected; cmd.execSQL(rowsAffected); return rowsAffected; } ResultSet testRows()(Connection cn, string sql) { auto cmd = Command(cn); cmd.sql = sql; return cmd.execSQLResult(); } void testMysql(){ string connStr = "host=localhost;port=3306;user=root;pwd=123456;db=test"; auto mdb = new MysqlDB(connStr); auto con = mdb.lockConnection(); scope(exit) con.close(); //测试增删改查 //add auto addSql = "insert into country(name,user_age,id)values('helloworld',59,1)"; writeln("add data is ", testExce(con,addSql)); //update auto updateSql = "update country set name = 'helloworld' where id=1 limit 1"; writeln("update data is ", testExce(con,updateSql)); //delte auto delSql = "delete from country where id=1 limit 1"; writeln("delete data is ", testExce(con,delSql)); //select auto selSql = "select name,user_age,id from country"; ResultSet rs = testRows(con,selSql); int i; auto keys = ["name","user_age","id"]; for(i=0;i<rs.length;i++){ foreach(k,v;keys){ writef("%s:%s",v,rs[i][k]); } writeln(""); } writeln(rs[0],rs[0][0],rs[0][1]); } int main(char[][] args) { testMysql(); return 0; }
D
/** SDL format support for PackageRecipe Copyright: © 2014-2015 rejectedsoftware e.K. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. Authors: Sönke Ludwig */ module dub.recipe.sdl; import dub.compilers.compiler; import dub.dependency; import dub.internal.sdlang; import dub.internal.vibecompat.core.log; import dub.internal.vibecompat.inet.path; import dub.recipe.packagerecipe; import std.algorithm : map; import std.array : array; import std.conv; import std.string : startsWith; void parseSDL(ref PackageRecipe recipe, string sdl, string parent_name, string filename) { parseSDL(recipe, parseSource(sdl, filename), parent_name); } void parseSDL(ref PackageRecipe recipe, Tag sdl, string parent_name) { Tag[] subpacks; Tag[] configs; // parse top-level fields foreach (n; sdl.all.tags) { enforceSDL(n.name.length > 0, "Anonymous tags are not allowed at the root level.", n); switch (n.fullName) { default: break; case "name": recipe.name = n.stringTagValue; break; case "version": recipe.version_ = n.stringTagValue; break; case "description": recipe.description = n.stringTagValue; break; case "homepage": recipe.homepage = n.stringTagValue; break; case "authors": recipe.authors ~= n.stringArrayTagValue; break; case "copyright": recipe.copyright = n.stringTagValue; break; case "license": recipe.license = n.stringTagValue; break; case "subPackage": subpacks ~= n; break; case "configuration": configs ~= n; break; case "buildType": auto name = n.stringTagValue(true); BuildSettingsTemplate bt; parseBuildSettings(n, bt, parent_name); recipe.buildTypes[name] = bt; break; case "x:ddoxFilterArgs": recipe.ddoxFilterArgs ~= n.stringArrayTagValue; break; case "x:ddoxTool": recipe.ddoxTool = n.stringTagValue; break; } } enforceSDL(recipe.name.length > 0, "The package \"name\" field is missing or empty.", sdl); string full_name = parent_name.length ? parent_name ~ ":" ~ recipe.name : recipe.name; // parse general build settings parseBuildSettings(sdl, recipe.buildSettings, full_name); // determine default target type for configurations auto defttype = recipe.buildSettings.targetType; if (defttype == TargetType.autodetect) defttype = TargetType.library; // parse configurations recipe.configurations.length = configs.length; foreach (i, n; configs) { recipe.configurations[i].buildSettings.targetType = defttype; parseConfiguration(n, recipe.configurations[i], full_name); } // finally parse all sub packages recipe.subPackages.length = subpacks.length; foreach (i, n; subpacks) { if (n.values.length) { recipe.subPackages[i].path = n.stringTagValue; } else { enforceSDL(n.attributes.length == 0, "No attributes allowed for inline sub package definitions.", n); parseSDL(recipe.subPackages[i].recipe, n, full_name); } } } Tag toSDL(in ref PackageRecipe recipe) { Tag ret = new Tag; void add(T)(string field, T value) { ret.add(new Tag(null, field, [Value(value)])); } add("name", recipe.name); if (recipe.version_.length) add("version", recipe.version_); if (recipe.description.length) add("description", recipe.description); if (recipe.homepage.length) add("homepage", recipe.homepage); if (recipe.authors.length) ret.add(new Tag(null, "authors", recipe.authors.map!(a => Value(a)).array)); if (recipe.copyright.length) add("copyright", recipe.copyright); if (recipe.license.length) add("license", recipe.license); foreach (name, settings; recipe.buildTypes) { auto t = new Tag(null, "buildType", [Value(name)]); t.add(settings.toSDL()); ret.add(t); } if (recipe.ddoxFilterArgs.length) ret.add(new Tag("x", "ddoxFilterArgs", recipe.ddoxFilterArgs.map!(a => Value(a)).array)); if (recipe.ddoxTool.length) ret.add(new Tag("x", "ddoxTool", [Value(recipe.ddoxTool)])); ret.add(recipe.buildSettings.toSDL()); foreach(config; recipe.configurations) ret.add(config.toSDL()); foreach (i, subPackage; recipe.subPackages) { if (subPackage.path !is null) { add("subPackage", subPackage.path); } else { auto t = subPackage.recipe.toSDL(); t.name = "subPackage"; ret.add(t); } } return ret; } private void parseBuildSettings(Tag settings, ref BuildSettingsTemplate bs, string package_name) { foreach (setting; settings.all.tags) parseBuildSetting(setting, bs, package_name); } private void parseBuildSetting(Tag setting, ref BuildSettingsTemplate bs, string package_name) { switch (setting.fullName) { default: break; case "dependency": parseDependency(setting, bs, package_name); break; case "systemDependencies": bs.systemDependencies = setting.stringTagValue; break; case "targetType": bs.targetType = setting.stringTagValue.to!TargetType; break; case "targetName": bs.targetName = setting.stringTagValue; break; case "targetPath": bs.targetPath = setting.stringTagValue; break; case "workingDirectory": bs.workingDirectory = setting.stringTagValue; break; case "subConfiguration": auto args = setting.stringArrayTagValue; enforceSDL(args.length == 2, "Expecting package and configuration names as arguments.", setting); bs.subConfigurations[expandPackageName(args[0], package_name, setting)] = args[1]; break; case "dflags": setting.parsePlatformStringArray(bs.dflags); break; case "lflags": setting.parsePlatformStringArray(bs.lflags); break; case "libs": setting.parsePlatformStringArray(bs.libs); break; case "sourceFiles": setting.parsePlatformStringArray(bs.sourceFiles); break; case "sourcePaths": setting.parsePlatformStringArray(bs.sourcePaths); break; case "excludedSourceFiles": setting.parsePlatformStringArray(bs.excludedSourceFiles); break; case "mainSourceFile": bs.mainSourceFile = setting.stringTagValue; break; case "copyFiles": setting.parsePlatformStringArray(bs.copyFiles); break; case "versions": setting.parsePlatformStringArray(bs.versions); break; case "debugVersions": setting.parsePlatformStringArray(bs.debugVersions); break; case "x:versionFilters": setting.parsePlatformStringArray(bs.versionFilters); break; case "x:debugVersionFilters": setting.parsePlatformStringArray(bs.debugVersionFilters); break; case "importPaths": setting.parsePlatformStringArray(bs.importPaths); break; case "stringImportPaths": setting.parsePlatformStringArray(bs.stringImportPaths); break; case "preGenerateCommands": setting.parsePlatformStringArray(bs.preGenerateCommands); break; case "postGenerateCommands": setting.parsePlatformStringArray(bs.postGenerateCommands); break; case "preBuildCommands": setting.parsePlatformStringArray(bs.preBuildCommands); break; case "postBuildCommands": setting.parsePlatformStringArray(bs.postBuildCommands); break; case "preRunCommands": setting.parsePlatformStringArray(bs.preRunCommands); break; case "postRunCommands": setting.parsePlatformStringArray(bs.postRunCommands); break; case "buildRequirements": setting.parsePlatformEnumArray!BuildRequirement(bs.buildRequirements); break; case "buildOptions": setting.parsePlatformEnumArray!BuildOption(bs.buildOptions); break; } } private void parseDependency(Tag t, ref BuildSettingsTemplate bs, string package_name) { enforceSDL(t.values.length != 0, "Missing dependency name.", t); enforceSDL(t.values.length == 1, "Multiple dependency names.", t); auto pkg = expandPackageName(t.values[0].get!string, package_name, t); enforceSDL(pkg !in bs.dependencies, "The dependency '"~pkg~"' is specified more than once.", t); Dependency dep = Dependency.any; auto attrs = t.attributes; auto pv = "version" in attrs; if ("path" in attrs) { if ("version" in attrs) logDiagnostic("Ignoring version specification (%s) for path based dependency %s", attrs["version"][0].value.get!string, attrs["path"][0].value.get!string); dep.versionSpec = "*"; dep.path = NativePath(attrs["path"][0].value.get!string); } else { enforceSDL("version" in attrs, "Missing version specification.", t); dep.versionSpec = attrs["version"][0].value.get!string; } if ("optional" in attrs) dep.optional = attrs["optional"][0].value.get!bool; if ("default" in attrs) dep.default_ = attrs["default"][0].value.get!bool; bs.dependencies[pkg] = dep; } private void parseConfiguration(Tag t, ref ConfigurationInfo ret, string package_name) { ret.name = t.stringTagValue(true); foreach (f; t.tags) { switch (f.fullName) { default: parseBuildSetting(f, ret.buildSettings, package_name); break; case "platforms": ret.platforms ~= f.stringArrayTagValue; break; } } } private Tag toSDL(in ref ConfigurationInfo config) { auto ret = new Tag(null, "configuration", [Value(config.name)]); if (config.platforms.length) ret.add(new Tag(null, "platforms", config.platforms[].map!(p => Value(p)).array)); ret.add(config.buildSettings.toSDL()); return ret; } private Tag[] toSDL(in ref BuildSettingsTemplate bs) { Tag[] ret; void add(string name, string value, string namespace = null) { ret ~= new Tag(namespace, name, [Value(value)]); } void adda(string name, string suffix, in string[] values, string namespace = null) { ret ~= new Tag(namespace, name, values[].map!(v => Value(v)).array, suffix.length ? [new Attribute(null, "platform", Value(suffix[1 .. $]))] : null); } string[] toNameArray(T, U)(U bits) if(is(T == enum)) { string[] ret; foreach (m; __traits(allMembers, T)) if (bits & __traits(getMember, T, m)) ret ~= m; return ret; } foreach (pack, d; bs.dependencies) { Attribute[] attribs; if (!d.path.empty) attribs ~= new Attribute(null, "path", Value(d.path.toString())); else attribs ~= new Attribute(null, "version", Value(d.versionSpec)); if (d.optional) attribs ~= new Attribute(null, "optional", Value(true)); ret ~= new Tag(null, "dependency", [Value(pack)], attribs); } if (bs.systemDependencies !is null) add("systemDependencies", bs.systemDependencies); if (bs.targetType != TargetType.autodetect) add("targetType", bs.targetType.to!string()); if (bs.targetPath.length) add("targetPath", bs.targetPath); if (bs.targetName.length) add("targetName", bs.targetName); if (bs.workingDirectory.length) add("workingDirectory", bs.workingDirectory); if (bs.mainSourceFile.length) add("mainSourceFile", bs.mainSourceFile); foreach (pack, conf; bs.subConfigurations) ret ~= new Tag(null, "subConfiguration", [Value(pack), Value(conf)]); foreach (suffix, arr; bs.dflags) adda("dflags", suffix, arr); foreach (suffix, arr; bs.lflags) adda("lflags", suffix, arr); foreach (suffix, arr; bs.libs) adda("libs", suffix, arr); foreach (suffix, arr; bs.sourceFiles) adda("sourceFiles", suffix, arr); foreach (suffix, arr; bs.sourcePaths) adda("sourcePaths", suffix, arr); foreach (suffix, arr; bs.excludedSourceFiles) adda("excludedSourceFiles", suffix, arr); foreach (suffix, arr; bs.copyFiles) adda("copyFiles", suffix, arr); foreach (suffix, arr; bs.versions) adda("versions", suffix, arr); foreach (suffix, arr; bs.debugVersions) adda("debugVersions", suffix, arr); foreach (suffix, arr; bs.versionFilters) adda("versionFilters", suffix, arr, "x"); foreach (suffix, arr; bs.debugVersionFilters) adda("debugVersionFilters", suffix, arr, "x"); foreach (suffix, arr; bs.importPaths) adda("importPaths", suffix, arr); foreach (suffix, arr; bs.stringImportPaths) adda("stringImportPaths", suffix, arr); foreach (suffix, arr; bs.preGenerateCommands) adda("preGenerateCommands", suffix, arr); foreach (suffix, arr; bs.postGenerateCommands) adda("postGenerateCommands", suffix, arr); foreach (suffix, arr; bs.preBuildCommands) adda("preBuildCommands", suffix, arr); foreach (suffix, arr; bs.postBuildCommands) adda("postBuildCommands", suffix, arr); foreach (suffix, arr; bs.preRunCommands) adda("preRunCommands", suffix, arr); foreach (suffix, arr; bs.postRunCommands) adda("postRunCommands", suffix, arr); foreach (suffix, bits; bs.buildRequirements) adda("buildRequirements", suffix, toNameArray!BuildRequirement(bits)); foreach (suffix, bits; bs.buildOptions) adda("buildOptions", suffix, toNameArray!BuildOption(bits)); return ret; } private string expandPackageName(string name, string parent_name, Tag tag) { import std.algorithm : canFind; import std.string : format; if (name.startsWith(":")) { enforceSDL(!parent_name.canFind(':'), format("Short-hand packages syntax not allowed within sub packages: %s -> %s", parent_name, name), tag); return parent_name ~ name; } else return name; } private string stringTagValue(Tag t, bool allow_child_tags = false) { import std.string : format; enforceSDL(t.values.length > 0, format("Missing string value for '%s'.", t.fullName), t); enforceSDL(t.values.length == 1, format("Expected only one value for '%s'.", t.fullName), t); enforceSDL(t.values[0].peek!string !is null, format("Expected value of type string for '%s'.", t.fullName), t); enforceSDL(allow_child_tags || t.tags.length == 0, format("No child tags allowed for '%s'.", t.fullName), t); // Q: should attributes be disallowed, or just ignored for forward compatibility reasons? //enforceSDL(t.attributes.length == 0, format("No attributes allowed for '%s'.", t.fullName), t); return t.values[0].get!string; } private string[] stringArrayTagValue(Tag t, bool allow_child_tags = false) { import std.string : format; enforceSDL(allow_child_tags || t.tags.length == 0, format("No child tags allowed for '%s'.", t.fullName), t); // Q: should attributes be disallowed, or just ignored for forward compatibility reasons? //enforceSDL(t.attributes.length == 0, format("No attributes allowed for '%s'.", t.fullName), t); string[] ret; foreach (v; t.values) { enforceSDL(t.values[0].peek!string !is null, format("Values for '%s' must be strings.", t.fullName), t); ret ~= v.get!string; } return ret; } private void parsePlatformStringArray(Tag t, ref string[][string] dst) { string platform; if ("platform" in t.attributes) platform = "-" ~ t.attributes["platform"][0].value.get!string; dst[platform] ~= t.values.map!(v => v.get!string).array; } private void parsePlatformEnumArray(E, Es)(Tag t, ref Es[string] dst) { string platform; if ("platform" in t.attributes) platform = "-" ~ t.attributes["platform"][0].value.get!string; foreach (v; t.values) { if (platform !in dst) dst[platform] = Es.init; dst[platform] |= v.get!string.to!E; } } private void enforceSDL(bool condition, lazy string message, Tag tag, string file = __FILE__, int line = __LINE__) { import std.string : format; if (!condition) { throw new Exception(format("%s(%s): Error: %s", tag.location.file, tag.location.line, message), file, line); } } unittest { // test all possible fields auto sdl = `name "projectname"; description "project description"; homepage "http://example.com" authors "author 1" "author 2" authors "author 3" copyright "copyright string" license "license string" version "1.0.0" subPackage { name "subpackage1" } subPackage { name "subpackage2" dependency "projectname:subpackage1" version="*" } subPackage "pathsp3" configuration "config1" { platforms "windows" "linux" targetType "library" } configuration "config2" { platforms "windows-x86" targetType "executable" } buildType "debug" { dflags "-g" "-debug" } buildType "release" { dflags "-release" "-O" } x:ddoxFilterArgs "-arg1" "-arg2" x:ddoxFilterArgs "-arg3" x:ddoxTool "ddoxtool" dependency ":subpackage1" optional=false path="." dependency "somedep" version="1.0.0" optional=true systemDependencies "system dependencies" targetType "executable" targetName "target name" targetPath "target path" workingDirectory "working directory" subConfiguration ":subpackage2" "library" buildRequirements "allowWarnings" "silenceDeprecations" buildOptions "verbose" "ignoreUnknownPragmas" libs "lib1" "lib2" libs "lib3" sourceFiles "source1" "source2" sourceFiles "source3" sourcePaths "sourcepath1" "sourcepath2" sourcePaths "sourcepath3" excludedSourceFiles "excluded1" "excluded2" excludedSourceFiles "excluded3" mainSourceFile "main source" copyFiles "copy1" "copy2" copyFiles "copy3" versions "version1" "version2" versions "version3" debugVersions "debug1" "debug2" debugVersions "debug3" x:versionFilters "version1" "version2" x:versionFilters "version3" x:versionFilters x:debugVersionFilters "debug1" "debug2" x:debugVersionFilters "debug3" x:debugVersionFilters importPaths "import1" "import2" importPaths "import3" stringImportPaths "string1" "string2" stringImportPaths "string3" preGenerateCommands "preg1" "preg2" preGenerateCommands "preg3" postGenerateCommands "postg1" "postg2" postGenerateCommands "postg3" preBuildCommands "preb1" "preb2" preBuildCommands "preb3" postBuildCommands "postb1" "postb2" postBuildCommands "postb3" preRunCommands "prer1" "prer2" preRunCommands "prer3" postRunCommands "postr1" "postr2" postRunCommands "postr3" dflags "df1" "df2" dflags "df3" lflags "lf1" "lf2" lflags "lf3" `; PackageRecipe rec1; parseSDL(rec1, sdl, null, "testfile"); PackageRecipe rec; parseSDL(rec, rec1.toSDL(), null); // verify that all fields are serialized properly assert(rec.name == "projectname"); assert(rec.description == "project description"); assert(rec.homepage == "http://example.com"); assert(rec.authors == ["author 1", "author 2", "author 3"]); assert(rec.copyright == "copyright string"); assert(rec.license == "license string"); assert(rec.version_ == "1.0.0"); assert(rec.subPackages.length == 3); assert(rec.subPackages[0].path == ""); assert(rec.subPackages[0].recipe.name == "subpackage1"); assert(rec.subPackages[1].path == ""); assert(rec.subPackages[1].recipe.name == "subpackage2"); assert(rec.subPackages[1].recipe.buildSettings.dependencies.length == 1); assert("projectname:subpackage1" in rec.subPackages[1].recipe.buildSettings.dependencies); assert(rec.subPackages[2].path == "pathsp3"); assert(rec.configurations.length == 2); assert(rec.configurations[0].name == "config1"); assert(rec.configurations[0].platforms == ["windows", "linux"]); assert(rec.configurations[0].buildSettings.targetType == TargetType.library); assert(rec.configurations[1].name == "config2"); assert(rec.configurations[1].platforms == ["windows-x86"]); assert(rec.configurations[1].buildSettings.targetType == TargetType.executable); assert(rec.buildTypes.length == 2); assert(rec.buildTypes["debug"].dflags == ["": ["-g", "-debug"]]); assert(rec.buildTypes["release"].dflags == ["": ["-release", "-O"]]); assert(rec.ddoxFilterArgs == ["-arg1", "-arg2", "-arg3"], rec.ddoxFilterArgs.to!string); assert(rec.ddoxTool == "ddoxtool"); assert(rec.buildSettings.dependencies.length == 2); assert(rec.buildSettings.dependencies["projectname:subpackage1"].optional == false); assert(rec.buildSettings.dependencies["projectname:subpackage1"].path == NativePath(".")); assert(rec.buildSettings.dependencies["somedep"].versionSpec == "1.0.0"); assert(rec.buildSettings.dependencies["somedep"].optional == true); assert(rec.buildSettings.dependencies["somedep"].path.empty); assert(rec.buildSettings.systemDependencies == "system dependencies"); assert(rec.buildSettings.targetType == TargetType.executable); assert(rec.buildSettings.targetName == "target name"); assert(rec.buildSettings.targetPath == "target path"); assert(rec.buildSettings.workingDirectory == "working directory"); assert(rec.buildSettings.subConfigurations.length == 1); assert(rec.buildSettings.subConfigurations["projectname:subpackage2"] == "library"); assert(rec.buildSettings.buildRequirements == ["": cast(BuildRequirements)(BuildRequirement.allowWarnings | BuildRequirement.silenceDeprecations)]); assert(rec.buildSettings.buildOptions == ["": cast(BuildOptions)(BuildOption.verbose | BuildOption.ignoreUnknownPragmas)]); assert(rec.buildSettings.libs == ["": ["lib1", "lib2", "lib3"]]); assert(rec.buildSettings.sourceFiles == ["": ["source1", "source2", "source3"]]); assert(rec.buildSettings.sourcePaths == ["": ["sourcepath1", "sourcepath2", "sourcepath3"]]); assert(rec.buildSettings.excludedSourceFiles == ["": ["excluded1", "excluded2", "excluded3"]]); assert(rec.buildSettings.mainSourceFile == "main source"); assert(rec.buildSettings.copyFiles == ["": ["copy1", "copy2", "copy3"]]); assert(rec.buildSettings.versions == ["": ["version1", "version2", "version3"]]); assert(rec.buildSettings.debugVersions == ["": ["debug1", "debug2", "debug3"]]); assert(rec.buildSettings.versionFilters == ["": ["version1", "version2", "version3"]]); assert(rec.buildSettings.debugVersionFilters == ["": ["debug1", "debug2", "debug3"]]); assert(rec.buildSettings.importPaths == ["": ["import1", "import2", "import3"]]); assert(rec.buildSettings.stringImportPaths == ["": ["string1", "string2", "string3"]]); assert(rec.buildSettings.preGenerateCommands == ["": ["preg1", "preg2", "preg3"]]); assert(rec.buildSettings.postGenerateCommands == ["": ["postg1", "postg2", "postg3"]]); assert(rec.buildSettings.preBuildCommands == ["": ["preb1", "preb2", "preb3"]]); assert(rec.buildSettings.postBuildCommands == ["": ["postb1", "postb2", "postb3"]]); assert(rec.buildSettings.preRunCommands == ["": ["prer1", "prer2", "prer3"]]); assert(rec.buildSettings.postRunCommands == ["": ["postr1", "postr2", "postr3"]]); assert(rec.buildSettings.dflags == ["": ["df1", "df2", "df3"]]); assert(rec.buildSettings.lflags == ["": ["lf1", "lf2", "lf3"]]); } unittest { // test platform identifiers auto sdl = `name "testproject" dflags "-a" "-b" platform="windows-x86" dflags "-c" platform="windows-x86" dflags "-e" "-f" dflags "-g" dflags "-h" "-i" platform="linux" dflags "-j" platform="linux" `; PackageRecipe rec; parseSDL(rec, sdl, null, "testfile"); assert(rec.buildSettings.dflags.length == 3); assert(rec.buildSettings.dflags["-windows-x86"] == ["-a", "-b", "-c"]); assert(rec.buildSettings.dflags[""] == ["-e", "-f", "-g"]); assert(rec.buildSettings.dflags["-linux"] == ["-h", "-i", "-j"]); } unittest { // test for missing name field import std.exception; auto sdl = `description "missing name"`; PackageRecipe rec; assertThrown(parseSDL(rec, sdl, null, "testfile")); } unittest { // test single value fields import std.exception; PackageRecipe rec; assertThrown!Exception(parseSDL(rec, `name "hello" "world"`, null, "testfile")); assertThrown!Exception(parseSDL(rec, `name`, null, "testfile")); assertThrown!Exception(parseSDL(rec, `name 10`, null, "testfile")); assertThrown!Exception(parseSDL(rec, `name "hello" { world }`, null, "testfile")); assertThrown!Exception(parseSDL(rec, `name "" versions "hello" 10` , null, "testfile")); } unittest { // test basic serialization PackageRecipe p; p.name = "test"; p.authors = ["foo", "bar"]; p.buildSettings.dflags["-windows"] = ["-a"]; p.buildSettings.lflags[""] = ["-b", "-c"]; auto sdl = toSDL(p).toSDLDocument(); assert(sdl == `name "test" authors "foo" "bar" dflags "-a" platform="windows" lflags "-b" "-c" `); } unittest { auto sdl = "name \"test\"\nsourcePaths"; PackageRecipe rec; parseSDL(rec, sdl, null, "testfile"); assert("" in rec.buildSettings.sourcePaths); }
D
/*===-- llvm-c/TargetMachine.h - Target Machine Library C Interface - C++ -*-=*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This header declares the C interface to the Target and TargetMachine *| |* classes, which can be used to generate assembly or object files. *| |* *| |* Many exotic languages can interoperate with C code but have a harder time *| |* with C++ due to name mangling. So in addition to C, this interface enables *| |* tools written in such languages. *| |* *| \*===----------------------------------------------------------------------===*/ module llvm.c.targetMachine; import llvm.c.core; import llvm.c.target; extern(C) nothrow: struct __LLVMOpaqueTargetMachine {}; alias LLVMTargetMachineRef = __LLVMOpaqueTargetMachine*; struct __LLVMTarget {}; alias LLVMTargetRef = __LLVMTarget*; enum LLVMCodeGenOptLevel { None, Less, Default, Aggressive } enum LLVMRelocMode { Default, Static, PIC, DynamicNoPic } enum LLVMCodeModel { Default, JITDefault, Small, Kernel, Medium, Large } enum LLVMCodeGenFileType { Assembly, Object } /** Returns the first llvm::Target in the registered targets list. */ LLVMTargetRef LLVMGetFirstTarget(); /** Returns the next llvm::Target given a previous one (or null if there's none) */ LLVMTargetRef LLVMGetNextTarget(LLVMTargetRef T); /*===-- Target ------------------------------------------------------------===*/ /** Finds the target corresponding to the given name and stores it in \p T. Returns 0 on success. */ LLVMTargetRef LLVMGetTargetFromName(const(char)* Name); /** Finds the target corresponding to the given triple and stores it in \p T. Returns 0 on success. Optionally returns any error in ErrorMessage. Use LLVMDisposeMessage to dispose the message. */ LLVMBool LLVMGetTargetFromTriple(const(char)* Triple, LLVMTargetRef* T, char** ErrorMessage); /** Returns the name of a target. See llvm::Target::getName */ const(char)* LLVMGetTargetName(LLVMTargetRef T); /** Returns the description of a target. See llvm::Target::getDescription */ const(char)* LLVMGetTargetDescription(LLVMTargetRef T); /** Returns if the target has a JIT */ LLVMBool LLVMTargetHasJIT(LLVMTargetRef T); /** Returns if the target has a TargetMachine associated */ LLVMBool LLVMTargetHasTargetMachine(LLVMTargetRef T); /** Returns if the target as an ASM backend (required for emitting output) */ LLVMBool LLVMTargetHasAsmBackend(LLVMTargetRef T); /*===-- Target Machine ----------------------------------------------------===*/ /** Creates a new llvm::TargetMachine. See llvm::Target::createTargetMachine */ LLVMTargetMachineRef LLVMCreateTargetMachine(LLVMTargetRef T, const(char)* Triple, const(char)* CPU, const(char)* Features, LLVMCodeGenOptLevel Level, LLVMRelocMode Reloc, LLVMCodeModel CodeModel); /** Dispose the LLVMTargetMachineRef instance generated by LLVMCreateTargetMachine. */ void LLVMDisposeTargetMachine(LLVMTargetMachineRef T); /** Returns the Target used in a TargetMachine */ LLVMTargetRef LLVMGetTargetMachineTarget(LLVMTargetMachineRef T); /** Returns the triple used creating this target machine. See llvm::TargetMachine::getTriple. The result needs to be disposed with LLVMDisposeMessage. */ char *LLVMGetTargetMachineTriple(LLVMTargetMachineRef T); /** Returns the cpu used creating this target machine. See llvm::TargetMachine::getCPU. The result needs to be disposed with LLVMDisposeMessage. */ char *LLVMGetTargetMachineCPU(LLVMTargetMachineRef T); /** Returns the feature string used creating this target machine. See llvm::TargetMachine::getFeatureString. The result needs to be disposed with LLVMDisposeMessage. */ char *LLVMGetTargetMachineFeatureString(LLVMTargetMachineRef T); /** Returns the llvm::DataLayout used for this llvm:TargetMachine. */ LLVMTargetDataRef LLVMGetTargetMachineData(LLVMTargetMachineRef T); /** Set the target machine's ASM verbosity. */ void LLVMSetTargetMachineAsmVerbosity(LLVMTargetMachineRef T, LLVMBool VerboseAsm); /** Emits an asm or object file for the given module to the filename. This wraps several c++ only classes (among them a file stream). Returns any error in ErrorMessage. Use LLVMDisposeMessage to dispose the message. */ LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M, const(char)* Filename, LLVMCodeGenFileType codegen, char** ErrorMessage); /** Compile the LLVM IR stored in \p M and store the result in \p OutMemBuf. */ LLVMBool LLVMTargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef T, LLVMModuleRef M, LLVMCodeGenFileType codegen, char** ErrorMessage, LLVMMemoryBufferRef* OutMemBuf); /*===-- Triple ------------------------------------------------------------===*/ /** Get a triple for the host machine as a string. The result needs to be disposed with LLVMDisposeMessage. */ char* LLVMGetDefaultTargetTriple(); /** Adds the target-specific analysis passes to the pass manager. */ void LLVMAddAnalysisPasses(LLVMTargetMachineRef T, LLVMPassManagerRef PM);
D
/* * #17 Jackal doesn't recognize the player's camp membership * * The hero is given a new guild and the condition function of the dialog is called. * * Expected behavior: The condition function will return FALSE. */ func int G1CP_Test_017() { // Check if dialog exists var int funcId; funcId = MEM_GetSymbolIndex("Info_Jackal_Hello_Condition"); if (funcId == -1) { G1CP_TestsuiteErrorDetail("Dialog condition 'Info_Jackal_Hello_Condition' not found"); return FALSE; }; // Backup the original guild var int guildBak; guildBak = Npc_GetTrueGuild(hero); // Assign a random guild Npc_SetTrueGuild(hero, 4); // Backup self and other var C_Npc slfBak; slfBak = MEM_CpyInst(self); var C_Npc othBak; othBak = MEM_CpyInst(other); // Set self and other self = MEM_CpyInst(hero); other = MEM_CpyInst(hero); // Call dialog condition function MEM_CallByID(funcId); var int ret; ret = MEM_PopIntResult(); // Restore self and other self = MEM_CpyInst(slfBak); other = MEM_CpyInst(othBak); // Restore guild Npc_SetTrueGuild(hero, guildBak); // Check return value if (ret) { G1CP_TestsuiteErrorDetail("Dialog condition failed"); return FALSE; } else { return TRUE; }; };
D
module UnrealScript.TribesGame.GFxTrPage_VideoGraphics; import ScriptClasses; import UnrealScript.Helpers; import UnrealScript.TribesGame.GFxTrAction; import UnrealScript.TribesGame.GFxTrPage; import UnrealScript.GFxUI.GFxObject; extern(C++) interface GFxTrPage_VideoGraphics : GFxTrPage { public extern(D): private static __gshared ScriptClass mStaticClass; @property final static ScriptClass StaticClass() { mixin(MGSCC("Class TribesGame.GFxTrPage_VideoGraphics")); } private static __gshared GFxTrPage_VideoGraphics mDefaultProperties; @property final static GFxTrPage_VideoGraphics DefaultProperties() { mixin(MGDPC("GFxTrPage_VideoGraphics", "GFxTrPage_VideoGraphics TribesGame.Default__GFxTrPage_VideoGraphics")); } static struct Functions { private static __gshared { ScriptFunction mInitialize; ScriptFunction mFillData; ScriptFunction mSpecialAction; ScriptFunction mFillOption; } public @property static final { ScriptFunction Initialize() { mixin(MGF("mInitialize", "Function TribesGame.GFxTrPage_VideoGraphics.Initialize")); } ScriptFunction FillData() { mixin(MGF("mFillData", "Function TribesGame.GFxTrPage_VideoGraphics.FillData")); } ScriptFunction SpecialAction() { mixin(MGF("mSpecialAction", "Function TribesGame.GFxTrPage_VideoGraphics.SpecialAction")); } ScriptFunction FillOption() { mixin(MGF("mFillOption", "Function TribesGame.GFxTrPage_VideoGraphics.FillOption")); } } } enum MENU_ACTION_VIDEOGRAPHICS : ubyte { MAVG_MINIMAL = 0, MAVG_LOW = 1, MAVG_MEDIUM = 2, MAVG_HIGH = 3, MAVG_VERYHIGH = 4, MAVG_MAX = 5, } @property final auto ref int CurrGraphics() { mixin(MGPC("int", 356)); } final: void Initialize() { (cast(ScriptObject)this).ProcessEvent(Functions.Initialize, cast(void*)0, cast(void*)0); } void FillData(GFxObject DataList) { ubyte params[4]; params[] = 0; *cast(GFxObject*)params.ptr = DataList; (cast(ScriptObject)this).ProcessEvent(Functions.FillData, params.ptr, cast(void*)0); } void SpecialAction(GFxTrAction Action) { ubyte params[4]; params[] = 0; *cast(GFxTrAction*)params.ptr = Action; (cast(ScriptObject)this).ProcessEvent(Functions.SpecialAction, params.ptr, cast(void*)0); } GFxObject FillOption(int ActionIndex) { ubyte params[8]; params[] = 0; *cast(int*)params.ptr = ActionIndex; (cast(ScriptObject)this).ProcessEvent(Functions.FillOption, params.ptr, cast(void*)0); return *cast(GFxObject*)&params[4]; } }
D
/* * Copyright (c) 2015 Derelict Developers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the names 'Derelict', 'DerelictImgui', nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ module derelict.imgui.types; import derelict.util.system; enum { ImGuiKey_Tab, // for tabbing through fields ImGuiKey_LeftArrow, // for text edit ImGuiKey_RightArrow,// for text edit ImGuiKey_UpArrow, // for text edit ImGuiKey_DownArrow, // for text edit ImGuiKey_PageUp, ImGuiKey_PageDown, ImGuiKey_Home, // for text edit ImGuiKey_End, // for text edit ImGuiKey_Delete, // for text edit ImGuiKey_Backspace, // for text edit ImGuiKey_Enter, // for text edit ImGuiKey_Escape, // for text edit ImGuiKey_A, // for text edit CTRL+A: select all ImGuiKey_C, // for text edit CTRL+C: copy ImGuiKey_V, // for text edit CTRL+V: paste ImGuiKey_X, // for text edit CTRL+X: cut ImGuiKey_Y, // for text edit CTRL+Y: redo ImGuiKey_Z, // for text edit CTRL+Z: undo ImGuiKey_COUNT }; enum { // Default: 0 ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbar (window can still scroll with mouse or programatically) ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user scrolling with mouse wheel ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame ImGuiWindowFlags_ShowBorders = 1 << 7, // Show borders around windows and items ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file ImGuiWindowFlags_NoInputs = 1 << 9, // Disable catching mouse or keyboard inputs ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menubar ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Enable horizontal scrollbar (off by default). You need to use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programatically giving it focus) // [Internal] ImGuiWindowFlags_ChildWindow = 1 << 20, // Don't use! For internal use by BeginChild() ImGuiWindowFlags_ChildWindowAutoFitX = 1 << 21, // Don't use! For internal use by BeginChild() ImGuiWindowFlags_ChildWindowAutoFitY = 1 << 22, // Don't use! For internal use by BeginChild() ImGuiWindowFlags_ComboBox = 1 << 23, // Don't use! For internal use by ComboBox() ImGuiWindowFlags_Tooltip = 1 << 24, // Don't use! For internal use by BeginTooltip() ImGuiWindowFlags_Popup = 1 << 25, // Don't use! For internal use by BeginPopup() ImGuiWindowFlags_Modal = 1 << 26, // Don't use! For internal use by BeginPopupModal() ImGuiWindowFlags_ChildMenu = 1 << 27 // Don't use! For internal use by BeginMenu() } enum { // Default: 0 ImGuiInputTextFlags_CharsDecimal = 1 << 0, // Allow 0123456789.+-*/ ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef ImGuiInputTextFlags_CharsUppercase = 1 << 2, // Turn a..z into A..Z ImGuiInputTextFlags_CharsNoBlank = 1 << 3, // Filter out spaces, tabs ImGuiInputTextFlags_AutoSelectAll = 1 << 4, // Select entire text when first taking mouse focus ImGuiInputTextFlags_EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to when the value was modified) ImGuiInputTextFlags_CallbackCompletion = 1 << 6, // Call user function on pressing TAB (for completion handling) ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Call user function on pressing Up/Down arrows (for history handling) ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Call user function every time ImGuiInputTextFlags_CallbackCharFilter = 1 << 9, // Call user function to filter character. Modify data->EventChar to replace/filter input, or return 1 to discard character. ImGuiInputTextFlags_AllowTabInput = 1 << 10, // Pressing TAB input a '\t' character into the text field ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, allow exiting edition by pressing Enter. Ctrl+Enter to add new line (by default adds new lines with Enter). ImGuiInputTextFlags_NoHorizontalScroll = 1 << 12, // Disable following the cursor horizontally ImGuiInputTextFlags_AlwaysInsertMode = 1 << 13, // Insert mode ImGuiInputTextFlags_ReadOnly = 1 << 14, // Read-only mode ImGuiInputTextFlags_Password = 1 << 15, // Password mode, display all characters as '*' // [Internal] ImGuiInputTextFlags_Multiline = 1 << 20 // For internal use by InputTextMultiline() } enum { ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected ImGuiTreeNodeFlags_Framed = 1 << 1, // Full colored frame (e.g. for CollapsingHeader) ImGuiTreeNodeFlags_AllowOverlapMode = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Need double-click to open node ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Only open when clicking on the arrow part. If ImGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open. ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow //ImGuITreeNodeFlags_SpanAllAvailWidth = 1 << 10, // FIXME: TODO: Extend hit box horizontally even if not framed //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 11, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoAutoOpenOnLog } enum { // Default: 0 ImGuiSelectableFlags_DontClosePopups = 1 << 0, // Clicking this don't close parent popup window ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Selectable frame can span all columns (text will still fit in current column) ImGuiSelectableFlags_AllowDoubleClick = 1 << 2 // Generate press events on double clicks too } enum { ImGuiSetCond_Always = 1 << 0, // Set the variable ImGuiSetCond_Once = 1 << 1, // Only set the variable on the first call per runtime session ImGuiSetCond_FirstUseEver = 1 << 2, // Only set the variable if the window doesn't exist in the .ini file ImGuiSetCond_Appearing = 1 << 3 // Only set the variable if the window is appearing after being inactive (or the first time) } enum { ImGuiCol_Text, ImGuiCol_TextDisabled, ImGuiCol_WindowBg, ImGuiCol_ChildWindowBg, ImGuiCol_PopupBg, ImGuiCol_Border, ImGuiCol_BorderShadow, ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive, ImGuiCol_TitleBg, ImGuiCol_TitleBgCollapsed, ImGuiCol_TitleBgActive, ImGuiCol_MenuBarBg, ImGuiCol_ScrollbarBg, ImGuiCol_ScrollbarGrab, ImGuiCol_ScrollbarGrabHovered, ImGuiCol_ScrollbarGrabActive, ImGuiCol_ComboBg, ImGuiCol_CheckMark, ImGuiCol_SliderGrab, ImGuiCol_SliderGrabActive, ImGuiCol_Button, ImGuiCol_ButtonHovered, ImGuiCol_ButtonActive, ImGuiCol_Header, ImGuiCol_HeaderHovered, ImGuiCol_HeaderActive, ImGuiCol_Column, ImGuiCol_ColumnHovered, ImGuiCol_ColumnActive, ImGuiCol_ResizeGrip, ImGuiCol_ResizeGripHovered, ImGuiCol_ResizeGripActive, ImGuiCol_CloseButton, ImGuiCol_CloseButtonHovered, ImGuiCol_CloseButtonActive, ImGuiCol_PlotLines, ImGuiCol_PlotLinesHovered, ImGuiCol_PlotHistogram, ImGuiCol_PlotHistogramHovered, ImGuiCol_TextSelectedBg, ImGuiCol_ModalWindowDarkening, // darken entire screen when a modal window is active ImGuiCol_COUNT } enum { ImGuiStyleVar_Alpha, // float ImGuiStyleVar_WindowPadding, // ImVec2 ImGuiStyleVar_WindowRounding, // float ImGuiStyleVar_WindowMinSize, // ImVec2 ImGuiStyleVar_ChildWindowRounding, // float ImGuiStyleVar_FramePadding, // ImVec2 ImGuiStyleVar_FrameRounding, // float ImGuiStyleVar_ItemSpacing, // ImVec2 ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ImGuiStyleVar_IndentSpacing, // float ImGuiStyleVar_GrabMinSize, // float ImGuiStyleVar_ButtonTextAlign, // flags ImGuiAlign_* ImGuiStyleVar_Count_ } enum { ImGuiColorEditMode_UserSelect = -2, ImGuiColorEditMode_UserSelectShowButton = -1, ImGuiColorEditMode_RGB = 0, ImGuiColorEditMode_HSV = 1, ImGuiColorEditMode_HEX = 2 } enum { ImGuiMouseCursor_None = -1, ImGuiMouseCursor_Arrow = 0, ImGuiMouseCursor_TextInput, // When hovering over InputText, etc. ImGuiMouseCursor_Move, // Unused ImGuiMouseCursor_ResizeNS, // Unused ImGuiMouseCursor_ResizeEW, // When hovering over a column ImGuiMouseCursor_ResizeNESW, // Unused ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window ImGuiMouseCursor_Count_ } align(1) struct ImVec2 { float x=0; float y=0; } align(1) struct ImVec4 { float x=0; float y=0; float z=0; float w=0; } struct ImFont{} struct ImFontAtlas{} struct ImDrawList{} struct ImGuiStorage{} struct ImGuiContext{} alias uint ImU32; alias ushort ImWchar; // character for display alias void* ImTextureID; // user data to refer to a texture (e.g. store your texture handle/id) alias ImU32 ImGuiID; // unique ID used by widgets (typically hashed from a stack of string) alias int ImGuiCol; // enum ImGuiCol_ alias int ImGuiStyleVar; // enum ImGuiStyleVar_ alias int ImGuiKey; // enum ImGuiKey_ alias int ImGuiColorEditMode; // enum ImGuiColorEditMode_ alias int ImGuiMouseCursor; // enum ImGuiMouseCursor_ alias int ImGuiWindowFlags; // enum ImGuiWindowFlags_ alias int ImGuiSetCond; // enum ImGuiSetCond_ alias int ImGuiInputTextFlags; // enum ImGuiInputTextFlags_ alias int ImGuiSelectableFlags; // enum ImGuiSelectableFlags_ alias int ImGuiTreeNodeFlags; // enum ImGuiTreeNodeFlags_ alias int function(ImGuiTextEditCallbackData *data) ImGuiTextEditCallback; alias void function(ImGuiSizeConstraintCallbackData *data) ImGuiSizeConstraintCallback; extern(C) nothrow { alias RenderDrawListFunc = void function(ImDrawData* data); alias GetClipboardTextFunc = const(char)* function(void* user_data); alias SetClipboardTextFunc = void function(void* user_data, const(char)* text); alias MemAllocFunc = void* function(size_t); alias MemFreeFunc = void function(void*); alias ImeSetInputScreenPosFunc = void function(int,int); } // Shared state of InputText(), passed to callback when a ImGuiInputTextFlags_Callback* flag is used. align(1) struct ImGuiTextEditCallbackData { ImGuiInputTextFlags EventFlag; // One of ImGuiInputTextFlags_Callback* // Read-only ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only void* UserData; // What user passed to InputText() // Read-only bool ReadOnly; // Read-only mode // Read-only // CharFilter event: ImWchar EventChar; // Character input // Read-write (replace character or set to zero) // Completion,History,Always events: ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only char* Buf; // Current text // Read-write (pointed data only) int BufTextLen; // Current text length in bytes // Read-write size_t BufSize; // // Read-only bool BufDirty; // Set if you modify Buf directly // Write int CursorPos; // // Read-write int SelectionStart; // // Read-write (== to SelectionEnd when no selection) int SelectionEnd; // // Read-write // NB: calling those function loses selection. //void DeleteChars(int pos, int bytes_count); //void InsertChars(int pos, const char* text, const char* text_end = NULL); bool HasSelection() const { return SelectionStart != SelectionEnd; } }; align(1) struct ImGuiIO { ImVec2 DisplaySize; // <unset> // Display size, in pixels. For clamping windows positions. float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. float IniSavingRate; // = 5.0f // Maximum time between saving positions/sizes to .ini file, in seconds. const char* IniFilename; // = "imgui.ini" // Path to .ini file. NULL to disable .ini saving. const char* LogFilename; // = "imgui_log.txt" // Path to .log file (default parameter to ImGui::LogToFile when no file is specified). float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds. float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels. float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging int[ImGuiKey_COUNT] KeyMap; // <unset> // Map of indices into the KeysDown[512] entries array float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds. (for actions where 'repeat' is active) float KeyRepeatRate; // = 0.020f // When holding a key/button, rate at which it repeats, in seconds. void* UserData; // = NULL // Store your own data for retrieval by callbacks. ImFontAtlas* Fonts; // <auto> // Load and assemble one or more fonts into a single tightly packed texture. Output to Fonts array. float FontGlobalScale; // = 1.0f // Global scale all fonts bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. ImVec2 DisplayFramebufferScale; // = (1.0f,1.0f) // For retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui. ImVec2 DisplayVisibleMin; // <unset> (0.0f,0.0f) // If you use DisplaySize as a virtual space larger than your screen, set DisplayVisibleMin/Max to the visible area. ImVec2 DisplayVisibleMax; // <unset> (0.0f,0.0f) // If the values are the same, we defaults to Min=(0.0f) and Max=DisplaySize // Advanced/subtle behaviors bool OSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl //------------------------------------------------------------------ // User Functions //------------------------------------------------------------------ // REQUIRED: rendering function. // See example code if you are unsure of how to implement this. RenderDrawListFunc RenderDrawListsFn; // Optional: access OS clipboard // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) GetClipboardTextFunc GetClipboardTextFn; SetClipboardTextFunc SetClipboardTextFn; void* ClipboardUserData; // Optional: override memory allocations. MemFreeFn() may be called with a NULL pointer. // (default to posix malloc/free) MemAllocFunc MemAllocFn; MemFreeFunc MemFreeFn; // Optional: notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME in Windows) // (default to use native imm32 api on Windows) ImeSetInputScreenPosFunc ImeSetInputScreenPosFn; void* ImeWindowHandle; // (Windows) Set this to your HWND to get automatic IME cursor positioning. //------------------------------------------------------------------ // Input - Fill before calling NewFrame() //------------------------------------------------------------------ ImVec2 MousePos; // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) bool[5] MouseDown; // Mouse buttons. ImGui itself only uses button 0 (left button). Others buttons allows to track if mouse is being used by your application + available to user as a convenience via IsMouse** API. float MouseWheel; // Mouse wheel: 1 unit scrolls about 5 lines text. bool MouseDrawCursor; // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). bool KeyCtrl; // Keyboard modifier pressed: Control bool KeyShift; // Keyboard modifier pressed: Shift bool KeyAlt; // Keyboard modifier pressed: Alt bool KeySuper; // Keyboard modifier pressed: Cmd/Super/Windows bool[512] KeysDown; // Keyboard keys that are pressed (in whatever storage order you naturally have access to keyboard data) ImWchar[16+1] InputCharacters; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper. //------------------------------------------------------------------ // Output - Retrieve after calling NewFrame(), you can use them to discard inputs or hide them from the rest of your application //------------------------------------------------------------------ bool WantCaptureMouse; // Mouse is hovering a window or widget is active (= ImGui will use your mouse input) bool WantCaptureKeyboard; // Widget is active (= ImGui will use your keyboard input) bool WantTextInput; // Some text input widget is active, which will read input characters from the InputCharacters array. float Framerate; // Framerate estimation, in frame per second. Rolling average estimation based on IO.DeltaTime over 120 frames int MetricsAllocs; // Number of active memory allocations int MetricsRenderVertices; // Vertices processed during last call to Render() int MetricsRenderIndices; // int MetricsActiveWindows; // Number of visible windows (exclude child windows) ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are negative, so a disappearing/reappearing mouse won't have a huge delta for one frame. //------------------------------------------------------------------ // [Internal] ImGui will maintain those fields for you //------------------------------------------------------------------ ImVec2 MousePosPrev; // Previous mouse position bool[5] MouseClicked; // Mouse button went from !Down to Down ImVec2[5] MouseClickedPos; // Position at time of clicking float[5] MouseClickedTime; // Time of last click (used to figure out double-click) bool[5] MouseDoubleClicked; // Has mouse button been double-clicked? bool[5] MouseReleased; // Mouse button went from Down to !Down bool[5] MouseDownOwned; // Track if button was clicked inside a window. We don't request mouse capture from the application if click started outside ImGui bounds. float[5] MouseDownDuration; // Duration the mouse button has been down (0.0f == just clicked) float[5] MouseDownDurationPrev; // Previous time the mouse button has been down float[5] MouseDragMaxDistanceSqr; // Squared maximum distance of how much mouse has traveled from the click point float[512] KeysDownDuration; // Duration the keyboard key has been down (0.0f == just pressed) float[512] KeysDownDurationPrev; // Previous duration the key has been down } align(1) struct ImGuiStyle { float Alpha; // Global alpha applies to everything in ImGui ImVec2 WindowPadding; // Padding within a window ImVec2 WindowMinSize; // Minimum window size float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. float ChildWindowRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets) float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets). ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! float IndentSpacing; // Horizontal indentation when e.g. entering a tree node float ColumnsMinSpacing; // Minimum horizontal spacing between two columns float ScrollbarSize; // Width of the vertical scrollbar float ScrollbarRounding; // Radius of grab corners for scrollbar float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f,0.5f) for horizontally+vertically centered. ImVec2 DisplayWindowPadding; // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows. ImVec2 DisplaySafeAreaPadding; // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU. bool AntiAliasedShapes; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) float CurveTessellationTol; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. ImVec4[ImGuiCol_COUNT] Colors; }; align(1) struct ImDrawVert { ImVec2 pos; ImVec2 uv; ImU32 col; }; alias ImDrawCallback = void function(const ImDrawList* parent_list, const ImDrawCmd* cmd) nothrow; align(1) struct ImDrawCmd { uint ElemCount; // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. ImVec4 ClipRect; // Clipping rectangle (x1, y1, x2, y2) ImTextureID TextureId; // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. ImDrawCallback UserCallback; // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. void* UserCallbackData; // The draw callback code can access this. } alias ImDrawIdx = ushort; align(1) struct ImDrawData { bool Valid; ImDrawList** CmdLists; int CmdListsCount; int TotalVtxCount; // For convenience, sum of all cmd_lists vtx_buffer.Size int TotalIdxCount; // For convenience, sum of all cmd_lists idx_buffer.Size } align(1) struct ImFontConfig { void* FontData; int FontDataSize; bool FontDataOwnedByAtlas=true; int FontNo=0; float SizePixels=0.0f; int OversampleH=3, OversampleV=1; bool PixelSnapH=false; ImVec2 GlyphExtraSpacing; ImVec2 GlyphOffset; const ImWchar* GlyphRanges; bool MergeMode=false; // [Internal] char[32] Name; ImFont* DstFont; } align(1) struct ImGuiSizeConstraintCallbackData { void* UserData; ImVec2 Pos; ImVec2 CurrentSize; ImVec2 DesiredSize; } align(1) struct ImColor { ImU32 value; alias value this; this(ubyte r, ubyte g, ubyte b, ubyte a = 255) { value = r | (g<<8) | (b<<16) | (a<<24); } this(float r, float g, float b, float a = 1.0f) { static float imSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } value = (cast(ImU32)(imSaturate(r)*255)); value |= (cast(ImU32)(imSaturate(g)*255) << 8); value |= (cast(ImU32)(imSaturate(b)*255) << 16); value |= (cast(ImU32)(imSaturate(a)*255) << 24); } ImVec4 asImVec4() @property { float s = 1.0f/255.0f; return ImVec4((value & 0xFF) * s, ((value >> 8) & 0xFF) * s, ((value >> 16) & 0xFF) * s, (value >> 24) * s); } void SetHSV(float h, float s, float v, float a = 1.0f) { import derelict.imgui.funcs; float r,g,b; igColorConvertHSVtoRGB(h, s, v, &r, &g, &b); this = ImColor(r,g,b,a); } } align(1) struct ImGuiListClipper { import derelict.imgui.funcs : ImGuiListClipper_Begin, ImGuiListClipper_End, ImGuiListClipper_Step; float StartPosY; float ItemsHeight; int ItemsCount, StepNo, DisplayStart, DisplayEnd; this(int items_count = -1, float items_height = -1.0f) { ImGuiListClipper_Begin(&this, items_count, items_height); } ~this() { assert(ItemsCount == -1); } void Begin(int items_count, float items_height = -1.0f) { ImGuiListClipper_Begin(&this, items_count, items_height); } void End() { ImGuiListClipper_End(&this); } bool Step() { return ImGuiListClipper_Step(&this); } }
D
/* TEST_OUTPUT: --- fail_compilation/test8793.d(13): Error: cannot implicitly convert expression (__lambda2) of type bool delegate(const(int) x) @system to bool delegate(const(int)) pure fail_compilation/test8793.d(14): Error: cannot implicitly convert expression (__lambda2) of type bool delegate(const(int) x) @system to bool delegate(const(int)) pure fail_compilation/test8793.d(16): Error: cannot implicitly convert expression (__lambda2) of type bool delegate(const(int) x) nothrow @safe to bool delegate(const(int)) pure --- */ alias bool function(in int) pure Fp8793; alias bool delegate(in int) pure Dg8793; Dg8793 foo8793pfp2(const Fp8793* f) pure { return x => (*f)(x); } // Line13, error Dg8793 foo8793pdg2(const Dg8793* f) pure { return x => (*f)(x); } // Line14, error Dg8793 foo8793ptr2(const int* p) pure { return x => *p == x; } // Line16, error
D
class WordListGeneratorClass : ErrorHandlerClass { import translator; }
D
/** * Defines a package and module. * * Specification: $(LINK2 https://dlang.org/spec/module.html, Modules) * * 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/dmodule.d, _dmodule.d) * Documentation: https://dlang.org/phobos/dmd_dmodule.html * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/dmodule.d */ module dmd.dmodule; import core.stdc.stdio; import core.stdc.stdlib; import core.stdc.string; import dmd.aggregate; import dmd.arraytypes; import dmd.astcodegen; import dmd.astenums; import dmd.compiler; import dmd.gluelayer; import dmd.dimport; import dmd.dmacro; import dmd.doc; import dmd.dscope; import dmd.dsymbol; import dmd.dsymbolsem; import dmd.errors; import dmd.errorsink; import dmd.expression; import dmd.expressionsem; import dmd.file_manager; import dmd.globals; import dmd.id; import dmd.identifier; import dmd.location; import dmd.parse; import dmd.cparse; import dmd.root.array; import dmd.root.file; import dmd.root.filename; import dmd.common.outbuffer; import dmd.root.port; import dmd.root.rmem; import dmd.root.rootobject; import dmd.root.string; import dmd.semantic2; import dmd.semantic3; import dmd.target; import dmd.utils; import dmd.visitor; version (IN_GCC) {} else version (IN_LLVM) {} else version = MARS; // function used to call semantic3 on a module's dependencies void semantic3OnDependencies(Module m) { if (!m) return; if (m.semanticRun > PASS.semantic3) return; m.semantic3(null); foreach (i; 1 .. m.aimports.length) semantic3OnDependencies(m.aimports[i]); } /** * Remove generated .di files on error and exit */ void removeHdrFilesAndFail(ref Param params, ref Modules modules) nothrow { if (params.dihdr.doOutput) { foreach (m; modules) { if (m.filetype == FileType.dhdr) continue; File.remove(m.hdrfile.toChars()); } } fatal(); } /** * Converts a chain of identifiers to the filename of the module * * Params: * packages = the names of the "parent" packages * ident = the name of the child package or module * * Returns: * the filename of the child package or module */ private const(char)[] getFilename(Identifier[] packages, Identifier ident) nothrow { const(char)[] filename = ident.toString(); OutBuffer buf; OutBuffer dotmods; auto modAliases = &global.params.modFileAliasStrings; if (packages.length == 0 && modAliases.length == 0) return filename; void checkModFileAlias(const(char)[] p) { /* Check and replace the contents of buf[] with * an alias string from global.params.modFileAliasStrings[] */ dotmods.writestring(p); foreach_reverse (const m; *modAliases) { const q = strchr(m, '='); assert(q); if (dotmods.length == q - m && memcmp(dotmods.peekChars(), m, q - m) == 0) { buf.setsize(0); auto rhs = q[1 .. strlen(q)]; if (rhs.length > 0 && (rhs[$ - 1] == '/' || rhs[$ - 1] == '\\')) rhs = rhs[0 .. $ - 1]; // remove trailing separator buf.writestring(rhs); break; // last matching entry in ms[] wins } } dotmods.writeByte('.'); } foreach (pid; packages) { const p = pid.toString(); buf.writestring(p); if (modAliases.length) checkModFileAlias(p); version (Windows) enum FileSeparator = '\\'; else enum FileSeparator = '/'; buf.writeByte(FileSeparator); } buf.writestring(filename); if (modAliases.length) checkModFileAlias(filename); buf.writeByte(0); filename = buf.extractSlice()[0 .. $ - 1]; return filename; } /*********************************************************** */ extern (C++) class Package : ScopeDsymbol { PKG isPkgMod = PKG.unknown; uint tag; // auto incremented tag, used to mask package tree in scopes Module mod; // !=null if isPkgMod == PKG.module_ final extern (D) this(const ref Loc loc, Identifier ident) nothrow { super(loc, ident); __gshared uint packageTag; this.tag = packageTag++; } override const(char)* kind() const nothrow { return "package"; } override bool equals(const RootObject o) const { // custom 'equals' for bug 17441. "package a" and "module a" are not equal if (this == o) return true; auto p = cast(Package)o; return p && isModule() == p.isModule() && ident.equals(p.ident); } /**************************************************** * Input: * packages[] the pkg1.pkg2 of pkg1.pkg2.mod * Returns: * the symbol table that mod should be inserted into * Output: * *pparent the rightmost package, i.e. pkg2, or NULL if no packages * *ppkg the leftmost package, i.e. pkg1, or NULL if no packages */ extern (D) static DsymbolTable resolve(Identifier[] packages, Dsymbol* pparent, Package* ppkg) { DsymbolTable dst = Module.modules; Dsymbol parent = null; //printf("Package::resolve()\n"); if (ppkg) *ppkg = null; foreach (pid; packages) { Package pkg; Dsymbol p = dst.lookup(pid); if (!p) { pkg = new Package(Loc.initial, pid); dst.insert(pkg); pkg.parent = parent; pkg.symtab = new DsymbolTable(); } else { pkg = p.isPackage(); assert(pkg); // It might already be a module, not a package, but that needs // to be checked at a higher level, where a nice error message // can be generated. // dot net needs modules and packages with same name // But we still need a symbol table for it if (!pkg.symtab) pkg.symtab = new DsymbolTable(); } parent = pkg; dst = pkg.symtab; if (ppkg && !*ppkg) *ppkg = pkg; if (pkg.isModule()) { // Return the module so that a nice error message can be generated if (ppkg) *ppkg = cast(Package)p; break; } } if (pparent) *pparent = parent; return dst; } override final inout(Package) isPackage() inout { return this; } /** * Checks if pkg is a sub-package of this * * For example, if this qualifies to 'a1.a2' and pkg - to 'a1.a2.a3', * this function returns 'true'. If it is other way around or qualified * package paths conflict function returns 'false'. * * Params: * pkg = possible subpackage * * Returns: * see description */ final bool isAncestorPackageOf(const Package pkg) const { if (this == pkg) return true; if (!pkg || !pkg.parent) return false; return isAncestorPackageOf(pkg.parent.isPackage()); } override Dsymbol search(const ref Loc loc, Identifier ident, int flags = SearchLocalsOnly) { //printf("%s Package.search('%s', flags = x%x)\n", toChars(), ident.toChars(), flags); flags &= ~SearchLocalsOnly; // searching an import is always transitive if (!isModule() && mod) { // Prefer full package name. Dsymbol s = symtab ? symtab.lookup(ident) : null; if (s) return s; //printf("[%s] through pkdmod: %s\n", loc.toChars(), toChars()); return mod.search(loc, ident, flags); } return ScopeDsymbol.search(loc, ident, flags); } override void accept(Visitor v) { v.visit(this); } final Module isPackageMod() { if (isPkgMod == PKG.module_) { return mod; } return null; } /** * Checks for the existence of a package.d to set isPkgMod appropriately * if isPkgMod == PKG.unknown */ final void resolvePKGunknown() { if (isModule()) return; if (isPkgMod != PKG.unknown) return; Identifier[] packages; for (Dsymbol s = this.parent; s; s = s.parent) packages ~= s.ident; reverse(packages); if (Module.find(getFilename(packages, ident))) Module.load(Loc.initial, packages, this.ident); else isPkgMod = PKG.package_; } } /*********************************************************** */ extern (C++) final class Module : Package { extern (C++) __gshared Module rootModule; extern (C++) __gshared DsymbolTable modules; // symbol table of all modules extern (C++) __gshared Modules amodules; // array of all modules extern (C++) __gshared Dsymbols deferred; // deferred Dsymbol's needing semantic() run on them extern (C++) __gshared Dsymbols deferred2; // deferred Dsymbol's needing semantic2() run on them extern (C++) __gshared Dsymbols deferred3; // deferred Dsymbol's needing semantic3() run on them static void _init() { modules = new DsymbolTable(); } /** * Deinitializes the global state of the compiler. * * This can be used to restore the state set by `_init` to its original * state. */ static void deinitialize() { modules = modules.init; } extern (C++) __gshared AggregateDeclaration moduleinfo; const(char)[] arg; // original argument name ModuleDeclaration* md; // if !=null, the contents of the ModuleDeclaration declaration const FileName srcfile; // input source file const FileName objfile; // output .obj file const FileName hdrfile; // 'header' file FileName docfile; // output documentation file const(ubyte)[] src; /// Raw content of the file uint errors; // if any errors in file uint numlines; // number of lines in source file FileType filetype; // source file type bool hasAlwaysInlines; // contains references to functions that must be inlined bool isPackageFile; // if it is a package.d Package pkg; // if isPackageFile is true, the Package that contains this package.d Strings contentImportedFiles; // array of files whose content was imported int needmoduleinfo; private ThreeState selfimports; private ThreeState rootimports; Dsymbol[void*] tagSymTab; /// ImportC: tag symbols that conflict with other symbols used as the index private OutBuffer defines; // collect all the #define lines here /************************************* * Return true if module imports itself. */ bool selfImports() { //printf("Module::selfImports() %s\n", toChars()); if (selfimports == ThreeState.none) { foreach (Module m; amodules) m.insearch = false; selfimports = imports(this) ? ThreeState.yes : ThreeState.no; foreach (Module m; amodules) m.insearch = false; } return selfimports == ThreeState.yes; } /************************************* * Return true if module imports root module. */ bool rootImports() { //printf("Module::rootImports() %s\n", toChars()); if (rootimports == ThreeState.none) { foreach (Module m; amodules) m.insearch = false; rootimports = ThreeState.no; foreach (Module m; amodules) { if (m.isRoot() && imports(m)) { rootimports = ThreeState.yes; break; } } foreach (Module m; amodules) m.insearch = false; } return rootimports == ThreeState.yes; } private Identifier searchCacheIdent; private Dsymbol searchCacheSymbol; // cached value of search private int searchCacheFlags; // cached flags private bool insearch; /** * A root module is one that will be compiled all the way to * object code. This field holds the root module that caused * this module to be loaded. If this module is a root module, * then it will be set to `this`. This is used to determine * ownership of template instantiation. */ Module importedFrom; Dsymbols* decldefs; // top level declarations for this Module Modules aimports; // all imported modules uint debuglevel; // debug level Identifiers* debugids; // debug identifiers Identifiers* debugidsNot; // forward referenced debug identifiers uint versionlevel; // version level Identifiers* versionids; // version identifiers Identifiers* versionidsNot; // forward referenced version identifiers MacroTable macrotable; // document comment macros Escape* _escapetable; // document comment escapes size_t nameoffset; // offset of module name from start of ModuleInfo size_t namelen; // length of module name in characters extern (D) this(const ref Loc loc, const(char)[] filename, Identifier ident, int doDocComment, int doHdrGen) { super(loc, ident); const(char)[] srcfilename; //printf("Module::Module(filename = '%.*s', ident = '%s')\n", cast(int)filename.length, filename.ptr, ident.toChars()); this.arg = filename; srcfilename = FileName.defaultExt(filename, mars_ext); if (target.run_noext && global.params.run && !FileName.ext(filename) && FileName.exists(srcfilename) == 0 && FileName.exists(filename) == 1) { FileName.free(srcfilename.ptr); srcfilename = FileName.removeExt(filename); // just does a mem.strdup(filename) } else if (!FileName.equalsExt(srcfilename, mars_ext) && !FileName.equalsExt(srcfilename, hdr_ext) && !FileName.equalsExt(srcfilename, c_ext) && !FileName.equalsExt(srcfilename, i_ext) && !FileName.equalsExt(srcfilename, dd_ext)) { error("source file name '%.*s' must have .%.*s extension", cast(int)srcfilename.length, srcfilename.ptr, cast(int)mars_ext.length, mars_ext.ptr); fatal(); } srcfile = FileName(srcfilename); objfile = setOutfilename(global.params.objname, global.params.objdir, filename, target.obj_ext); if (doDocComment) setDocfile(); if (doHdrGen) hdrfile = setOutfilename(global.params.dihdr.name, global.params.dihdr.dir, arg, hdr_ext); } extern (D) this(const(char)[] filename, Identifier ident, int doDocComment, int doHdrGen) { this(Loc.initial, filename, ident, doDocComment, doHdrGen); } static Module create(const(char)* filename, Identifier ident, int doDocComment, int doHdrGen) { return create(filename.toDString, ident, doDocComment, doHdrGen); } extern (D) static Module create(const(char)[] filename, Identifier ident, int doDocComment, int doHdrGen) { return new Module(Loc.initial, filename, ident, doDocComment, doHdrGen); } static const(char)* find(const(char)* filename) { return find(filename.toDString).ptr; } extern (D) static const(char)[] find(const(char)[] filename) { return global.fileManager.lookForSourceFile(filename, global.path ? (*global.path)[] : null); } extern (C++) static Module load(const ref Loc loc, Identifiers* packages, Identifier ident) { return load(loc, packages ? (*packages)[] : null, ident); } extern (D) static Module load(const ref Loc loc, Identifier[] packages, Identifier ident) { //printf("Module::load(ident = '%s')\n", ident.toChars()); // Build module filename by turning: // foo.bar.baz // into: // foo\bar\baz const(char)[] filename = getFilename(packages, ident); // Look for the source file if (const result = find(filename)) filename = result; // leaks auto m = new Module(loc, filename, ident, 0, 0); if (!m.read(loc)) return null; if (global.params.verbose) { OutBuffer buf; foreach (pid; packages) { buf.writestring(pid.toString()); buf.writeByte('.'); } buf.printf("%s\t(%s)", ident.toChars(), m.srcfile.toChars()); message("import %s", buf.peekChars()); } if((m = m.parse()) is null) return null; return m; } override const(char)* kind() const { return "module"; } /********************************************* * Combines things into output file name for .html and .di files. * Input: * name Command line name given for the file, NULL if none * dir Command line directory given for the file, NULL if none * arg Name of the source file * ext File name extension to use if 'name' is NULL * global.params.preservePaths get output path from arg * srcfile Input file - output file name must not match input file */ extern(D) FileName setOutfilename(const(char)[] name, const(char)[] dir, const(char)[] arg, const(char)[] ext) { const(char)[] docfilename; if (name) { docfilename = name; } else { const(char)[] argdoc; OutBuffer buf; if (arg == "__stdin.d") { version (Posix) import core.sys.posix.unistd : getpid; else version (Windows) import core.sys.windows.winbase : getpid = GetCurrentProcessId; buf.printf("__stdin_%d.d", getpid()); arg = buf[]; } if (global.params.preservePaths) argdoc = arg; else argdoc = FileName.name(arg); // If argdoc doesn't have an absolute path, make it relative to dir if (!FileName.absolute(argdoc)) { //FileName::ensurePathExists(dir); argdoc = FileName.combine(dir, argdoc); } docfilename = FileName.forceExt(argdoc, ext); } if (FileName.equals(docfilename, srcfile.toString())) { error("source file and output file have same name '%s'", srcfile.toChars()); fatal(); } return FileName(docfilename); } extern (D) void setDocfile() { docfile = setOutfilename(global.params.ddoc.name, global.params.ddoc.dir, arg, doc_ext); } /** * Trigger the relevant semantic error when a file cannot be read * * We special case `object.d` as a failure is likely to be a rare * but difficult to diagnose case for the user. Packages also require * special handling to avoid exposing the compiler's internals. * * Params: * loc = The location at which the file read originated (e.g. import) */ private void onFileReadError(const ref Loc loc) { if (FileName.equals(srcfile.toString(), "object.d")) { .error(loc, "cannot find source code for runtime library file 'object.d'"); version (IN_LLVM) { errorSupplemental(loc, "ldc2 might not be correctly installed."); errorSupplemental(loc, "Please check your ldc2.conf configuration file."); errorSupplemental(loc, "Installation instructions can be found at http://wiki.dlang.org/LDC."); } version (MARS) { errorSupplemental(loc, "dmd might not be correctly installed. Run 'dmd -man' for installation instructions."); const dmdConfFile = global.inifilename.length ? FileName.canonicalName(global.inifilename) : "not found"; errorSupplemental(loc, "config file: %.*s", cast(int)dmdConfFile.length, dmdConfFile.ptr); } } else if (FileName.ext(this.arg) || !loc.isValid()) { // Modules whose original argument name has an extension, or do not // have a valid location come from the command-line. // Error that their file cannot be found and return early. .error(loc, "cannot find input file `%s`", srcfile.toChars()); } else { // if module is not named 'package' but we're trying to read 'package.d', we're looking for a package module bool isPackageMod = (strcmp(toChars(), "package") != 0) && isPackageFileName(srcfile); if (isPackageMod) .error(loc, "importing package '%s' requires a 'package.d' file which cannot be found in '%s'", toChars(), srcfile.toChars()); else { .error(loc, "unable to read module `%s`", toChars()); const pkgfile = FileName.combine(FileName.removeExt(srcfile.toString()), package_d); .errorSupplemental(loc, "Expected '%s' or '%s' in one of the following import paths:", srcfile.toChars(), pkgfile.ptr); } } if (!global.gag) { /* Print path */ if (global.path) { foreach (i, p; *global.path) fprintf(stderr, "import path[%llu] = %s\n", cast(ulong)i, p); } else { fprintf(stderr, "Specify path to file '%s' with -I switch\n", srcfile.toChars()); } removeHdrFilesAndFail(global.params, Module.amodules); } } /** * Reads the file from `srcfile` and loads the source buffer. * * If makefile module dependency is requested, we add this module * to the list of dependencies from here. * * Params: * loc = the location * * Returns: `true` if successful */ bool read(const ref Loc loc) { if (this.src) return true; // already read //printf("Module::read('%s') file '%s'\n", toChars(), srcfile.toChars()); /* Preprocess the file if it's a .c file */ FileName filename = srcfile; bool ifile = false; // did we generate a .i file scope (exit) { if (ifile) File.remove(filename.toChars()); // remove generated file } if (global.preprocess && FileName.equalsExt(srcfile.toString(), c_ext) && FileName.exists(srcfile.toString())) { filename = global.preprocess(srcfile, loc, ifile, &defines); // run C preprocessor } if (auto result = global.fileManager.lookup(filename)) { this.src = result; if (global.params.makeDeps.doOutput) global.params.makeDeps.files.push(srcfile.toChars()); return true; } this.onFileReadError(loc); return false; } /// syntactic parse Module parse() { return parseModule!ASTCodegen(); } /// ditto extern (D) Module parseModule(AST)() { const(char)* srcname = srcfile.toChars(); //printf("Module::parse(srcname = '%s')\n", srcname); isPackageFile = isPackageFileName(srcfile); const(char)[] buf = processSource(src, this); // an error happened on UTF conversion if (buf is null) return null; /* If it starts with the string "Ddoc", then it's a documentation * source file. */ if (buf.length>= 4 && buf[0..4] == "Ddoc") { comment = buf.ptr + 4; filetype = FileType.ddoc; if (!docfile) setDocfile(); return this; } /* If it has the extension ".dd", it is also a documentation * source file. Documentation source files may begin with "Ddoc" * but do not have to if they have the .dd extension. * https://issues.dlang.org/show_bug.cgi?id=15465 */ if (FileName.equalsExt(arg, dd_ext)) { comment = buf.ptr; // the optional Ddoc, if present, is handled above. filetype = FileType.ddoc; if (!docfile) setDocfile(); return this; } /* If it has the extension ".di", it is a "header" file. */ if (FileName.equalsExt(arg, hdr_ext)) filetype = FileType.dhdr; /// Promote `this` to a root module if requested via `-i` void checkCompiledImport() { if (!this.isRoot() && Compiler.onImport(this)) this.importedFrom = this; } DsymbolTable dst; Package ppack = null; /* If it has the extension ".c", it is a "C" file. * If it has the extension ".i", it is a preprocessed "C" file. */ if (FileName.equalsExt(arg, c_ext) || FileName.equalsExt(arg, i_ext)) { filetype = FileType.c; scope p = new CParser!AST(this, buf, cast(bool) docfile, global.errorSink, target.c, &defines, &global.compileEnv); p.nextToken(); checkCompiledImport(); members = p.parseModule(); assert(!p.md); // C doesn't have module declarations numlines = p.scanloc.linnum; } else { const bool doUnittests = global.params.useUnitTests || global.params.ddoc.doOutput || global.params.dihdr.doOutput; scope p = new Parser!AST(this, buf, cast(bool) docfile, global.errorSink, &global.compileEnv, doUnittests); p.transitionIn = global.params.vin; p.nextToken(); p.parseModuleDeclaration(); md = p.md; if (md) { /* A ModuleDeclaration, md, was provided. * The ModuleDeclaration sets the packages this module appears in, and * the name of this module. */ this.ident = md.id; dst = Package.resolve(md.packages, &this.parent, &ppack); } // Done after parsing the module header because `module x.y.z` may override the file name checkCompiledImport(); members = p.parseModuleContent(); numlines = p.scanloc.linnum; } /* The symbol table into which the module is to be inserted. */ if (md) { // Mark the package path as accessible from the current module // https://issues.dlang.org/show_bug.cgi?id=21661 // Code taken from Import.addPackageAccess() if (md.packages.length > 0) { // module a.b.c.d; auto p = ppack; // a addAccessiblePackage(p, Visibility(Visibility.Kind.private_)); foreach (id; md.packages[1 .. $]) // [b, c] { p = cast(Package) p.symtab.lookup(id); if (p is null) break; addAccessiblePackage(p, Visibility(Visibility.Kind.private_)); } } assert(dst); Module m = ppack ? ppack.isModule() : null; if (m && !isPackageFileName(m.srcfile)) { .error(md.loc, "package name '%s' conflicts with usage as a module name in file %s", ppack.toPrettyChars(), m.srcfile.toChars()); } } else { /* The name of the module is set to the source file name. * There are no packages. */ dst = modules; // and so this module goes into global module symbol table /* Check to see if module name is a valid identifier */ if (!Identifier.isValidIdentifier(this.ident.toChars())) error("has non-identifier characters in filename, use module declaration instead"); } // Insert module into the symbol table Dsymbol s = this; if (isPackageFile) { /* If the source tree is as follows: * pkg/ * +- package.d * +- common.d * the 'pkg' will be incorporated to the internal package tree in two ways: * import pkg; * and: * import pkg.common; * * If both are used in one compilation, 'pkg' as a module (== pkg/package.d) * and a package name 'pkg' will conflict each other. * * To avoid the conflict: * 1. If preceding package name insertion had occurred by Package::resolve, * reuse the previous wrapping 'Package' if it exists * 2. Otherwise, 'package.d' wrapped by 'Package' is inserted to the internal tree in here. * * Then change Package::isPkgMod to PKG.module_ and set Package::mod. * * Note that the 'wrapping Package' is the Package that contains package.d and other submodules, * the one inserted to the symbol table. */ auto ps = dst.lookup(ident); Package p = ps ? ps.isPackage() : null; if (p is null) { p = new Package(Loc.initial, ident); p.tag = this.tag; // reuse the same package tag p.symtab = new DsymbolTable(); } this.tag = p.tag; // reuse the 'older' package tag this.pkg = p; p.parent = this.parent; p.isPkgMod = PKG.module_; p.mod = this; s = p; } if (!dst.insert(s)) { /* It conflicts with a name that is already in the symbol table. * Figure out what went wrong, and issue error message. */ Dsymbol prev = dst.lookup(ident); assert(prev); if (Module mprev = prev.isModule()) { if (!FileName.equals(srcname, mprev.srcfile.toChars())) error(loc, "from file %s conflicts with another module %s from file %s", srcname, mprev.toChars(), mprev.srcfile.toChars()); else if (isRoot() && mprev.isRoot()) error(loc, "from file %s is specified twice on the command line", srcname); else error(loc, "from file %s must be imported with 'import %s;'", srcname, toPrettyChars()); // https://issues.dlang.org/show_bug.cgi?id=14446 // Return previously parsed module to avoid AST duplication ICE. return mprev; } else if (Package pkg = prev.isPackage()) { // 'package.d' loaded after a previous 'Package' insertion if (isPackageFile) amodules.push(this); // Add to global array of all modules else error(md ? md.loc : loc, "from file %s conflicts with package name %s", srcname, pkg.toChars()); } else assert(global.errors); } else { // Add to global array of all modules amodules.push(this); } Compiler.onParseModule(this); return this; } override void importAll(Scope* prevsc) { //printf("+Module::importAll(this = %p, '%s'): parent = %p\n", this, toChars(), parent); if (_scope) return; // already done if (filetype == FileType.ddoc) { error("is a Ddoc file, cannot import it"); return; } /* Note that modules get their own scope, from scratch. * This is so regardless of where in the syntax a module * gets imported, it is unaffected by context. * Ignore prevsc. */ Scope* sc = Scope.createGlobal(this); // create root scope if (md && md.msg) md.msg = semanticString(sc, md.msg, "deprecation message"); // Add import of "object", even for the "object" module. // If it isn't there, some compiler rewrites, like // classinst == classinst -> .object.opEquals(classinst, classinst) // would fail inside object.d. if (filetype != FileType.c && (members.length == 0 || (*members)[0].ident != Id.object || (*members)[0].isImport() is null)) { auto im = new Import(Loc.initial, null, Id.object, null, 0); members.shift(im); } if (!symtab) { // Add all symbols into module's symbol table symtab = new DsymbolTable(); for (size_t i = 0; i < members.length; i++) { Dsymbol s = (*members)[i]; s.addMember(sc, sc.scopesym); } } // anything else should be run after addMember, so version/debug symbols are defined /* Set scope for the symbols so that if we forward reference * a symbol, it can possibly be resolved on the spot. * If this works out well, it can be extended to all modules * before any semantic() on any of them. */ setScope(sc); // remember module scope for semantic for (size_t i = 0; i < members.length; i++) { Dsymbol s = (*members)[i]; s.setScope(sc); } for (size_t i = 0; i < members.length; i++) { Dsymbol s = (*members)[i]; s.importAll(sc); } sc = sc.pop(); sc.pop(); // 2 pops because Scope.createGlobal() created 2 } /********************************** * Determine if we need to generate an instance of ModuleInfo * for this Module. */ int needModuleInfo() { //printf("needModuleInfo() %s, %d, %d\n", toChars(), needmoduleinfo, global.params.cov); return needmoduleinfo || global.params.cov; } /******************************************* * Print deprecation warning if we're deprecated, when * this module is imported from scope sc. * * Params: * sc = the scope into which we are imported * loc = the location of the import statement */ void checkImportDeprecation(const ref Loc loc, Scope* sc) { if (md && md.isdeprecated && !sc.isDeprecated) { Expression msg = md.msg; if (StringExp se = msg ? msg.toStringExp() : null) { const slice = se.peekString(); if (slice.length) { deprecation(loc, "is deprecated - %.*s", cast(int)slice.length, slice.ptr); return; } } deprecation(loc, "is deprecated"); } } override Dsymbol search(const ref Loc loc, Identifier ident, int flags = SearchLocalsOnly) { /* Since modules can be circularly referenced, * need to stop infinite recursive searches. * This is done with the cache. */ //printf("%s Module.search('%s', flags = x%x) insearch = %d\n", toChars(), ident.toChars(), flags, insearch); if (insearch) return null; /* Qualified module searches always search their imports, * even if SearchLocalsOnly */ if (!(flags & SearchUnqualifiedModule)) flags &= ~(SearchUnqualifiedModule | SearchLocalsOnly); if (searchCacheIdent == ident && searchCacheFlags == flags) { //printf("%s Module::search('%s', flags = %d) insearch = %d searchCacheSymbol = %s\n", // toChars(), ident.toChars(), flags, insearch, searchCacheSymbol ? searchCacheSymbol.toChars() : "null"); return searchCacheSymbol; } uint errors = global.errors; insearch = true; Dsymbol s = ScopeDsymbol.search(loc, ident, flags); insearch = false; if (errors == global.errors) { // https://issues.dlang.org/show_bug.cgi?id=10752 // Can cache the result only when it does not cause // access error so the side-effect should be reproduced in later search. searchCacheIdent = ident; searchCacheSymbol = s; searchCacheFlags = flags; } return s; } override bool isPackageAccessible(Package p, Visibility visibility, int flags = 0) { if (insearch) // don't follow import cycles return false; insearch = true; scope (exit) insearch = false; if (flags & IgnorePrivateImports) visibility = Visibility(Visibility.Kind.public_); // only consider public imports return super.isPackageAccessible(p, visibility); } override Dsymbol symtabInsert(Dsymbol s) { searchCacheIdent = null; // symbol is inserted, so invalidate cache return Package.symtabInsert(s); } void deleteObjFile() { if (global.params.obj) File.remove(objfile.toChars()); if (docfile) File.remove(docfile.toChars()); } /******************************************* * Can't run semantic on s now, try again later. */ extern (D) static void addDeferredSemantic(Dsymbol s) { //printf("Module::addDeferredSemantic('%s')\n", s.toChars()); if (!deferred.contains(s)) deferred.push(s); } extern (D) static void addDeferredSemantic2(Dsymbol s) { //printf("Module::addDeferredSemantic2('%s')\n", s.toChars()); if (!deferred2.contains(s)) deferred2.push(s); } extern (D) static void addDeferredSemantic3(Dsymbol s) { //printf("Module::addDeferredSemantic3('%s')\n", s.toChars()); if (!deferred.contains(s)) deferred3.push(s); } /****************************************** * Run semantic() on deferred symbols. */ static void runDeferredSemantic() { __gshared int nested; if (nested) return; //if (deferred.length) printf("+Module::runDeferredSemantic(), len = %ld\n", deferred.length); nested++; size_t len; do { len = deferred.length; if (!len) break; Dsymbol* todo; Dsymbol* todoalloc = null; Dsymbol tmp; if (len == 1) { todo = &tmp; } else { todo = cast(Dsymbol*)Mem.check(malloc(len * Dsymbol.sizeof)); todoalloc = todo; } memcpy(todo, deferred.tdata(), len * Dsymbol.sizeof); deferred.setDim(0); foreach (i; 0..len) { Dsymbol s = todo[i]; s.dsymbolSemantic(null); //printf("deferred: %s, parent = %s\n", s.toChars(), s.parent.toChars()); } //printf("\tdeferred.length = %ld, len = %ld\n", deferred.length, len); if (todoalloc) free(todoalloc); } while (deferred.length != len); // while making progress nested--; //printf("-Module::runDeferredSemantic(), len = %ld\n", deferred.length); } static void runDeferredSemantic2() { Module.runDeferredSemantic(); Dsymbols* a = &Module.deferred2; for (size_t i = 0; i < a.length; i++) { Dsymbol s = (*a)[i]; //printf("[%d] %s semantic2a\n", i, s.toPrettyChars()); s.semantic2(null); if (global.errors) break; } a.setDim(0); } static void runDeferredSemantic3() { Module.runDeferredSemantic2(); Dsymbols* a = &Module.deferred3; for (size_t i = 0; i < a.length; i++) { Dsymbol s = (*a)[i]; //printf("[%d] %s semantic3a\n", i, s.toPrettyChars()); s.semantic3(null); if (global.errors) break; } a.setDim(0); } extern (D) static void clearCache() nothrow { foreach (Module m; amodules) m.searchCacheIdent = null; } /************************************ * Recursively look at every module this module imports, * return true if it imports m. * Can be used to detect circular imports. */ int imports(Module m) nothrow { //printf("%s Module::imports(%s)\n", toChars(), m.toChars()); version (none) { foreach (i, Module mi; aimports) printf("\t[%d] %s\n", cast(int) i, mi.toChars()); } foreach (Module mi; aimports) { if (mi == m) return true; if (!mi.insearch) { mi.insearch = true; int r = mi.imports(m); if (r) return r; } } return false; } bool isRoot() nothrow { return this.importedFrom == this; } /// Returns: Whether this module is in the `core` package and has name `ident` bool isCoreModule(Identifier ident) nothrow { return this.ident == ident && parent && parent.ident == Id.core && !parent.parent; } // Back end int doppelganger; // sub-module Symbol* cov; // private uint[] __coverage; uint* covb; // bit array of valid code line numbers Symbol* sictor; // module order independent constructor Symbol* sctor; // module constructor Symbol* sdtor; // module destructor Symbol* ssharedctor; // module shared constructor Symbol* sshareddtor; // module shared destructor Symbol* stest; // module unit test Symbol* sfilename; // symbol for filename uint[uint] ctfe_cov; /// coverage information from ctfe execution_count[line] override inout(Module) isModule() inout nothrow { return this; } override void accept(Visitor v) { v.visit(this); } /*********************************************** * Writes this module's fully-qualified name to buf * Params: * buf = The buffer to write to */ void fullyQualifiedName(ref OutBuffer buf) nothrow { buf.writestring(ident.toString()); for (auto package_ = parent; package_ !is null; package_ = package_.parent) { buf.prependstring("."); buf.prependstring(package_.ident.toChars()); } } /** Lazily initializes and returns the escape table. Turns out it eats a lot of memory. */ extern(D) Escape* escapetable() nothrow { if (!_escapetable) _escapetable = new Escape(); return _escapetable; } /**************************** * A Singleton that loads core.stdc.config * Returns: * Module of core.stdc.config, null if couldn't find it */ extern (D) static Module loadCoreStdcConfig() { __gshared Module core_stdc_config; auto pkgids = new Identifier[2]; pkgids[0] = Id.core; pkgids[1] = Id.stdc; return loadModuleFromLibrary(core_stdc_config, pkgids, Id.config); } /**************************** * A Singleton that loads core.atomic * Returns: * Module of core.atomic, null if couldn't find it */ extern (D) static Module loadCoreAtomic() { __gshared Module core_atomic; auto pkgids = new Identifier[1]; pkgids[0] = Id.core; return loadModuleFromLibrary(core_atomic, pkgids, Id.atomic); } /**************************** * A Singleton that loads std.math * Returns: * Module of std.math, null if couldn't find it */ extern (D) static Module loadStdMath() { __gshared Module std_math; auto pkgids = new Identifier[1]; pkgids[0] = Id.std; return loadModuleFromLibrary(std_math, pkgids, Id.math); } /********************************** * Load a Module from the library. * Params: * mod = cached return value of this call * pkgids = package identifiers * modid = module id * Returns: * Module loaded, null if cannot load it */ extern (D) private static Module loadModuleFromLibrary(ref Module mod, Identifier[] pkgids, Identifier modid) { if (mod) return mod; auto imp = new Import(Loc.initial, pkgids[], modid, null, true); // Module.load will call fatal() if there's no module available. // Gag the error here, pushing the error handling to the caller. const errors = global.startGagging(); imp.load(null); if (imp.mod) { imp.mod.importAll(null); imp.mod.dsymbolSemantic(null); } global.endGagging(errors); mod = imp.mod; return mod; } } /*********************************************************** */ extern (C++) struct ModuleDeclaration { Loc loc; Identifier id; Identifier[] packages; // array of Identifier's representing packages bool isdeprecated; // if it is a deprecated module Expression msg; extern (D) this(const ref Loc loc, Identifier[] packages, Identifier id, Expression msg, bool isdeprecated) { this.loc = loc; this.packages = packages; this.id = id; this.msg = msg; this.isdeprecated = isdeprecated; } extern (C++) const(char)* toChars() const { OutBuffer buf; foreach (pid; packages) { buf.writestring(pid.toString()); buf.writeByte('.'); } buf.writestring(id.toString()); return buf.extractChars(); } /// Provide a human readable representation extern (D) const(char)[] toString() const { return this.toChars().toDString; } } /**************************************** * Create array of the local classes in the Module, suitable * for inclusion in ModuleInfo * Params: * mod = the Module * aclasses = array to fill in * Returns: array of local classes */ extern (C++) void getLocalClasses(Module mod, ref ClassDeclarations aclasses) { //printf("members.length = %d\n", mod.members.length); int pushAddClassDg(size_t n, Dsymbol sm) { if (!sm) return 0; if (auto cd = sm.isClassDeclaration()) { // compatibility with previous algorithm if (cd.parent && cd.parent.isTemplateMixin()) return 0; if (cd.classKind != ClassKind.objc) aclasses.push(cd); } return 0; } ScopeDsymbol._foreach(null, mod.members, &pushAddClassDg); } /** * Process the content of a source file * * Attempts to find which encoding it is using, if it has BOM, * and then normalize the source to UTF-8. If no encoding is required, * a slice of `src` will be returned without extra allocation. * * Params: * src = Content of the source file to process * mod = Module matching `src`, used for error handling * * Returns: * UTF-8 encoded variant of `src`, stripped of any BOM, * or `null` if an error happened. */ private const(char)[] processSource (const(ubyte)[] src, Module mod) { enum SourceEncoding { utf16, utf32} enum Endian { little, big} /* * Convert a buffer from UTF32 to UTF8 * Params: * Endian = is the buffer big/little endian * buf = buffer of UTF32 data * Returns: * input buffer reencoded as UTF8 */ char[] UTF32ToUTF8(Endian endian)(const(char)[] buf) { static if (endian == Endian.little) alias readNext = Port.readlongLE; else alias readNext = Port.readlongBE; if (buf.length & 3) { mod.error("odd length of UTF-32 char source %llu", cast(ulong) buf.length); return null; } const (uint)[] eBuf = cast(const(uint)[])buf; OutBuffer dbuf; dbuf.reserve(eBuf.length); foreach (i; 0 .. eBuf.length) { const u = readNext(&eBuf[i]); if (u & ~0x7F) { if (u > 0x10FFFF) { mod.error("UTF-32 value %08x greater than 0x10FFFF", u); return null; } dbuf.writeUTF8(u); } else dbuf.writeByte(u); } dbuf.writeByte(0); //add null terminator return dbuf.extractSlice(); } /* * Convert a buffer from UTF16 to UTF8 * Params: * Endian = is the buffer big/little endian * buf = buffer of UTF16 data * Returns: * input buffer reencoded as UTF8 */ char[] UTF16ToUTF8(Endian endian)(const(char)[] buf) { static if (endian == Endian.little) alias readNext = Port.readwordLE; else alias readNext = Port.readwordBE; if (buf.length & 1) { mod.error("odd length of UTF-16 char source %llu", cast(ulong) buf.length); return null; } const (ushort)[] eBuf = cast(const(ushort)[])buf; OutBuffer dbuf; dbuf.reserve(eBuf.length); //i will be incremented in the loop for high codepoints foreach (ref i; 0 .. eBuf.length) { uint u = readNext(&eBuf[i]); if (u & ~0x7F) { if (0xD800 <= u && u < 0xDC00) { i++; if (i >= eBuf.length) { mod.error("surrogate UTF-16 high value %04x at end of file", u); return null; } const u2 = readNext(&eBuf[i]); if (u2 < 0xDC00 || 0xE000 <= u2) { mod.error("surrogate UTF-16 low value %04x out of range", u2); return null; } u = (u - 0xD7C0) << 10; u |= (u2 - 0xDC00); } else if (u >= 0xDC00 && u <= 0xDFFF) { mod.error("unpaired surrogate UTF-16 value %04x", u); return null; } else if (u == 0xFFFE || u == 0xFFFF) { mod.error("illegal UTF-16 value %04x", u); return null; } dbuf.writeUTF8(u); } else dbuf.writeByte(u); } dbuf.writeByte(0); //add a terminating null byte return dbuf.extractSlice(); } const(char)[] buf = cast(const(char)[]) src; // Assume the buffer is from memory and has not be read from disk. Assume UTF-8. if (buf.length < 2) return buf; /* Convert all non-UTF-8 formats to UTF-8. * BOM : https://www.unicode.org/faq/utf_bom.html * 00 00 FE FF UTF-32BE, big-endian * FF FE 00 00 UTF-32LE, little-endian * FE FF UTF-16BE, big-endian * FF FE UTF-16LE, little-endian * EF BB BF UTF-8 */ if (buf[0] == 0xFF && buf[1] == 0xFE) { if (buf.length >= 4 && buf[2] == 0 && buf[3] == 0) return UTF32ToUTF8!(Endian.little)(buf[4 .. $]); return UTF16ToUTF8!(Endian.little)(buf[2 .. $]); } if (buf[0] == 0xFE && buf[1] == 0xFF) return UTF16ToUTF8!(Endian.big)(buf[2 .. $]); if (buf.length >= 4 && buf[0] == 0 && buf[1] == 0 && buf[2] == 0xFE && buf[3] == 0xFF) return UTF32ToUTF8!(Endian.big)(buf[4 .. $]); if (buf.length >= 3 && buf[0] == 0xEF && buf[1] == 0xBB && buf[2] == 0xBF) return buf[3 .. $]; /* There is no BOM. Make use of Arcane Jill's insight that * the first char of D source must be ASCII to * figure out the encoding. */ if (buf.length >= 4 && buf[1] == 0 && buf[2] == 0 && buf[3] == 0) return UTF32ToUTF8!(Endian.little)(buf); if (buf.length >= 4 && buf[0] == 0 && buf[1] == 0 && buf[2] == 0) return UTF32ToUTF8!(Endian.big)(buf); // try to check for UTF-16 if (buf.length >= 2 && buf[1] == 0) return UTF16ToUTF8!(Endian.little)(buf); if (buf[0] == 0) return UTF16ToUTF8!(Endian.big)(buf); // It's UTF-8 if (buf[0] >= 0x80) { mod.error("source file must start with BOM or ASCII character, not \\x%02X", buf[0]); return null; } return buf; }
D
module d.llvm.evaluator; import d.llvm.codegen; import d.ir.expression; import d.semantic.evaluator; import util.visitor; import llvm.c.core; import llvm.c.executionEngine; import std.algorithm; import std.array; // In order to JIT. extern(C) void _d_assert(string, int); extern(C) void _d_assert_msg(string, string, int); extern(C) void _d_arraybounds(string, int); extern(C) void* _d_allocmemory(size_t); final class LLVMEvaluator : Evaluator { private CodeGenPass codeGen; this(CodeGenPass codeGen) { this.codeGen = codeGen; } CompileTimeExpression evaluate(Expression e) { if (auto ce = cast(CompileTimeExpression) e) { return ce; } // XXX: Work around not being able to pass e down. static Expression statice; auto oldStatice = statice; statice = e; scope(exit) statice = oldStatice; static CodeGenPass staticCodeGen; auto oldStaticCodeGen = staticCodeGen; staticCodeGen = codeGen; scope(exit) staticCodeGen = oldStaticCodeGen; // We agressively JIT all CTFE return jit!(function CompileTimeExpression(void[] p) { return JitRepacker(staticCodeGen, statice.location, p).visit(statice.type); })(e); } ulong evalIntegral(Expression e) in { auto t = e.type.getCanonical(); while (t.kind = TypeKing.Enum) { t = t.denum.type.getCanonical(); } assert(t.kind == TypeKind.Builtin); auto bt = t.builtin; assert(isIntegral(bt) || bt == BuiltinType.Bool); } body { return jit!(function ulong(ulong r) { return r; }, JitReturn.Direct)(e); } string evalString(Expression e) in { auto t = e.type.getCanonical(); assert(t.kind = TypeKind.Slice); auto et = t.element.getCanonical(); assert(et.builtin = BuiltinType.Char); } body { return jit!(function string(void[] p) in { assert(p.length == string.sizeof); } body { auto s = *(cast(string*) p.ptr); return s.idup; })(e); } private auto jit(alias handler, JitReturn R = JitReturn.Indirect)(Expression e) { scope(failure) LLVMDumpModule(codeGen.dmodule); // Create a global variable to hold the returned blob. auto type = codeGen.visit(e.type); static if (R == JitReturn.Direct) { auto returnType = type; } else { auto buffer = LLVMAddGlobal(codeGen.dmodule, type, "__ctBuf"); scope(exit) LLVMDeleteGlobal(buffer); LLVMSetInitializer(buffer, LLVMGetUndef(type)); import llvm.c.target; auto size = LLVMStoreSizeOfType(codeGen.targetData, type); auto returnType = LLVMInt64TypeInContext(codeGen.llvmCtx); } // Generate function signature auto funType = LLVMFunctionType(returnType, null, 0, false); auto fun = LLVMAddFunction(codeGen.dmodule, "__ctfe", funType); scope(exit) LLVMDeleteFunction(fun); auto backupCurrentBB = LLVMGetInsertBlock(codeGen.builder); scope(exit) { if (backupCurrentBB) { LLVMPositionBuilderAtEnd(codeGen.builder, backupCurrentBB); } else { LLVMClearInsertionPosition(codeGen.builder); } } auto bodyBB = LLVMAppendBasicBlockInContext(codeGen.llvmCtx, fun, ""); LLVMPositionBuilderAtEnd(codeGen.builder, bodyBB); // Generate function's body. import d.llvm.expression; auto value = ExpressionGen(codeGen).visit(e); static if (R == JitReturn.Direct) { LLVMBuildRet(codeGen.builder, value); } else { LLVMBuildStore(codeGen.builder, value, buffer); // FIXME This is 64bit only code. auto ptrToInt = LLVMBuildPtrToInt(codeGen.builder, buffer, LLVMInt64TypeInContext(codeGen.llvmCtx), ""); LLVMBuildRet(codeGen.builder, ptrToInt); } codeGen.checkModule(); auto executionEngine = createExecutionEngine(codeGen.dmodule); scope(exit) { char* errorPtr; LLVMModuleRef outMod; auto removeError = LLVMRemoveModule(executionEngine, codeGen.dmodule, &outMod, &errorPtr); if (removeError) { scope (exit) LLVMDisposeMessage(errorPtr); import std.c.string; auto error = errorPtr[0 .. strlen(errorPtr)].idup; import std.stdio; writeln(error); assert(0, "Cannot remove module from execution engine ! Exiting..."); } LLVMDisposeExecutionEngine(executionEngine); } auto result = LLVMRunFunction(executionEngine, fun, 0, null); scope(exit) LLVMDisposeGenericValue(result); static if (R == JitReturn.Direct) { return handler(LLVMGenericValueToInt(result, true)); } else { // FIXME This only works for 64 bit platforms because the retval // of the "__ctfe" is specifically a i64. This is due to MCJIT // not supporting pointer return values directly at this time. auto asInt = LLVMGenericValueToInt(result, false); return handler((cast(void*) asInt)[0 .. size]); } } private auto createExecutionEngine(LLVMModuleRef dmodule) { char* errorPtr; LLVMExecutionEngineRef executionEngine; auto creationError = LLVMCreateMCJITCompilerForModule(&executionEngine, dmodule, null, 0, &errorPtr); if (creationError) { scope(exit) LLVMDisposeMessage(errorPtr); import std.c.string; auto error = errorPtr[0 .. strlen(errorPtr)].idup; import std.stdio; writeln(error); assert(0, "Cannot create execution engine ! Exiting..."); } return executionEngine; } } private: enum JitReturn { Direct, Indirect, } struct JitRepacker { CodeGenPass codeGen; import d.location; Location location; void[] p; this(CodeGenPass codeGen, Location location, void[] p) { this.codeGen = codeGen; this.p = p; } import d.ir.type, d.ir.symbol; CompileTimeExpression visit(Type t) in { import llvm.c.target; auto size = LLVMStoreSizeOfType(codeGen.targetData, codeGen.visit(t)); import std.conv; assert( size == p.length, "Buffer of length " ~ p.length.to!string() ~ " when " ~ size.to!string() ~ " was expected" ); } out(result) { // FIXME: This does not always pass now. // assert(result.type == t, "Result type do not match"); assert(p.length == 0, "Remaining data in the buffer"); } body { return t.accept(this); } T get(T)() { scope(exit) p = p[T.sizeof .. $]; return *(cast(T*) p.ptr); } CompileTimeExpression visit(BuiltinType t) { ulong raw; switch(t) with(BuiltinType) { case Bool : return new BooleanLiteral(location, get!bool()); case Byte, Ubyte: raw = get!ubyte(); goto HandleIntegral; case Short, Ushort: raw = get!ushort(); goto HandleIntegral; case Int, Uint: raw = get!uint(); goto HandleIntegral; case Long, Ulong: raw = get!ulong(); goto HandleIntegral; HandleIntegral: return isSigned(t) ? new IntegerLiteral!true(location, raw, t) : new IntegerLiteral!false(location, raw, t); default: assert(0, "Not implemented"); } } CompileTimeExpression visitPointerOf(Type t) { assert(0, "Not implemented"); } CompileTimeExpression visitSliceOf(Type t) { if (t.kind == TypeKind.Builtin && t.builtin == BuiltinType.Char && t.qualifier == TypeQualifier.Immutable) { return new StringLiteral(location, get!string().idup); } assert(0, "Not Implemented."); } CompileTimeExpression visitArrayOf(uint size, Type t) { import llvm.c.target; uint elementSize = cast(uint) LLVMStoreSizeOfType(codeGen.targetData, codeGen.visit(t)); CompileTimeExpression[] elements; elements.reserve(size); auto buf = p; uint start = 0; scope(exit) p = buf[start .. $]; for (uint i = 0; i < size; i++) { uint end = start + elementSize; p = buf[start .. end]; start = end; elements ~= visit(t); } return new CompileTimeTupleExpression(location, t.getArray(size), elements); } CompileTimeExpression visit(Struct s) { auto type = codeGen.buildStructType(s); auto count = LLVMCountStructElementTypes(type); // Hopefully we will be able to use http://reviews.llvm.org/D10148 LLVMTypeRef[] elementTypes; elementTypes.length = count; import llvm.c.target; LLVMGetStructElementTypes(type, elementTypes.ptr); auto buf = p; auto size = LLVMStoreSizeOfType(codeGen.targetData, type); scope(exit) p = buf[size .. $]; CompileTimeExpression[] elements; uint i = 0; foreach (m; s.members) { if (auto f = cast(Field) m) { scope(success) i++; assert(f.index == i, "fields are out of order"); auto t = f.type; auto start = LLVMOffsetOfElement(codeGen.targetData, type, i); auto elementType = elementTypes[i]; auto fieldSize = LLVMStoreSizeOfType(codeGen.targetData, elementType); auto end = start + fieldSize; p = buf[start .. end]; elements ~= visit(t); } } return new CompileTimeTupleExpression(location, Type.get(s), elements); } CompileTimeExpression visit(Class c) { assert(0, "Not Implemented."); } CompileTimeExpression visit(Enum e) { auto r = visit(e.type); r.type = Type.get(e); return r; } CompileTimeExpression visit(TypeAlias a) { auto r = visit(a.type); r.type = Type.get(a); return r; } CompileTimeExpression visit(Interface i) { assert(0, "Not Implemented."); } CompileTimeExpression visit(Union u) { assert(0, "Not Implemented."); } CompileTimeExpression visit(Function f) { assert(0, "Not Implemented."); } CompileTimeExpression visit(Type[] seq) { assert(0, "Not Implemented."); } CompileTimeExpression visit(FunctionType f) { assert(0, "Not Implemented."); } CompileTimeExpression visit(TypeTemplateParameter p) { assert(0, "Not implemented."); } }
D
module witchcraft.mixins.structs; mixin template WitchcraftStruct() { import witchcraft; import std.meta; import std.traits; static class StructMixin(T) : Struct if(is(T == struct)) { this() { foreach(name; FieldNameTuple!T) { _fields[name] = new FieldMixin!(T, name); } foreach(name; __traits(derivedMembers, T)) { static if(is(typeof(__traits(getMember, T, name)) == function)) { static if(name != "__ctor" && name != "__dtor" && !__traits(isDisabled, __traits(getMember, T, name))) { foreach(index, overload; __traits(getOverloads, T, name)) { _methods[name] ~= new MethodMixin!(T, name, index); } } } } } const(Attribute)[] getAttributes() const { alias attributes = AliasSeq!(__traits(getAttributes, T)); auto values = new Attribute[attributes.length]; foreach(index, attribute; attributes) { values[index] = new AttributeImpl!attribute; } return values; } override const(Constructor)[] getConstructors() const { static if(__traits(hasMember, T, "__ctor")) { alias constructors = AliasSeq!(__traits(getOverloads, T, "__ctor")); auto values = new Constructor[constructors.length]; foreach(index, constructor; constructors) { values[index] = new ConstructorMixin!(T, index); } return values; } else { return [ ]; } } const(Type) getDeclaringType() const { alias Parent = Alias!(__traits(parent, T)); return inspect!Parent; } const(TypeInfo) getDeclaringTypeInfo() const { alias Parent = Alias!(__traits(parent, T)); static if(__traits(compiles, typeid(Parent))) { return typeid(Parent); } else { return null; } } string getFullName() const { return fullyQualifiedName!T; } string getName() const { return T.stringof; } string getProtection() const { return __traits(getProtection, T); } override const(TypeInfo) getTypeInfo() const { return typeid(T); } @property final bool isAccessible() const { return true; } } }
D
import everything; SDL_Rect orbSRect, orbDRect; SDL_Texture*[] smallOrbTextures; SDL_Texture*[] mediumOrbTextures; Orb[] activeOrbs; const int ORB_FRAMES_SMALL = 4, ORB_FRAMES_MEDIUM = 6, ORB_FRAMES_LARGE = 40; const float SMALL_TIMER = 4.1, MEDIUM_TIMER = 12.1, LARGE_TIMER = 45.1; uint sprite; int orbMargin, smallOrbMin, smallOrbXMax, smallOrbYMax, mediumOrbMin, mediumOrbXMax, mediumOrbYMax, largeOrbMin, largeOrbXMax, largeOrbYMax; float orbTimerDecay = .03, smallOrbTimer, mediumOrbTimer, largeOrbTimer; float distanceSquared(int p1x, int p1y, int p2x, int p2y) { return (p2x - p1x) * (p2x - p1x) + (p2y - p1y) * (p2y - p1y); } void createOrb( Size size, int numFrames, int min, int xMax, int yMax, int hitPointsMin, int hitPointsMax, int moveMin, int moveMax, int x, int y) { Orb o; if(x == int.max) { o.x = uniform(app.display_width + 5 + size, xMax); o.y = uniform(app.display_height + 5 + size, yMax); } else { o.x = x + uniform(-5, 5); o.y = y + uniform(-5, 5); } o.hitPoints = uniform(hitPointsMin, hitPointsMax); o.shakeTimer = 6; o.moveSpeed = uniform(moveMin,moveMax); o.angle = uniform(0,2f*PI); o.size = size; o.radius = size/2; o.radiusSquared = o.radius * o.radius; o.dx = cast(int) (o.moveSpeed * cos(o.angle)); o.dy = cast(int) (o.moveSpeed * sin(o.angle)); o.animationOffset = uniform(0, numFrames); o.animationDivisor = uniform(50, 80); // spin/speed o.spinningSpeed = uniform(-0.5f, 0.5f); // set timer for size if(size == Size.SMALL) { int orbIndex = cast(int)uniform(0, smallOrbTextures.length); o.texture = smallOrbTextures[orbIndex]; smallOrbTimer = SMALL_TIMER; } else if(size == Size.MEDIUM) { int orbIndex = cast(int)uniform(0, mediumOrbTextures.length); o.texture = mediumOrbTextures[orbIndex]; mediumOrbTimer = 8.1; } activeOrbs ~= o; } void resetTimers() { smallOrbTimer = SMALL_TIMER; mediumOrbTimer = MEDIUM_TIMER; largeOrbTimer = LARGE_TIMER; } void orbSpawner() { if(player.dead) return; if(smallOrbTimer < 0) { // size, numFrames, XYmin, xMax, yMax, // hitPointsMin, hitPointsMax, moveMax, moveMin spawn x / ; createOrb(Size.SMALL, ORB_FRAMES_SMALL, smallOrbMin, smallOrbXMax, smallOrbYMax, 3, 6, 5, 7, int.max, int.max); } else { smallOrbTimer -= orbTimerDecay; } if(mediumOrbTimer < 0) { //movespeed createOrb(Size.MEDIUM, ORB_FRAMES_MEDIUM, mediumOrbMin, mediumOrbXMax, mediumOrbYMax, 10, 15, 3,5, int.max, int.max); } else { mediumOrbTimer -= orbTimerDecay; } if(largeOrbTimer < 0) { //createOrb(Size.LARGE, ORB_FRAMES_LARGE, largeOrbMin, largeOrbXMax, largeOrbYMax, 100, 200, 1, 2); } } void checkBounds(ref Orb orb, int min, int xMax, int yMax) { if(orb.y < min) { orb.y = (yMax + orb.y); } else if(orb.y > yMax) { orb.y = (min); } if(orb.x < min) { orb.x = (xMax + orb.x); } else if(orb.x > xMax) { orb.x = (min); } } void setup() { resetTimers(); orbSRect.y = 0; utils.loadGFXFromDisk("img/orbs/small/", renderer, smallOrbTextures); foreach(texture; smallOrbTextures) assert(texture); utils.loadGFXFromDisk("img/orbs/medium/", renderer, mediumOrbTextures); foreach(texture; mediumOrbTextures) assert(texture); // setting spawn area limits for orbs, also use these for teleport edges orbMargin = 20; smallOrbMin = -Size.SMALL - orbMargin; smallOrbXMax = app.display_width + Size.SMALL + orbMargin; smallOrbYMax = app.display_height + Size.SMALL + orbMargin; mediumOrbMin = -Size.MEDIUM - orbMargin; mediumOrbXMax = app.display_width + Size.MEDIUM + orbMargin; mediumOrbYMax = app.display_height + Size.MEDIUM + orbMargin; largeOrbMin = -Size.LARGE - orbMargin; largeOrbXMax = app.display_width + Size.LARGE + orbMargin; largeOrbYMax = app.display_height + Size.LARGE + orbMargin; } void updateAndDraw() { player.currentlyBeingHit = false; foreach(ref orb; activeOrbs) { // secondary wep if(secondaryfire.secondaryFire) { if(secondaryfire.hitByBeam(orb.x, orb.y, orb.radius, player.xPos, player.yPos, gameState.angle, 120f)) // beam-hit-radius { orb.del = true; } } // player/orb float playerDist = distanceSquared(orb.x, orb.y, player.xPos, player.yPos); if(playerDist < (orb.radius + player.radius)^^2) { player.currentlyBeingHit = true; } // bullets foreach(ref bullet; bullets) { float dist = distanceSquared(orb.x, orb.y, bullet.x, bullet.y); if(dist < (orb.radius + primaryfire.radius)^^2) { if(--orb.hitPoints == 0) { orb.del = true; if(orb.size == Size.MEDIUM) { // spawn small orbs int numChildren = uniform(4,8); for(int i = 0; i < numChildren; ++i) { createOrb(Size.SMALL, ORB_FRAMES_SMALL, smallOrbMin, smallOrbXMax, smallOrbYMax, 3, 6, 5, 7, orb.x, orb.y); } } else if(orb.size == Size.LARGE) { // spawn medium orbs } } orb.isShaking = true; ringblasts.createBlast(bullet.x, bullet.y, orb.size); score.addOrbHitScore(orb.size); sparks.createSparks(bullet.x, bullet.y, bullet.dx, bullet.dy, bullet.angle, uniform(3,8)); Mix_PlayChannel(-1, orbHitSFX[uniform(0, orbHitSFX.length)], 0); bullet.del = true; } } } primaryfire.bullets = remove!(bullet => bullet.del)(bullets); activeOrbs = remove!(orb => orb.del)(activeOrbs); orbSpawner(); foreach(ref orb; activeOrbs) { orb.x += orb.dx; orb.y += orb.dy; if(orb.size == Size.SMALL) { checkBounds(orb, smallOrbMin, smallOrbXMax, smallOrbYMax); } else if(orb.size == Size.MEDIUM) { checkBounds(orb, mediumOrbMin, mediumOrbXMax, mediumOrbYMax); } else { checkBounds(orb, largeOrbMin, largeOrbXMax, largeOrbYMax); } orb.angle += orb.spinningSpeed; orbDRect.w = orb.size; orbDRect.h = orb.size; if(orb.isShaking || player.shake) { orbDRect.x = orb.x - orb.size/2 + uniform(-7, 7); orbDRect.y = orb.y - orb.size/2 + uniform(-7, 7); orb.shakeTimer -= 0.1; if(orb.shakeTimer < 0) { orb.isShaking = false; orb.shakeTimer = 4; } } else { orbDRect.x = orb.x - orb.size/2; orbDRect.y = orb.y - orb.size/2; } orbSRect.w = orb.size; orbSRect.h = orb.size; sprite = ((app.ticks / orb.animationDivisor) + orb.animationOffset); if(orb.size == Size.SMALL) sprite %= ORB_FRAMES_SMALL; else if(orb.size == Size.MEDIUM) sprite %= ORB_FRAMES_MEDIUM; else sprite %= ORB_FRAMES_LARGE; orbSRect.x = sprite * orb.size; SDL_RenderCopyEx(renderer, orb.texture, &orbSRect, &orbDRect, orb.angle, null, 0); } }
D
import std.string; import std.stdio; import std.conv; import utils_hash; import std.digest.sha; import std.digest.crc; class Node { private char[64] _hash; private Node _parent; private Node _left; private Node _right; private bool _leaf; private bool _root; private bool _duplicate; // abstract == overriding forced // verify the node's subtree hash, return it abstract string verify () { return ""; } // properties @property inout(Node) left() inout { return _left; } @property inout(Node) right() inout { return _right; } @property inout(Node) parent() inout { return _parent; } // overloads to add new left, right, parent @property Node left (Node n) { return _left = n; } @property Node right (Node n) { return _right = n; } @property Node parent(Node n) { return _parent = n; } // flag duplicate nodes @property bool duplicate () { return _duplicate; } // set a node as duplicate @property bool duplicate (bool v) { return _duplicate = v; } // get the hash as a char array @property string hash () { return cast(string)this._hash; } @property char[64] hash (char[64] h) { return this._hash = h; } // LeafNode or InternalNode (faster way of discriminating) @property bool leaf (){ return _leaf; } @property bool leaf (bool v) { return _leaf = v; } @property bool root (){ return _root; } @property bool root (bool v) { return _root = v; } } class LeafNode : Node { // the block id (unique) uint blockId; private ubyte[] data; this (uint bId, ubyte[] d) { leaf = true; data = d; duplicate = false; blockId = bId; } string computeHash(Hash)() { hash = produceHash!Hash(to!string(data), leaf); return hash; } override string verify () { // this node is a leaf, thus return the computed hash auto h = computeHash!SHA256(); return h; } } class InternalNode : Node { // intialize the InternalNode node // the parent must be provided, // default is null for root this (Node l, Node r) { leaf = false; root = true; duplicate = false; if (parent !is null) { parent = parent; root = false; } else { root = true; } left = l; right = r; } string computeHash(Hash)(string lhash, string rhash) { // concatenate the two childrens' hashes into a string string data = lhash ~ rhash; // hash the string hash = produceHash!Hash(data, leaf); return hash; } override string verify () { // the node is not a leaf, recur on the subnodes auto h = computeHash!SHA256(left.verify(), right.verify()); return h; } } unittest { ubyte[] input = []; auto l = new LeafNode(0, input); auto theHash = produceHash!SHA256(to!string(input), l.leaf); assert (theHash == l.computeHash!SHA256()); } unittest { ubyte[] input = []; auto l = new LeafNode(0, input); auto r = new LeafNode(1, input); auto internal = new InternalNode (l,r); LeafNode intL = cast(LeafNode) internal.left; LeafNode intR = cast(LeafNode) internal.right; assert (intL.blockId == l.blockId); assert (intR.blockId == r.blockId); } //** Testing Purpose (uncomment)** //void main () {}
D
/* TEST_OUTPUT: --- fail_compilation/fail161.d(15): Error: template instance `MetaString!"2 == 1"` does not match template declaration `MetaString(String)` --- */ template MetaString(String) { alias String Value; } void main() { alias MetaString!("2 == 1") S; assert(mixin(S.Value)); }
D
import std.conv; import Experiment; class Interaction{ public: string label; Experiment experience; string result; int weight = 0; int valence; Interaction preInteraction; Interaction postInteraction; this( string label ){ this.label = label; } void incrementWeight() { weight++; } override string toString(){ return label ~ " valence " ~ to!string( valence ) ~ ", weight " ~ to!string( weight ); } bool isPrimitive(){ return (preInteraction is null); } }
D
/* TEST_OUTPUT: --- fail_compilation/circ10280.d(11): Error: circular initialization of variable `circ10280.q10280` fail_compilation/circ10280.d(10): called from here: `foo10280()` --- */ // https://issues.dlang.org/show_bug.cgi?id=10280 const int q10280 = foo10280(); int foo10280() { return q10280; }
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/dmodule.d, _dmodule.d) * Documentation: https://dlang.org/phobos/dmd_dmodule.html * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/dmodule.d */ module dmd.dmodule; import core.stdc.stdio; import core.stdc.stdlib; import core.stdc.string; import dmd.aggregate; import dmd.arraytypes; import dmd.astcodegen; import dmd.compiler; import dmd.gluelayer; import dmd.dimport; import dmd.dmacro; import dmd.doc; import dmd.dscope; import dmd.dsymbol; import dmd.dsymbolsem; import dmd.errors; import dmd.expression; import dmd.expressionsem; import dmd.globals; import dmd.id; import dmd.identifier; import dmd.parse; import dmd.root.file; import dmd.root.filename; import dmd.root.outbuffer; import dmd.root.port; import dmd.root.rmem; import dmd.root.rootobject; import dmd.root.string; import dmd.semantic2; import dmd.semantic3; import dmd.visitor; version(Windows) { extern (C) char* getcwd(char* buffer, size_t maxlen); } else { import core.sys.posix.unistd : getcwd; } /* =========================== ===================== */ /******************************************** * Look for the source file if it's different from filename. * Look for .di, .d, directory, and along global.path. * Does not open the file. * Input: * filename as supplied by the user * global.path * Returns: * NULL if it's not different from filename. */ private const(char)[] lookForSourceFile(const(char)[] filename) { /* Search along global.path for .di file, then .d file. */ const sdi = FileName.forceExt(filename, global.hdr_ext); if (FileName.exists(sdi) == 1) return sdi; scope(exit) FileName.free(sdi.ptr); const sd = FileName.forceExt(filename, global.mars_ext); if (FileName.exists(sd) == 1) return sd; scope(exit) FileName.free(sd.ptr); if (FileName.exists(filename) == 2) { /* The filename exists and it's a directory. * Therefore, the result should be: filename/package.d * iff filename/package.d is a file */ const ni = FileName.combine(filename, "package.di"); if (FileName.exists(ni) == 1) return ni; FileName.free(ni.ptr); const n = FileName.combine(filename, "package.d"); if (FileName.exists(n) == 1) return n; FileName.free(n.ptr); } if (FileName.absolute(filename)) return null; if (!global.path) return null; for (size_t i = 0; i < global.path.dim; i++) { const p = (*global.path)[i].toDString(); const(char)[] n = FileName.combine(p, sdi); if (FileName.exists(n) == 1) { return n; } FileName.free(n.ptr); n = FileName.combine(p, sd); if (FileName.exists(n) == 1) { return n; } FileName.free(n.ptr); const b = FileName.removeExt(filename); n = FileName.combine(p, b); FileName.free(b.ptr); if (FileName.exists(n) == 2) { const n2i = FileName.combine(n, "package.di"); if (FileName.exists(n2i) == 1) return n2i; FileName.free(n2i.ptr); const n2 = FileName.combine(n, "package.d"); if (FileName.exists(n2) == 1) { return n2; } FileName.free(n2.ptr); } FileName.free(n.ptr); } return null; } // function used to call semantic3 on a module's dependencies void semantic3OnDependencies(Module m) { if (!m) return; if (m.semanticRun > PASS.semantic3) return; m.semantic3(null); foreach (i; 1 .. m.aimports.dim) semantic3OnDependencies(m.aimports[i]); } /** * Converts a chain of identifiers to the filename of the module * * Params: * packages = the names of the "parent" packages * ident = the name of the child package or module * * Returns: * the filename of the child package or module */ private const(char)[] getFilename(Identifiers* packages, Identifier ident) { const(char)[] filename = ident.toString(); if (packages == null || packages.dim == 0) return filename; OutBuffer buf; OutBuffer dotmods; auto modAliases = &global.params.modFileAliasStrings; void checkModFileAlias(const(char)[] p) { /* Check and replace the contents of buf[] with * an alias string from global.params.modFileAliasStrings[] */ dotmods.writestring(p); foreach_reverse (const m; *modAliases) { const q = strchr(m, '='); assert(q); if (dotmods.length == q - m && memcmp(dotmods.peekChars(), m, q - m) == 0) { buf.setsize(0); auto rhs = q[1 .. strlen(q)]; if (rhs.length > 0 && (rhs[$ - 1] == '/' || rhs[$ - 1] == '\\')) rhs = rhs[0 .. $ - 1]; // remove trailing separator buf.writestring(rhs); break; // last matching entry in ms[] wins } } dotmods.writeByte('.'); } foreach (pid; *packages) { const p = pid.toString(); buf.writestring(p); if (modAliases.dim) checkModFileAlias(p); version (Windows) enum FileSeparator = '\\'; else enum FileSeparator = '/'; buf.writeByte(FileSeparator); } buf.writestring(filename); if (modAliases.dim) checkModFileAlias(filename); buf.writeByte(0); filename = buf.extractSlice()[0 .. $ - 1]; return filename; } enum PKG : int { unknown, // not yet determined whether it's a package.d or not module_, // already determined that's an actual package.d package_, // already determined that's an actual package } /*********************************************************** */ extern (C++) class Package : ScopeDsymbol { PKG isPkgMod = PKG.unknown; uint tag; // auto incremented tag, used to mask package tree in scopes Module mod; // !=null if isPkgMod == PKG.module_ final extern (D) this(const ref Loc loc, Identifier ident) { super(loc, ident); __gshared uint packageTag; this.tag = packageTag++; } override const(char)* kind() const { return "package"; } override bool equals(const RootObject o) const { // custom 'equals' for bug 17441. "package a" and "module a" are not equal if (this == o) return true; auto p = cast(Package)o; return p && isModule() == p.isModule() && ident.equals(p.ident); } /**************************************************** * Input: * packages[] the pkg1.pkg2 of pkg1.pkg2.mod * Returns: * the symbol table that mod should be inserted into * Output: * *pparent the rightmost package, i.e. pkg2, or NULL if no packages * *ppkg the leftmost package, i.e. pkg1, or NULL if no packages */ extern (D) static DsymbolTable resolve(Identifiers* packages, Dsymbol* pparent, Package* ppkg) { DsymbolTable dst = Module.modules; Dsymbol parent = null; //printf("Package::resolve()\n"); if (ppkg) *ppkg = null; if (packages) { for (size_t i = 0; i < packages.dim; i++) { Identifier pid = (*packages)[i]; Package pkg; Dsymbol p = dst.lookup(pid); if (!p) { pkg = new Package(Loc.initial, pid); dst.insert(pkg); pkg.parent = parent; pkg.symtab = new DsymbolTable(); } else { pkg = p.isPackage(); assert(pkg); // It might already be a module, not a package, but that needs // to be checked at a higher level, where a nice error message // can be generated. // dot net needs modules and packages with same name // But we still need a symbol table for it if (!pkg.symtab) pkg.symtab = new DsymbolTable(); } parent = pkg; dst = pkg.symtab; if (ppkg && !*ppkg) *ppkg = pkg; if (pkg.isModule()) { // Return the module so that a nice error message can be generated if (ppkg) *ppkg = cast(Package)p; break; } } } if (pparent) *pparent = parent; return dst; } override final inout(Package) isPackage() inout { return this; } /** * Checks if pkg is a sub-package of this * * For example, if this qualifies to 'a1.a2' and pkg - to 'a1.a2.a3', * this function returns 'true'. If it is other way around or qualified * package paths conflict function returns 'false'. * * Params: * pkg = possible subpackage * * Returns: * see description */ final bool isAncestorPackageOf(const Package pkg) const { if (this == pkg) return true; if (!pkg || !pkg.parent) return false; return isAncestorPackageOf(pkg.parent.isPackage()); } override Dsymbol search(const ref Loc loc, Identifier ident, int flags = SearchLocalsOnly) { //printf("%s Package.search('%s', flags = x%x)\n", toChars(), ident.toChars(), flags); flags &= ~SearchLocalsOnly; // searching an import is always transitive if (!isModule() && mod) { // Prefer full package name. Dsymbol s = symtab ? symtab.lookup(ident) : null; if (s) return s; //printf("[%s] through pkdmod: %s\n", loc.toChars(), toChars()); return mod.search(loc, ident, flags); } return ScopeDsymbol.search(loc, ident, flags); } override void accept(Visitor v) { v.visit(this); } final Module isPackageMod() { if (isPkgMod == PKG.module_) { return mod; } return null; } /** * Checks for the existence of a package.d to set isPkgMod appropriately * if isPkgMod == PKG.unknown */ final void resolvePKGunknown() { if (isModule()) return; if (isPkgMod != PKG.unknown) return; Identifiers packages; for (Dsymbol s = this.parent; s; s = s.parent) packages.insert(0, s.ident); if (lookForSourceFile(getFilename(&packages, ident))) Module.load(Loc(), &packages, this.ident); else isPkgMod = PKG.package_; } } /*********************************************************** */ extern (C++) final class Module : Package { extern (C++) __gshared Module rootModule; extern (C++) __gshared DsymbolTable modules; // symbol table of all modules extern (C++) __gshared Modules amodules; // array of all modules extern (C++) __gshared Dsymbols deferred; // deferred Dsymbol's needing semantic() run on them extern (C++) __gshared Dsymbols deferred2; // deferred Dsymbol's needing semantic2() run on them extern (C++) __gshared Dsymbols deferred3; // deferred Dsymbol's needing semantic3() run on them extern (C++) __gshared uint dprogress; // progress resolving the deferred list static void _init() { modules = new DsymbolTable(); } /** * Deinitializes the global state of the compiler. * * This can be used to restore the state set by `_init` to its original * state. */ static void deinitialize() { modules = modules.init; } extern (C++) __gshared AggregateDeclaration moduleinfo; const(char)[] arg; // original argument name ModuleDeclaration* md; // if !=null, the contents of the ModuleDeclaration declaration const FileName srcfile; // input source file const FileName objfile; // output .obj file const FileName hdrfile; // 'header' file FileName docfile; // output documentation file FileBuffer* srcBuffer; // set during load(), free'd in parse() uint errors; // if any errors in file uint numlines; // number of lines in source file bool isHdrFile; // if it is a header (.di) file bool isDocFile; // if it is a documentation input file, not D source bool isPackageFile; // if it is a package.d Package pkg; // if isPackageFile is true, the Package that contains this package.d Strings contentImportedFiles; // array of files whose content was imported int needmoduleinfo; int selfimports; // 0: don't know, 1: does not, 2: does /************************************* * Return true if module imports itself. */ bool selfImports() { //printf("Module::selfImports() %s\n", toChars()); if (selfimports == 0) { for (size_t i = 0; i < amodules.dim; i++) amodules[i].insearch = 0; selfimports = imports(this) + 1; for (size_t i = 0; i < amodules.dim; i++) amodules[i].insearch = 0; } return selfimports == 2; } int rootimports; // 0: don't know, 1: does not, 2: does /************************************* * Return true if module imports root module. */ bool rootImports() { //printf("Module::rootImports() %s\n", toChars()); if (rootimports == 0) { for (size_t i = 0; i < amodules.dim; i++) amodules[i].insearch = 0; rootimports = 1; for (size_t i = 0; i < amodules.dim; ++i) { Module m = amodules[i]; if (m.isRoot() && imports(m)) { rootimports = 2; break; } } for (size_t i = 0; i < amodules.dim; i++) amodules[i].insearch = 0; } return rootimports == 2; } int insearch; Identifier searchCacheIdent; Dsymbol searchCacheSymbol; // cached value of search int searchCacheFlags; // cached flags /** * A root module is one that will be compiled all the way to * object code. This field holds the root module that caused * this module to be loaded. If this module is a root module, * then it will be set to `this`. This is used to determine * ownership of template instantiation. */ Module importedFrom; Dsymbols* decldefs; // top level declarations for this Module Modules aimports; // all imported modules uint debuglevel; // debug level Identifiers* debugids; // debug identifiers Identifiers* debugidsNot; // forward referenced debug identifiers uint versionlevel; // version level Identifiers* versionids; // version identifiers Identifiers* versionidsNot; // forward referenced version identifiers MacroTable macrotable; // document comment macros Escape* escapetable; // document comment escapes size_t nameoffset; // offset of module name from start of ModuleInfo size_t namelen; // length of module name in characters extern (D) this(const ref Loc loc, const(char)[] filename, Identifier ident, int doDocComment, int doHdrGen) { super(loc, ident); const(char)[] srcfilename; //printf("Module::Module(filename = '%s', ident = '%s')\n", filename, ident.toChars()); this.arg = filename; srcfilename = FileName.defaultExt(filename, global.mars_ext); if (global.run_noext && global.params.run && !FileName.ext(filename) && FileName.exists(srcfilename) == 0 && FileName.exists(filename) == 1) { FileName.free(srcfilename.ptr); srcfilename = FileName.removeExt(filename); // just does a mem.strdup(filename) } else if (!FileName.equalsExt(srcfilename, global.mars_ext) && !FileName.equalsExt(srcfilename, global.hdr_ext) && !FileName.equalsExt(srcfilename, "dd")) { error("source file name '%.*s' must have .%.*s extension", cast(int)srcfilename.length, srcfilename.ptr, cast(int)global.mars_ext.length, global.mars_ext.ptr); fatal(); } srcfile = FileName(srcfilename); objfile = setOutfilename(global.params.objname, global.params.objdir, filename, global.obj_ext); if (doDocComment) setDocfile(); if (doHdrGen) hdrfile = setOutfilename(global.params.hdrname, global.params.hdrdir, arg, global.hdr_ext); escapetable = new Escape(); } extern (D) this(const(char)[] filename, Identifier ident, int doDocComment, int doHdrGen) { this(Loc.initial, filename, ident, doDocComment, doHdrGen); } static Module create(const(char)* filename, Identifier ident, int doDocComment, int doHdrGen) { return create(filename.toDString, ident, doDocComment, doHdrGen); } extern (D) static Module create(const(char)[] filename, Identifier ident, int doDocComment, int doHdrGen) { return new Module(Loc.initial, filename, ident, doDocComment, doHdrGen); } static Module load(Loc loc, Identifiers* packages, Identifier ident) { //printf("Module::load(ident = '%s')\n", ident.toChars()); // Build module filename by turning: // foo.bar.baz // into: // foo\bar\baz const(char)[] filename = getFilename(packages, ident); // Look for the source file if (const result = lookForSourceFile(filename)) filename = result; // leaks auto m = new Module(loc, filename, ident, 0, 0); if (!m.read(loc)) return null; if (global.params.verbose) { OutBuffer buf; if (packages) { foreach (pid; *packages) { buf.writestring(pid.toString()); buf.writeByte('.'); } } buf.printf("%s\t(%s)", ident.toChars(), m.srcfile.toChars()); message("import %s", buf.peekChars()); } m = m.parse(); // Call onImport here because if the module is going to be compiled then we // need to determine it early because it affects semantic analysis. This is // being done after parsing the module so the full module name can be taken // from whatever was declared in the file. if (!m.isRoot() && Compiler.onImport(m)) { m.importedFrom = m; assert(m.isRoot()); } Compiler.loadModule(m); return m; } override const(char)* kind() const { return "module"; } /********************************************* * Combines things into output file name for .html and .di files. * Input: * name Command line name given for the file, NULL if none * dir Command line directory given for the file, NULL if none * arg Name of the source file * ext File name extension to use if 'name' is NULL * global.params.preservePaths get output path from arg * srcfile Input file - output file name must not match input file */ extern(D) FileName setOutfilename(const(char)[] name, const(char)[] dir, const(char)[] arg, const(char)[] ext) { const(char)[] docfilename; if (name) { docfilename = name; } else { const(char)[] argdoc; OutBuffer buf; if (arg == "__stdin.d") { version (Posix) import core.sys.posix.unistd : getpid; else version (Windows) import core.sys.windows.winbase : getpid = GetCurrentProcessId; buf.printf("__stdin_%d.d", getpid()); arg = buf[]; } if (global.params.preservePaths) argdoc = arg; else argdoc = FileName.name(arg); // If argdoc doesn't have an absolute path, make it relative to dir if (!FileName.absolute(argdoc)) { //FileName::ensurePathExists(dir); argdoc = FileName.combine(dir, argdoc); } docfilename = FileName.forceExt(argdoc, ext); } if (FileName.equals(docfilename, srcfile.toString())) { error("source file and output file have same name '%s'", srcfile.toChars()); fatal(); } return FileName(docfilename); } extern (D) void setDocfile() { docfile = setOutfilename(global.params.docname, global.params.docdir, arg, global.doc_ext); } /** * Loads the source buffer from the given read result into `this.srcBuffer`. * * Will take ownership of the buffer located inside `readResult`. * * Params: * loc = the location * readResult = the result of reading a file containing the source code * * Returns: `true` if successful */ bool loadSourceBuffer(const ref Loc loc, ref File.ReadResult readResult) { //printf("Module::loadSourceBuffer('%s') file '%s'\n", toChars(), srcfile.toChars()); // take ownership of buffer srcBuffer = new FileBuffer(readResult.extractSlice()); if (readResult.success) return true; if (FileName.equals(srcfile.toString(), "object.d")) { .error(loc, "cannot find source code for runtime library file 'object.d'"); errorSupplemental(loc, "dmd might not be correctly installed. Run 'dmd -man' for installation instructions."); const dmdConfFile = global.inifilename.length ? FileName.canonicalName(global.inifilename) : "not found"; errorSupplemental(loc, "config file: %.*s", cast(int)dmdConfFile.length, dmdConfFile.ptr); } else { // if module is not named 'package' but we're trying to read 'package.d', we're looking for a package module bool isPackageMod = (strcmp(toChars(), "package") != 0) && (strcmp(srcfile.name(), "package.d") == 0 || (strcmp(srcfile.name(), "package.di") == 0)); if (isPackageMod) .error(loc, "importing package '%s' requires a 'package.d' file which cannot be found in '%s'", toChars(), srcfile.toChars()); else error(loc, "is in file '%s' which cannot be read", srcfile.toChars()); } if (!global.gag) { /* Print path */ if (global.path) { foreach (i, p; *global.path) fprintf(stderr, "import path[%llu] = %s\n", cast(ulong)i, p); } else fprintf(stderr, "Specify path to file '%s' with -I switch\n", srcfile.toChars()); // fatal(); } return false; } /** * Reads the file from `srcfile` and loads the source buffer. * * Params: * loc = the location * * Returns: `true` if successful * See_Also: loadSourceBuffer */ bool read(const ref Loc loc) { if (srcBuffer) return true; // already read //printf("Module::read('%s') file '%s'\n", toChars(), srcfile.toChars()); auto readResult = File.read(srcfile.toChars()); return loadSourceBuffer(loc, readResult); } /// syntactic parse Module parse() { return parseModule!ASTCodegen(); } /// ditto extern (D) Module parseModule(AST)() { enum Endian { little, big} enum SourceEncoding { utf16, utf32} /* * Convert a buffer from UTF32 to UTF8 * Params: * Endian = is the buffer big/little endian * buf = buffer of UTF32 data * Returns: * input buffer reencoded as UTF8 */ char[] UTF32ToUTF8(Endian endian)(const(char)[] buf) { static if (endian == Endian.little) alias readNext = Port.readlongLE; else alias readNext = Port.readlongBE; if (buf.length & 3) { error("odd length of UTF-32 char source %u", buf.length); fatal(); } const (uint)[] eBuf = cast(const(uint)[])buf; OutBuffer dbuf; dbuf.reserve(eBuf.length); foreach (i; 0 .. eBuf.length) { const u = readNext(&eBuf[i]); if (u & ~0x7F) { if (u > 0x10FFFF) { error("UTF-32 value %08x greater than 0x10FFFF", u); fatal(); } dbuf.writeUTF8(u); } else dbuf.writeByte(u); } dbuf.writeByte(0); //add null terminator return dbuf.extractSlice(); } /* * Convert a buffer from UTF16 to UTF8 * Params: * Endian = is the buffer big/little endian * buf = buffer of UTF16 data * Returns: * input buffer reencoded as UTF8 */ char[] UTF16ToUTF8(Endian endian)(const(char)[] buf) { static if (endian == Endian.little) alias readNext = Port.readwordLE; else alias readNext = Port.readwordBE; if (buf.length & 1) { error("odd length of UTF-16 char source %u", buf.length); fatal(); } const (ushort)[] eBuf = cast(const(ushort)[])buf; OutBuffer dbuf; dbuf.reserve(eBuf.length); //i will be incremented in the loop for high codepoints foreach (ref i; 0 .. eBuf.length) { uint u = readNext(&eBuf[i]); if (u & ~0x7F) { if (0xD800 <= u && u < 0xDC00) { i++; if (i >= eBuf.length) { error("surrogate UTF-16 high value %04x at end of file", u); fatal(); } const u2 = readNext(&eBuf[i]); if (u2 < 0xDC00 || 0xE000 <= u2) { error("surrogate UTF-16 low value %04x out of range", u2); fatal(); } u = (u - 0xD7C0) << 10; u |= (u2 - 0xDC00); } else if (u >= 0xDC00 && u <= 0xDFFF) { error("unpaired surrogate UTF-16 value %04x", u); fatal(); } else if (u == 0xFFFE || u == 0xFFFF) { error("illegal UTF-16 value %04x", u); fatal(); } dbuf.writeUTF8(u); } else dbuf.writeByte(u); } dbuf.writeByte(0); //add a terminating null byte return dbuf.extractSlice(); } const(char)* srcname = srcfile.toChars(); //printf("Module::parse(srcname = '%s')\n", srcname); isPackageFile = (strcmp(srcfile.name(), "package.d") == 0 || strcmp(srcfile.name(), "package.di") == 0); const(char)[] buf = cast(const(char)[]) srcBuffer.data; bool needsReencoding = true; bool hasBOM = true; //assume there's a BOM Endian endian; SourceEncoding sourceEncoding; if (buf.length >= 2) { /* Convert all non-UTF-8 formats to UTF-8. * BOM : http://www.unicode.org/faq/utf_bom.html * 00 00 FE FF UTF-32BE, big-endian * FF FE 00 00 UTF-32LE, little-endian * FE FF UTF-16BE, big-endian * FF FE UTF-16LE, little-endian * EF BB BF UTF-8 */ if (buf[0] == 0xFF && buf[1] == 0xFE) { endian = Endian.little; sourceEncoding = buf.length >= 4 && buf[2] == 0 && buf[3] == 0 ? SourceEncoding.utf32 : SourceEncoding.utf16; } else if (buf[0] == 0xFE && buf[1] == 0xFF) { endian = Endian.big; sourceEncoding = SourceEncoding.utf16; } else if (buf.length >= 4 && buf[0] == 0 && buf[1] == 0 && buf[2] == 0xFE && buf[3] == 0xFF) { endian = Endian.big; sourceEncoding = SourceEncoding.utf32; } else if (buf.length >= 3 && buf[0] == 0xEF && buf[1] == 0xBB && buf[2] == 0xBF) { needsReencoding = false;//utf8 with BOM } else { /* There is no BOM. Make use of Arcane Jill's insight that * the first char of D source must be ASCII to * figure out the encoding. */ hasBOM = false; if (buf.length >= 4 && buf[1] == 0 && buf[2] == 0 && buf[3] == 0) { endian = Endian.little; sourceEncoding = SourceEncoding.utf32; } else if (buf.length >= 4 && buf[0] == 0 && buf[1] == 0 && buf[2] == 0) { endian = Endian.big; sourceEncoding = SourceEncoding.utf32; } else if (buf.length >= 2 && buf[1] == 0) //try to check for UTF-16 { endian = Endian.little; sourceEncoding = SourceEncoding.utf16; } else if (buf[0] == 0) { endian = Endian.big; sourceEncoding = SourceEncoding.utf16; } else { // It's UTF-8 needsReencoding = false; if (buf[0] >= 0x80) { error("source file must start with BOM or ASCII character, not \\x%02X", buf[0]); fatal(); } } } //throw away BOM if (hasBOM) { if (!needsReencoding) buf = buf[3..$];// utf-8 already else if (sourceEncoding == SourceEncoding.utf32) buf = buf[4..$]; else buf = buf[2..$]; //utf 16 } } // Assume the buffer is from memory and has not be read from disk. Assume UTF-8. else if (buf.length >= 1 && (buf[0] == '\0' || buf[0] == 0x1A)) needsReencoding = false; //printf("%s, %d, %d, %d\n", srcfile.name.toChars(), needsReencoding, endian == Endian.little, sourceEncoding == SourceEncoding.utf16); if (needsReencoding) { if (sourceEncoding == SourceEncoding.utf16) { buf = endian == Endian.little ? UTF16ToUTF8!(Endian.little)(buf) : UTF16ToUTF8!(Endian.big)(buf); } else { buf = endian == Endian.little ? UTF32ToUTF8!(Endian.little)(buf) : UTF32ToUTF8!(Endian.big)(buf); } } /* If it starts with the string "Ddoc", then it's a documentation * source file. */ if (buf.length>= 4 && buf[0..4] == "Ddoc") { comment = buf.ptr + 4; isDocFile = true; if (!docfile) setDocfile(); return this; } /* If it has the extension ".dd", it is also a documentation * source file. Documentation source files may begin with "Ddoc" * but do not have to if they have the .dd extension. * https://issues.dlang.org/show_bug.cgi?id=15465 */ if (FileName.equalsExt(arg, "dd")) { comment = buf.ptr; // the optional Ddoc, if present, is handled above. isDocFile = true; if (!docfile) setDocfile(); return this; } /* If it has the extension ".di", it is a "header" file. */ if (FileName.equalsExt(arg, "di")) { isHdrFile = true; } { scope p = new Parser!AST(this, buf, cast(bool) docfile); p.nextToken(); members = p.parseModule(); md = p.md; numlines = p.scanloc.linnum; } srcBuffer.destroy(); srcBuffer = null; /* The symbol table into which the module is to be inserted. */ DsymbolTable dst; if (md) { /* A ModuleDeclaration, md, was provided. * The ModuleDeclaration sets the packages this module appears in, and * the name of this module. */ this.ident = md.id; Package ppack = null; dst = Package.resolve(md.packages, &this.parent, &ppack); assert(dst); Module m = ppack ? ppack.isModule() : null; if (m && (strcmp(m.srcfile.name(), "package.d") != 0 && strcmp(m.srcfile.name(), "package.di") != 0)) { .error(md.loc, "package name '%s' conflicts with usage as a module name in file %s", ppack.toPrettyChars(), m.srcfile.toChars()); } } else { /* The name of the module is set to the source file name. * There are no packages. */ dst = modules; // and so this module goes into global module symbol table /* Check to see if module name is a valid identifier */ if (!Identifier.isValidIdentifier(this.ident.toChars())) error("has non-identifier characters in filename, use module declaration instead"); } // Insert module into the symbol table Dsymbol s = this; if (isPackageFile) { /* If the source tree is as follows: * pkg/ * +- package.d * +- common.d * the 'pkg' will be incorporated to the internal package tree in two ways: * import pkg; * and: * import pkg.common; * * If both are used in one compilation, 'pkg' as a module (== pkg/package.d) * and a package name 'pkg' will conflict each other. * * To avoid the conflict: * 1. If preceding package name insertion had occurred by Package::resolve, * reuse the previous wrapping 'Package' if it exists * 2. Otherwise, 'package.d' wrapped by 'Package' is inserted to the internal tree in here. * * Then change Package::isPkgMod to PKG.module_ and set Package::mod. * * Note that the 'wrapping Package' is the Package that contains package.d and other submodules, * the one inserted to the symbol table. */ auto ps = dst.lookup(ident); Package p = ps ? ps.isPackage() : null; if (p is null) { p = new Package(Loc.initial, ident); p.tag = this.tag; // reuse the same package tag p.symtab = new DsymbolTable(); } this.tag = p.tag; // reuse the 'older' package tag this.pkg = p; p.parent = this.parent; p.isPkgMod = PKG.module_; p.mod = this; s = p; } if (!dst.insert(s)) { /* It conflicts with a name that is already in the symbol table. * Figure out what went wrong, and issue error message. */ Dsymbol prev = dst.lookup(ident); assert(prev); if (Module mprev = prev.isModule()) { if (!FileName.equals(srcname, mprev.srcfile.toChars())) error(loc, "from file %s conflicts with another module %s from file %s", srcname, mprev.toChars(), mprev.srcfile.toChars()); else if (isRoot() && mprev.isRoot()) error(loc, "from file %s is specified twice on the command line", srcname); else error(loc, "from file %s must be imported with 'import %s;'", srcname, toPrettyChars()); // https://issues.dlang.org/show_bug.cgi?id=14446 // Return previously parsed module to avoid AST duplication ICE. return mprev; } else if (Package pkg = prev.isPackage()) { // 'package.d' loaded after a previous 'Package' insertion if (isPackageFile) amodules.push(this); // Add to global array of all modules else error(md ? md.loc : loc, "from file %s conflicts with package name %s", srcname, pkg.toChars()); } else assert(global.errors); } else { // Add to global array of all modules amodules.push(this); } return this; } override void importAll(Scope* prevsc) { //printf("+Module::importAll(this = %p, '%s'): parent = %p\n", this, toChars(), parent); if (_scope) return; // already done if (isDocFile) { error("is a Ddoc file, cannot import it"); return; } /* Note that modules get their own scope, from scratch. * This is so regardless of where in the syntax a module * gets imported, it is unaffected by context. * Ignore prevsc. */ Scope* sc = Scope.createGlobal(this); // create root scope if (md && md.msg) md.msg = semanticString(sc, md.msg, "deprecation message"); // Add import of "object", even for the "object" module. // If it isn't there, some compiler rewrites, like // classinst == classinst -> .object.opEquals(classinst, classinst) // would fail inside object.d. if (members.dim == 0 || (*members)[0].ident != Id.object || (*members)[0].isImport() is null) { auto im = new Import(Loc.initial, null, Id.object, null, 0); members.shift(im); } if (!symtab) { // Add all symbols into module's symbol table symtab = new DsymbolTable(); for (size_t i = 0; i < members.dim; i++) { Dsymbol s = (*members)[i]; s.addMember(sc, sc.scopesym); } } // anything else should be run after addMember, so version/debug symbols are defined /* Set scope for the symbols so that if we forward reference * a symbol, it can possibly be resolved on the spot. * If this works out well, it can be extended to all modules * before any semantic() on any of them. */ setScope(sc); // remember module scope for semantic for (size_t i = 0; i < members.dim; i++) { Dsymbol s = (*members)[i]; s.setScope(sc); } for (size_t i = 0; i < members.dim; i++) { Dsymbol s = (*members)[i]; s.importAll(sc); } sc = sc.pop(); sc.pop(); // 2 pops because Scope::createGlobal() created 2 } /********************************** * Determine if we need to generate an instance of ModuleInfo * for this Module. */ int needModuleInfo() { //printf("needModuleInfo() %s, %d, %d\n", toChars(), needmoduleinfo, global.params.cov); return needmoduleinfo || global.params.cov; } /******************************************* * Print deprecation warning if we're deprecated, when * this module is imported from scope sc. * * Params: * sc = the scope into which we are imported * loc = the location of the import statement */ void checkImportDeprecation(const ref Loc loc, Scope* sc) { if (md && md.isdeprecated && !sc.isDeprecated) { Expression msg = md.msg; if (StringExp se = msg ? msg.toStringExp() : null) { const slice = se.peekString(); deprecation(loc, "is deprecated - %.*s", cast(int)slice.length, slice.ptr); } else deprecation(loc, "is deprecated"); } } override Dsymbol search(const ref Loc loc, Identifier ident, int flags = SearchLocalsOnly) { /* Since modules can be circularly referenced, * need to stop infinite recursive searches. * This is done with the cache. */ //printf("%s Module.search('%s', flags = x%x) insearch = %d\n", toChars(), ident.toChars(), flags, insearch); if (insearch) return null; /* Qualified module searches always search their imports, * even if SearchLocalsOnly */ if (!(flags & SearchUnqualifiedModule)) flags &= ~(SearchUnqualifiedModule | SearchLocalsOnly); if (searchCacheIdent == ident && searchCacheFlags == flags) { //printf("%s Module::search('%s', flags = %d) insearch = %d searchCacheSymbol = %s\n", // toChars(), ident.toChars(), flags, insearch, searchCacheSymbol ? searchCacheSymbol.toChars() : "null"); return searchCacheSymbol; } uint errors = global.errors; insearch = 1; Dsymbol s = ScopeDsymbol.search(loc, ident, flags); insearch = 0; if (errors == global.errors) { // https://issues.dlang.org/show_bug.cgi?id=10752 // Can cache the result only when it does not cause // access error so the side-effect should be reproduced in later search. searchCacheIdent = ident; searchCacheSymbol = s; searchCacheFlags = flags; } return s; } override bool isPackageAccessible(Package p, Prot protection, int flags = 0) { if (insearch) // don't follow import cycles return false; insearch = true; scope (exit) insearch = false; if (flags & IgnorePrivateImports) protection = Prot(Prot.Kind.public_); // only consider public imports return super.isPackageAccessible(p, protection); } override Dsymbol symtabInsert(Dsymbol s) { searchCacheIdent = null; // symbol is inserted, so invalidate cache return Package.symtabInsert(s); } void deleteObjFile() { if (global.params.obj) File.remove(objfile.toChars()); if (docfile) File.remove(docfile.toChars()); } /******************************************* * Can't run semantic on s now, try again later. */ extern (D) static void addDeferredSemantic(Dsymbol s) { //printf("Module::addDeferredSemantic('%s')\n", s.toChars()); deferred.push(s); } extern (D) static void addDeferredSemantic2(Dsymbol s) { //printf("Module::addDeferredSemantic2('%s')\n", s.toChars()); deferred2.push(s); } extern (D) static void addDeferredSemantic3(Dsymbol s) { //printf("Module::addDeferredSemantic3('%s')\n", s.toChars()); deferred3.push(s); } /****************************************** * Run semantic() on deferred symbols. */ static void runDeferredSemantic() { if (dprogress == 0) return; __gshared int nested; if (nested) return; //if (deferred.dim) printf("+Module::runDeferredSemantic(), len = %d\n", deferred.dim); nested++; size_t len; do { dprogress = 0; len = deferred.dim; if (!len) break; Dsymbol* todo; Dsymbol* todoalloc = null; Dsymbol tmp; if (len == 1) { todo = &tmp; } else { todo = cast(Dsymbol*)Mem.check(malloc(len * Dsymbol.sizeof)); todoalloc = todo; } memcpy(todo, deferred.tdata(), len * Dsymbol.sizeof); deferred.setDim(0); for (size_t i = 0; i < len; i++) { Dsymbol s = todo[i]; s.dsymbolSemantic(null); //printf("deferred: %s, parent = %s\n", s.toChars(), s.parent.toChars()); } //printf("\tdeferred.dim = %d, len = %d, dprogress = %d\n", deferred.dim, len, dprogress); if (todoalloc) free(todoalloc); } while (deferred.dim < len || dprogress); // while making progress nested--; //printf("-Module::runDeferredSemantic(), len = %d\n", deferred.dim); } static void runDeferredSemantic2() { Module.runDeferredSemantic(); Dsymbols* a = &Module.deferred2; for (size_t i = 0; i < a.dim; i++) { Dsymbol s = (*a)[i]; //printf("[%d] %s semantic2a\n", i, s.toPrettyChars()); s.semantic2(null); if (global.errors) break; } a.setDim(0); } static void runDeferredSemantic3() { Module.runDeferredSemantic2(); Dsymbols* a = &Module.deferred3; for (size_t i = 0; i < a.dim; i++) { Dsymbol s = (*a)[i]; //printf("[%d] %s semantic3a\n", i, s.toPrettyChars()); s.semantic3(null); if (global.errors) break; } a.setDim(0); } extern (D) static void clearCache() { for (size_t i = 0; i < amodules.dim; i++) { Module m = amodules[i]; m.searchCacheIdent = null; } } /************************************ * Recursively look at every module this module imports, * return true if it imports m. * Can be used to detect circular imports. */ int imports(Module m) { //printf("%s Module::imports(%s)\n", toChars(), m.toChars()); version (none) { for (size_t i = 0; i < aimports.dim; i++) { Module mi = cast(Module)aimports.data[i]; printf("\t[%d] %s\n", i, mi.toChars()); } } for (size_t i = 0; i < aimports.dim; i++) { Module mi = aimports[i]; if (mi == m) return true; if (!mi.insearch) { mi.insearch = 1; int r = mi.imports(m); if (r) return r; } } return false; } bool isRoot() { return this.importedFrom == this; } // true if the module source file is directly // listed in command line. bool isCoreModule(Identifier ident) { return this.ident == ident && parent && parent.ident == Id.core && !parent.parent; } // Back end int doppelganger; // sub-module Symbol* cov; // private uint[] __coverage; uint* covb; // bit array of valid code line numbers Symbol* sictor; // module order independent constructor Symbol* sctor; // module constructor Symbol* sdtor; // module destructor Symbol* ssharedctor; // module shared constructor Symbol* sshareddtor; // module shared destructor Symbol* stest; // module unit test Symbol* sfilename; // symbol for filename override inout(Module) isModule() inout { return this; } override void accept(Visitor v) { v.visit(this); } /*********************************************** * Writes this module's fully-qualified name to buf * Params: * buf = The buffer to write to */ void fullyQualifiedName(ref OutBuffer buf) { buf.writestring(ident.toString()); for (auto package_ = parent; package_ !is null; package_ = package_.parent) { buf.prependstring("."); buf.prependstring(package_.ident.toChars()); } } } /*********************************************************** */ extern (C++) struct ModuleDeclaration { Loc loc; Identifier id; Identifiers* packages; // array of Identifier's representing packages bool isdeprecated; // if it is a deprecated module Expression msg; extern (D) this(const ref Loc loc, Identifiers* packages, Identifier id, Expression msg, bool isdeprecated) { this.loc = loc; this.packages = packages; this.id = id; this.msg = msg; this.isdeprecated = isdeprecated; } extern (C++) const(char)* toChars() const { OutBuffer buf; if (packages && packages.dim) { foreach (pid; *packages) { buf.writestring(pid.toString()); buf.writeByte('.'); } } buf.writestring(id.toString()); return buf.extractChars(); } /// Provide a human readable representation extern (D) const(char)[] toString() const { return this.toChars().toDString; } }
D
/* 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. */ module flow.identitylink.service.impl.persistence.entity.data.impl.MybatisIdentityLinkDataManager; import hunt.collection.HashMap; import hunt.collection.List; import hunt.collection.Map; import flow.common.api.scop.ScopeTypes; import flow.common.db.AbstractDataManager; //import flow.common.db.DbSqlSession; //import flow.common.persistence.cache.CachedEntityMatcher; import flow.identitylink.service.impl.persistence.entity.IdentityLinkEntity; import flow.identitylink.service.impl.persistence.entity.IdentityLinkEntityImpl; import flow.identitylink.service.impl.persistence.entity.data.IdentityLinkDataManager; //import flow.identitylink.service.impl.persistence.entity.data.impl.cachematcher.IdentityLinksByProcessInstanceMatcher; //import flow.identitylink.service.impl.persistence.entity.data.impl.cachematcher.IdentityLinksByProcessInstanceUserGroupAndTypeMatcher; //import flow.identitylink.service.impl.persistence.entity.data.impl.cachematcher.IdentityLinksByScopeIdAndTypeMatcher; //import flow.identitylink.service.impl.persistence.entity.data.impl.cachematcher.IdentityLinksByScopeIdScopeTypeUserGroupAndTypeMatcher; //import flow.identitylink.service.impl.persistence.entity.data.impl.cachematcher.IdentityLinksBySubScopeIdAndTypeMatcher; //import flow.identitylink.service.impl.persistence.entity.data.impl.cachematcher.IdentityLinksByTaskIdMatcher; import hunt.collection.ArrayList; import hunt.entity; import hunt.Exceptions; import flow.common.AbstractEngineConfiguration; import hunt.logging; import flow.common.persistence.entity.Entity; import flow.common.interceptor.CommandContext; import flow.common.api.DataManger; import flow.common.context.Context; import flow.engine.impl.util.CommandContextUtil; /** * @author Joram Barrez */ class MybatisIdentityLinkDataManager : EntityRepository!( IdentityLinkEntityImpl , string) , IdentityLinkDataManager ,DataManger{ // //protected CachedEntityMatcher!IdentityLinkEntity identityLinksByTaskIdMatcher = new IdentityLinksByTaskIdMatcher(); //protected CachedEntityMatcher!IdentityLinkEntity identityLinkByProcessInstanceMatcher = new IdentityLinksByProcessInstanceMatcher(); //protected CachedEntityMatcher!IdentityLinkEntity identityLinksByScopeIdAndTypeMatcher = new IdentityLinksByScopeIdAndTypeMatcher(); //protected CachedEntityMatcher!IdentityLinkEntity identityLinksBySubScopeIdAndTypeMatcher = new IdentityLinksBySubScopeIdAndTypeMatcher(); //protected CachedEntityMatcher!IdentityLinkEntity identityLinksByProcessInstanceUserGroupAndTypeMatcher = new IdentityLinksByProcessInstanceUserGroupAndTypeMatcher(); //protected CachedEntityMatcher!IdentityLinkEntity identityLinksByScopeIdScopeTypeUserGroupAndTypeMatcher = new IdentityLinksByScopeIdScopeTypeUserGroupAndTypeMatcher(); // //class<? extends IdentityLinkEntity> getManagedEntityClass() { // return IdentityLinkEntityImpl.class; //} TypeInfo getTypeInfo() { return typeid(MybatisIdentityLinkDataManager); } alias findById = CrudRepository!( IdentityLinkEntityImpl , string).findById; alias insert = CrudRepository!( IdentityLinkEntityImpl , string).insert; alias update = CrudRepository!( IdentityLinkEntityImpl , string).update; public IdentityLinkEntity findById(string entityId) { if (entityId is null) { return null; } //return find(entityId); auto entity = CommandContextUtil.getEntityCache().findInCache(typeid(IdentityLinkEntityImpl),entityId); if (entity !is null) { return cast(IdentityLinkEntity)entity; } IdentityLinkEntity dbData = cast(IdentityLinkEntity)(find(entityId)); if (dbData !is null) { CommandContextUtil.getEntityCache().put(dbData, true , typeid(IdentityLinkEntityImpl), this); } return dbData; //if (entityId is null) { // return null; //} // //return find(entityId); // Cache //EntityImpl cachedEntity = getEntityCache().findInCache(getManagedEntityClass(), entityId); //if (cachedEntity !is null) { // return cachedEntity; //} // Database //return getDbSqlSession().selectById(getManagedEntityClass(), entityId, false); } // //@Override public void insert(IdentityLinkEntity entity) { //insert(cast(IdentityLinkEntityImpl)entity); //getDbSqlSession().insert(entity); if (entity.getId() is null) { string id = Context.getCommandContext().getCurrentEngineConfiguration().getIdGenerator().getNextId(); //if (dbSqlSessionFactory.isUsePrefixId()) { // id = entity.getIdPrefix() + id; //} entity.setId(id); } entity.setInserted(true); insertJob[entity] = this; CommandContextUtil.getEntityCache().put(entity, false, typeid(IdentityLinkEntityImpl), this); } public void insertTrans(Entity entity , EntityManager db) { //auto em = _manager ? _manager : createEntityManager; IdentityLinkEntityImpl tmp = cast(IdentityLinkEntityImpl)entity; db.persist!IdentityLinkEntityImpl(tmp); } // //@Override public IdentityLinkEntity update(IdentityLinkEntity entity) { return update(cast(IdentityLinkEntityImpl)entity); //getDbSqlSession().update(entity); //return entity; } // //@Override public void dele(string id) { IdentityLinkEntity entity = findById(id); if (entity !is null) { // remove(cast(IdentityLinkEntityImpl)entity); deleteJob[entity] = this; entity.setDeleted(true); } //delete(entity); } public void dele(IdentityLinkEntity entity) { deleteJob[entity] = this; entity.setDeleted(true); //CommandContextUtil.getEntityCache().put(entity, false, typeid(IdentityLinkEntityImpl)); //if (entity !is null) //{ // remove(cast(IdentityLinkEntityImpl)entity); //} //getDbSqlSession().delete(entity); } void deleteTrans(Entity entity , EntityManager db) { db.remove!IdentityLinkEntityImpl(cast(IdentityLinkEntityImpl)entity); } public void updateTrans(Entity entity , EntityManager db) { db.merge!IdentityLinkEntityImpl(cast(IdentityLinkEntityImpl)entity); } this() { super(entityManagerFactory.currentEntityManager()); } public IdentityLinkEntity create() { return new IdentityLinkEntityImpl(); } public List!IdentityLinkEntity findIdentityLinksByTaskId(string taskId) { //DbSqlSession dbSqlSession = getDbSqlSession(); // //if (isEntityInserted(dbSqlSession, "task", taskId)) { // return getListFromCache(identityLinksByTaskIdMatcher, taskId); //} //return getList("selectIdentityLinksByTaskId", taskId, identityLinkByProcessInstanceMatcher, true); List!IdentityLinkEntity lst = new ArrayList!IdentityLinkEntity; IdentityLinkEntityImpl[] objs = findAll(new Condition("%s = %s" , field.taskId , taskId)); foreach (IdentityLinkEntityImpl id ; objs) { lst.add(cast(IdentityLinkEntity)id); } return lst; } public List!IdentityLinkEntity findIdentityLinksByProcessInstanceId(string processInstanceId) { //DbSqlSession dbSqlSession = getDbSqlSession(); // //// If the process instance has been inserted in the same command execution as this query, there can't be any in the database //if (isEntityInserted(dbSqlSession, "execution", processInstanceId)) { // return getListFromCache(identityLinkByProcessInstanceMatcher, processInstanceId); //} //return getList("selectIdentityLinksByProcessInstance", processInstanceId, identityLinkByProcessInstanceMatcher, true); List!IdentityLinkEntity lst = new ArrayList!IdentityLinkEntity; IdentityLinkEntityImpl[] objs = findAll(new Condition("%s = %s" , field.processInstanceId , processInstanceId)); lst.addAll(lst); return lst; } public List!IdentityLinkEntity findIdentityLinksByScopeIdAndType(string scopeId, string scopeType) { List!IdentityLinkEntity lst = new ArrayList!IdentityLinkEntity; IdentityLinkEntityImpl[] objs = findAll(new Condition("%s = %s and %s = %s" , field.scopeId , scopeId , field.scopeType , scopeType)); lst.addAll(lst); return lst; //Map<string, string> parameters = new HashMap<>(); //parameters.put("scopeId", scopeId); //parameters.put("scopeType", scopeType); //return getList("selectIdentityLinksByScopeIdAndType", parameters, identityLinksByScopeIdAndTypeMatcher, true); } public List!IdentityLinkEntity findIdentityLinksBySubScopeIdAndType(string subScopeId, string scopeType) { List!IdentityLinkEntity lst = new ArrayList!IdentityLinkEntity; IdentityLinkEntityImpl[] objs = findAll(new Condition("%s = %s and %s = %s" , field.subScopeId , subScopeId , field.scopeType , scopeType)); lst.addAll(lst); return lst; //Map<string, string> parameters = new HashMap<>(); //parameters.put("subScopeId", subScopeId); //parameters.put("scopeType", scopeType); //return getList("selectIdentityLinksBySubScopeIdAndType", parameters, identityLinksBySubScopeIdAndTypeMatcher, true); } public List!IdentityLinkEntity findIdentityLinksByScopeDefinitionIdAndType(string scopeDefinitionId, string scopeType) { List!IdentityLinkEntity lst = new ArrayList!IdentityLinkEntity; IdentityLinkEntityImpl[] objs = findAll(new Condition("%s = %s and %s = %s" , field.scopeDefinitionId , scopeDefinitionId , field.scopeType , scopeType)); lst.addAll(lst); return lst; //Map<string, string> parameters = new HashMap<>(); //parameters.put("scopeDefinitionId", scopeDefinitionId); //parameters.put("scopeType", scopeType); //return getDbSqlSession().selectList("selectIdentityLinksByScopeDefinitionAndType", parameters); } public List!IdentityLinkEntity findIdentityLinksByProcessDefinitionId(string processDefinitionId) { //return getDbSqlSession().selectList("selectIdentityLinksByProcessDefinition", processDefinitionId); List!IdentityLinkEntity lst = new ArrayList!IdentityLinkEntity; IdentityLinkEntityImpl[] objs = findAll(new Condition("%s = %s" , field.processDefId , processDefinitionId)); lst.addAll(lst); return lst; } public List!IdentityLinkEntity findIdentityLinkByTaskUserGroupAndType(string taskId, string userId, string groupId, string type) { implementationMissing(false); return null; //List!IdentityLinkEntity lst = new ArrayList!IdentityLinkEntity; //IdentityLinkEntityImpl[] objs = findAll(new Condition("%s = %s and %s = %s and %s = %s and %s = %s and %s = %s" , field.taskId , taskId , field.userId , userId,field.groupId , groupId,field.type , type)); //lst.addAll(lst); //return objs; //Map<string, string> parameters = new HashMap<>(); //parameters.put("taskId", taskId); //parameters.put("userId", userId); //parameters.put("groupId", groupId); //parameters.put("type", type); //return getDbSqlSession().selectList("selectIdentityLinkByTaskUserGroupAndType", parameters); } public List!IdentityLinkEntity findIdentityLinkByProcessInstanceUserGroupAndType(string processInstanceId, string userId, string groupId, string type) { implementationMissing(false); return null; //List!IdentityLinkEntity lst = new ArrayList!IdentityLinkEntity; //IdentityLinkEntityImpl[] objs = findAll(new Condition("%s = %s and %s = %s and %s = %s and %s = %s and %s = %s" , field.processInstanceId , processInstanceId , field.userId , userId,field.groupId , groupId,field.type , type)); //lst.addAll(lst); //return objs; //Map<string, string> parameters = new HashMap<>(); //parameters.put("processInstanceId", processInstanceId); //parameters.put("userId", userId); //parameters.put("groupId", groupId); //parameters.put("type", type); //return getList("selectIdentityLinkByProcessInstanceUserGroupAndType", parameters, identityLinksByProcessInstanceUserGroupAndTypeMatcher); } public List!IdentityLinkEntity findIdentityLinkByProcessDefinitionUserAndGroup(string processDefinitionId, string userId, string groupId) { implementationMissing(false); return null; //List!IdentityLinkEntity lst = new ArrayList!IdentityLinkEntity; //IdentityLinkEntityImpl[] objs = findAll(new Condition("%s = %s and %s = %s and %s = %s and %s = %s" , field.processDefId , processDefinitionId , field.userId , userId,field.groupId , groupId)); //lst.addAll(lst); //return objs; //Map<string, string> parameters = new HashMap<>(); //parameters.put("processDefinitionId", processDefinitionId); //parameters.put("userId", userId); //parameters.put("groupId", groupId); //return getDbSqlSession().selectList("selectIdentityLinkByProcessDefinitionUserAndGroup", parameters); } public List!IdentityLinkEntity findIdentityLinkByScopeIdScopeTypeUserGroupAndType(string scopeId, string scopeType, string userId, string groupId, string type) { implementationMissing(false); return null; //List!IdentityLinkEntity lst = new ArrayList!IdentityLinkEntity; //IdentityLinkEntityImpl[] objs = findAll(new Condition("%s = %s and %s = %s and %s = %s and %s = %s" , field.processDefId , processDefinitionId , field.userId , userId,field.groupId , groupId)); //lst.addAll(lst); //return objs; //Map<string, string> parameters = new HashMap<>(); //parameters.put("scopeId", scopeId); //parameters.put("scopeType", scopeType); //parameters.put("userId", userId); //parameters.put("groupId", groupId); //parameters.put("type", type); //return getList("selectIdentityLinkByScopeIdScopeTypeUserGroupAndType", parameters, identityLinksByScopeIdScopeTypeUserGroupAndTypeMatcher); } public List!IdentityLinkEntity findIdentityLinkByScopeDefinitionScopeTypeUserAndGroup(string scopeDefinitionId, string scopeType, string userId, string groupId) { implementationMissing( false); return null; //Map<string, string> parameters = new HashMap<>(); //parameters.put("scopeDefinitionId", scopeDefinitionId); //parameters.put("scopeType", scopeType); //parameters.put("userId", userId); //parameters.put("groupId", groupId); //return getDbSqlSession().selectList("selectIdentityLinkByScopeDefinitionScopeTypeUserAndGroup", parameters); } public void deleteIdentityLinksByTaskId(string taskId) { List!IdentityLinkEntity identitys = findIdentityLinksByTaskId(taskId); foreach (IdentityLinkEntity identity ; identitys) { dele(identity); } //scope(exit) //{ // _manager.close(); //} // //auto update = _manager.createQuery!(IdentityLinkEntityImpl)("DELETE FROM IdentityLinkEntityImpl u WHERE u.taskId = :taskId"); //update.setParameter("taskId",taskId); //try{ // update.exec(); //} //catch(Exception e) //{ // logError("deleteIdentityLinksByTaskId error : %s",e.msg); //} //DbSqlSession dbSqlSession = getDbSqlSession(); //if (isEntityInserted(dbSqlSession, "task", taskId)) { // deleteCachedEntities(dbSqlSession, identityLinksByTaskIdMatcher, taskId); //} else { // bulkDelete("deleteIdentityLinksByTaskId", identityLinksByTaskIdMatcher, taskId); //} } public void deleteIdentityLinksByProcDef(string processDefId) { scope(exit) { _manager.close(); } auto update = _manager.createQuery!(IdentityLinkEntityImpl)("DELETE FROM IdentityLinkEntityImpl u WHERE u.processDefId = :processDefId"); update.setParameter("processDefId",processDefId); try{ update.exec(); } catch(Exception e) { logError("deleteIdentityLinksByProcDef error : %s",e.msg); } //getDbSqlSession().delete("deleteIdentityLinksByProcDef", processDefId, IdentityLinkEntityImpl.class); } public void deleteIdentityLinksByProcessInstanceId(string processInstanceId) { scope(exit) { _manager.close(); } auto update = _manager.createQuery!(IdentityLinkEntityImpl)("DELETE FROM IdentityLinkEntityImpl u WHERE u.processInstanceId = :processInstanceId"); update.setParameter("processInstanceId",processInstanceId); try{ update.exec(); } catch(Exception e) { logError("deleteIdentityLinksByProcessInstanceId error : %s",e.msg); } //DbSqlSession dbSqlSession = getDbSqlSession(); //if (isEntityInserted(dbSqlSession, "execution", processInstanceId)) { // deleteCachedEntities(dbSqlSession, identityLinkByProcessInstanceMatcher, processInstanceId); //} else { // bulkDelete("deleteIdentityLinksByProcessInstanceId", identityLinkByProcessInstanceMatcher, processInstanceId); //} } public void deleteIdentityLinksByScopeIdAndScopeType(string scopeId, string scopeType) { scope(exit) { _manager.close(); } auto update = _manager.createQuery!(IdentityLinkEntityImpl)("DELETE FROM IdentityLinkEntityImpl u WHERE u.scopeId = :scopeId and u.scopeType = :scopeType"); update.setParameter("scopeId",scopeId); update.setParameter("scopeType",scopeType); try{ update.exec(); } catch(Exception e) { logError("deleteIdentityLinksByScopeIdAndScopeType error : %s",e.msg); } //DbSqlSession dbSqlSession = getDbSqlSession(); // //Map<string, string> parameters = new HashMap<>(); //parameters.put("scopeId", scopeId); // //if (ScopeTypes.CMMN.equals(scopeType) && isEntityInserted(dbSqlSession, "caseInstance", scopeId)) { // deleteCachedEntities(dbSqlSession, identityLinksByScopeIdAndTypeMatcher, parameters); //} else { // // parameters.put("scopeType", scopeType); // bulkDelete("deleteIdentityLinksByScopeIdAndScopeType", identityLinksByScopeIdAndTypeMatcher, parameters); //} } public void deleteIdentityLinksByScopeDefinitionIdAndScopeType(string scopeDefinitionId, string scopeType) { scope(exit) { _manager.close(); } auto update = _manager.createQuery!(IdentityLinkEntityImpl)("DELETE FROM IdentityLinkEntityImpl u WHERE u.scopeDefinitionId = :scopeDefinitionId and u.scopeType = :scopeType"); update.setParameter("scopeDefinitionId",scopeDefinitionId); update.setParameter("scopeType",scopeType); try{ update.exec(); } catch(Exception e) { logError("deleteIdentityLinksByScopeDefinitionIdAndScopeType error : %s",e.msg); } //Map<string, string> parameters = new HashMap<>(); //parameters.put("scopeDefinitionId", scopeDefinitionId); //parameters.put("scopeType", scopeType); //getDbSqlSession().delete("deleteIdentityLinksByScopeDefinitionIdAndScopeType", parameters, IdentityLinkEntityImpl.class); } }
D
/* 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. */ module flow.idm.engine.impl.cmd.GetPrivilegeMappingsByPrivilegeIdCmd; import hunt.collection.List; import flow.common.api.FlowableIllegalArgumentException; import flow.common.interceptor.Command; import flow.common.interceptor.CommandContext; import flow.idm.api.PrivilegeMapping; import flow.idm.engine.impl.util.CommandContextUtil; import hunt.Exceptions; /** * @author Tijs Rademakers */ class GetPrivilegeMappingsByPrivilegeIdCmd : Command!(List!PrivilegeMapping) { protected string privilegeId; this(string privilegeId) { if (privilegeId is null) { throw new FlowableIllegalArgumentException("privilegeId is null"); } this.privilegeId = privilegeId; } public List!PrivilegeMapping execute(CommandContext commandContext) { implementationMissing(false); return null; // return CommandContextUtil.getPrivilegeMappingEntityManager(commandContext).getPrivilegeMappingsByPrivilegeId(privilegeId); } }
D
module UnrealScript.TribesGame.TrDevice_BoltLauncher; import ScriptClasses; import UnrealScript.Helpers; import UnrealScript.TribesGame.TrDevice; extern(C++) interface TrDevice_BoltLauncher : TrDevice { public extern(D): private static __gshared ScriptClass mStaticClass; @property final static ScriptClass StaticClass() { mixin(MGSCC("Class TribesGame.TrDevice_BoltLauncher")); } private static __gshared TrDevice_BoltLauncher mDefaultProperties; @property final static TrDevice_BoltLauncher DefaultProperties() { mixin(MGDPC("TrDevice_BoltLauncher", "TrDevice_BoltLauncher TribesGame.Default__TrDevice_BoltLauncher")); } }
D
a person who fells trees a short warm outer jacket
D
/Users/sridattbhamidipati/Desktop/money20202015/build/money20202015.build/Debug-iphonesimulator/money20202015.build/Objects-normal/x86_64/AppDelegate.o : /Users/sridattbhamidipati/Desktop/money20202015/money20202015/JSONObject.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/DisplayQRViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/NewItemViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/Place.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/ConsumerDataViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/Item.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/PlaceTableViewCell.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/ConsumerHomeViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/LoginViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/ItemTableViewCell.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/AppDelegate.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/SearchPlacesViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/Extension.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/CameraViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/CheckoutViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/BusinessHomeViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/ChooseUsageViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/Tool.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/sridattbhamidipati/Desktop/money20202015/money20202015/Bridging_Header.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKGraphRequestDataAttachment.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKGraphErrorRecoveryProcessor.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKAppLinkResolver.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKButton.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKUtility.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKTestUsersManager.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKSettings.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKProfilePictureView.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKProfile.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKMutableCopying.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKGraphRequest.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKConstants.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKApplicationDelegate.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKAppLinkUtility.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKAppEvents.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKMacros.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKGraphRequestConnection.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKCopying.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKAccessToken.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKCoreKit.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Modules/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/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginTooltipView.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginManagerLoginResult.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginConstants.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKTooltipView.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginManager.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginButton.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginKit.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreLocation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreData.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/AVFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreMedia.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreAudio.swiftmodule /Users/sridattbhamidipati/Desktop/money20202015/build/money20202015.build/Debug-iphonesimulator/money20202015.build/Objects-normal/x86_64/AppDelegate~partial.swiftmodule : /Users/sridattbhamidipati/Desktop/money20202015/money20202015/JSONObject.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/DisplayQRViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/NewItemViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/Place.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/ConsumerDataViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/Item.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/PlaceTableViewCell.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/ConsumerHomeViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/LoginViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/ItemTableViewCell.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/AppDelegate.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/SearchPlacesViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/Extension.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/CameraViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/CheckoutViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/BusinessHomeViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/ChooseUsageViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/Tool.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/sridattbhamidipati/Desktop/money20202015/money20202015/Bridging_Header.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKGraphRequestDataAttachment.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKGraphErrorRecoveryProcessor.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKAppLinkResolver.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKButton.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKUtility.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKTestUsersManager.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKSettings.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKProfilePictureView.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKProfile.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKMutableCopying.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKGraphRequest.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKConstants.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKApplicationDelegate.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKAppLinkUtility.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKAppEvents.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKMacros.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKGraphRequestConnection.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKCopying.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKAccessToken.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKCoreKit.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Modules/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/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginTooltipView.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginManagerLoginResult.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginConstants.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKTooltipView.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginManager.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginButton.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginKit.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreLocation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreData.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/AVFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreMedia.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreAudio.swiftmodule /Users/sridattbhamidipati/Desktop/money20202015/build/money20202015.build/Debug-iphonesimulator/money20202015.build/Objects-normal/x86_64/AppDelegate~partial.swiftdoc : /Users/sridattbhamidipati/Desktop/money20202015/money20202015/JSONObject.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/DisplayQRViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/NewItemViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/Place.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/ConsumerDataViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/Item.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/PlaceTableViewCell.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/ConsumerHomeViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/LoginViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/ItemTableViewCell.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/AppDelegate.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/SearchPlacesViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/Extension.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/CameraViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/CheckoutViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/BusinessHomeViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/ChooseUsageViewController.swift /Users/sridattbhamidipati/Desktop/money20202015/money20202015/Tool.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/sridattbhamidipati/Desktop/money20202015/money20202015/Bridging_Header.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKGraphRequestDataAttachment.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKGraphErrorRecoveryProcessor.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKAppLinkResolver.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKButton.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKUtility.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKTestUsersManager.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKSettings.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKProfilePictureView.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKProfile.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKMutableCopying.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKGraphRequest.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKConstants.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKApplicationDelegate.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKAppLinkUtility.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKAppEvents.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKMacros.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKGraphRequestConnection.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKCopying.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKAccessToken.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Headers/FBSDKCoreKit.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKCoreKit.framework/Modules/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/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginTooltipView.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginManagerLoginResult.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginConstants.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKTooltipView.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginManager.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginButton.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Headers/FBSDKLoginKit.h /Users/sridattbhamidipati/Desktop/money20202015/money20202015/FBSDKLoginKit.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreLocation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreData.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/AVFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreMedia.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreAudio.swiftmodule
D
/* * Copyright (c) 2007-2013 Scott Lembcke and Howling Moon Software * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ module dchip.cpCollision; import core.stdc.stdlib : alloca; import std.string; import dchip.cpArbiter; import dchip.cpBB; import dchip.cpBody; import dchip.chipmunk; import dchip.chipmunk_private; import dchip.chipmunk_types; import dchip.cpPolyShape; import dchip.cpShape; import dchip.cpSpace; import dchip.cpVect; import dchip.util; /+ #if DEBUG && 0 #include "ChipmunkDemo.h" #define DRAW_ALL 0 #define DRAW_GJK (0 || DRAW_ALL) #define DRAW_EPA (0 || DRAW_ALL) #define DRAW_CLOSEST (0 || DRAW_ALL) #define DRAW_CLIP (0 || DRAW_ALL) #define PRINT_LOG 0 #endif +/ enum ENABLE_CACHING = 1; enum MAX_GJK_ITERATIONS = 30; enum MAX_EPA_ITERATIONS = 30; enum WARN_GJK_ITERATIONS = 20; enum WARN_EPA_ITERATIONS = 20; // Add contact points for circle to circle collisions. // Used by several collision tests. // TODO should accept hash parameter int CircleToCircleQuery(const cpVect p1, const cpVect p2, const cpFloat r1, const cpFloat r2, cpHashValue hash, cpContact* con) { cpFloat mindist = r1 + r2; cpVect delta = cpvsub(p2, p1); cpFloat distsq = cpvlengthsq(delta); if (distsq < mindist * mindist) { cpFloat dist = cpfsqrt(distsq); cpVect n = (dist ? cpvmult(delta, 1.0f / dist) : cpv(1.0f, 0.0f)); cpContactInit(con, cpvlerp(p1, p2, r1 / (r1 + r2)), n, dist - mindist, hash); return 1; } else { return 0; } } //MARK: Support Points and Edges: int PolySupportPointIndex(const int count, const cpVect* verts, const cpVect n) { cpFloat max = -INFINITY; int index = 0; for (int i = 0; i < count; i++) { cpVect v = verts[i]; cpFloat d = cpvdot(v, n); if (d > max) { max = d; index = i; } } return index; } struct SupportPoint { cpVect p; cpCollisionID id; } SupportPoint SupportPointNew(cpVect p, cpCollisionID id) { SupportPoint point = { p, id }; return point; } alias SupportPointFunc = SupportPoint function(const cpShape* shape, const cpVect n); SupportPoint CircleSupportPoint(const cpCircleShape* circle, const cpVect n) { return SupportPointNew(circle.tc, 0); } SupportPoint SegmentSupportPoint(const cpSegmentShape* seg, const cpVect n) { if (cpvdot(seg.ta, n) > cpvdot(seg.tb, n)) { return SupportPointNew(seg.ta, 0); } else { return SupportPointNew(seg.tb, 1); } } SupportPoint PolySupportPoint(const cpPolyShape* poly, const cpVect n) { const cpVect* verts = poly.tVerts; int i = PolySupportPointIndex(poly.numVerts, verts, n); return SupportPointNew(verts[i], i); } struct MinkowskiPoint { cpVect a, b; cpVect ab; cpCollisionID id; } MinkowskiPoint MinkowskiPointNew(const SupportPoint a, const SupportPoint b) { MinkowskiPoint point = { a.p, b.p, cpvsub(b.p, a.p), (a.id & 0xFF) << 8 | (b.id & 0xFF) }; return point; } struct SupportContext { const cpShape* shape1; const cpShape* shape2; SupportPointFunc func1, func2; } MinkowskiPoint Support(const SupportContext* ctx, const cpVect n) { SupportPoint a = ctx.func1(ctx.shape1, cpvneg(n)); SupportPoint b = ctx.func2(ctx.shape2, n); return MinkowskiPointNew(a, b); } struct EdgePoint { cpVect p; cpHashValue hash; } struct Edge { EdgePoint a, b; cpFloat r = 0; cpVect n; } Edge EdgeNew(cpVect va, cpVect vb, cpHashValue ha, cpHashValue hb, cpFloat r) { Edge edge = { { va, ha }, { vb, hb }, r, cpvnormalize(cpvperp(cpvsub(vb, va))) }; return edge; } Edge SupportEdgeForPoly(const cpPolyShape* poly, const cpVect n) { int numVerts = poly.numVerts; int i1 = PolySupportPointIndex(poly.numVerts, poly.tVerts, n); // TODO get rid of mod eventually, very expensive on ARM int i0 = (i1 - 1 + numVerts) % numVerts; int i2 = (i1 + 1) % numVerts; cpVect* verts = cast(cpVect*)poly.tVerts; if (cpvdot(n, poly.tPlanes[i1].n) > cpvdot(n, poly.tPlanes[i2].n)) { Edge edge = { { verts[i0], CP_HASH_PAIR(poly, i0) }, { verts[i1], CP_HASH_PAIR(poly, i1) }, poly.r, poly.tPlanes[i1].n }; return edge; } else { Edge edge = { { verts[i1], CP_HASH_PAIR(poly, i1) }, { verts[i2], CP_HASH_PAIR(poly, i2) }, poly.r, poly.tPlanes[i2].n }; return edge; } } Edge SupportEdgeForSegment(const cpSegmentShape* seg, const cpVect n) { if (cpvdot(seg.tn, n) > 0.0) { Edge edge = { { seg.ta, CP_HASH_PAIR(seg, 0) }, { seg.tb, CP_HASH_PAIR(seg, 1) }, seg.r, seg.tn }; return edge; } else { Edge edge = { { seg.tb, CP_HASH_PAIR(seg, 1) }, { seg.ta, CP_HASH_PAIR(seg, 0) }, seg.r, cpvneg(seg.tn) }; return edge; } } cpFloat ClosestT(const cpVect a, const cpVect b) { cpVect delta = cpvsub(b, a); return -cpfclamp(cpvdot(delta, cpvadd(a, b)) / cpvlengthsq(delta), -1.0f, 1.0f); } cpVect LerpT(const cpVect a, const cpVect b, const cpFloat t) { cpFloat ht = 0.5f * t; return cpvadd(cpvmult(a, 0.5f - ht), cpvmult(b, 0.5f + ht)); } struct ClosestPoints { cpVect a, b; cpVect n; cpFloat d = 0; cpCollisionID id; } ClosestPoints ClosestPointsNew(const MinkowskiPoint v0, const MinkowskiPoint v1) { cpFloat t = ClosestT(v0.ab, v1.ab); cpVect p = LerpT(v0.ab, v1.ab, t); cpVect pa = LerpT(v0.a, v1.a, t); cpVect pb = LerpT(v0.b, v1.b, t); cpCollisionID id = (v0.id & 0xFFFF) << 16 | (v1.id & 0xFFFF); cpVect delta = cpvsub(v1.ab, v0.ab); cpVect n = cpvnormalize(cpvperp(delta)); cpFloat d = -cpvdot(n, p); if (d <= 0.0f || (0.0f < t && t < 1.0f)) { ClosestPoints points = { pa, pb, cpvneg(n), d, id }; return points; } else { cpFloat d2 = cpvlength(p); cpVect n_ = cpvmult(p, 1.0f / (d2 + CPFLOAT_MIN)); ClosestPoints points = { pa, pb, n_, d2, id }; return points; } } //MARK: EPA Functions cpFloat ClosestDist(const cpVect v0, const cpVect v1) { return cpvlengthsq(LerpT(v0, v1, ClosestT(v0, v1))); } ClosestPoints EPARecurse(const SupportContext* ctx, const int count, const MinkowskiPoint* hull, const int iteration) { int mini = 0; cpFloat minDist = INFINITY; // TODO: precalculate this when building the hull and save a step. for (int j = 0, i = count - 1; j < count; i = j, j++) { cpFloat d = ClosestDist(hull[i].ab, hull[j].ab); if (d < minDist) { minDist = d; mini = i; } } MinkowskiPoint v0 = hull[mini]; MinkowskiPoint v1 = hull[(mini + 1) % count]; cpAssertSoft(!cpveql(v0.ab, v1.ab), "!cpveql(v0.ab, v1.ab)", "Internal Error: EPA vertexes are the same (%d and %d)", mini, (mini + 1) % count); MinkowskiPoint p = Support(ctx, cpvperp(cpvsub(v1.ab, v0.ab))); /+ #if DRAW_EPA cpVect verts[count]; for (int i = 0; i < count; i++) verts[i] = hull[i].ab; ChipmunkDebugDrawPolygon(count, verts, RGBAColor(1, 1, 0, 1), RGBAColor(1, 1, 0, 0.25)); ChipmunkDebugDrawSegment(v0.ab, v1.ab, RGBAColor(1, 0, 0, 1)); ChipmunkDebugDrawPoints(5, 1, (cpVect[]){ p.ab }, RGBAColor(1, 1, 1, 1)); #endif +/ cpFloat area2x = cpvcross(cpvsub(v1.ab, v0.ab), cpvadd(cpvsub(p.ab, v0.ab), cpvsub(p.ab, v1.ab))); if (area2x > 0.0f && iteration < MAX_EPA_ITERATIONS) { int count2 = 1; MinkowskiPoint* hull2 = cast(MinkowskiPoint*)alloca((count + 1) * MinkowskiPoint.sizeof); hull2[0] = p; for (int i = 0; i < count; i++) { int index = (mini + 1 + i) % count; cpVect h0 = hull2[count2 - 1].ab; cpVect h1 = hull[index].ab; cpVect h2 = (i + 1 < count ? hull[(index + 1) % count] : p).ab; // TODO: Should this be changed to an area2x check? if (cpvcross(cpvsub(h2, h0), cpvsub(h1, h0)) > 0.0f) { hull2[count2] = hull[index]; count2++; } } return EPARecurse(ctx, count2, hull2, iteration + 1); } else { cpAssertWarn(iteration < WARN_EPA_ITERATIONS, "High EPA iterations: %d", iteration); return ClosestPointsNew(v0, v1); } } ClosestPoints EPA(const SupportContext* ctx, const MinkowskiPoint v0, const MinkowskiPoint v1, const MinkowskiPoint v2) { // TODO: allocate a NxM array here and do an in place convex hull reduction in EPARecurse MinkowskiPoint[3] hull; hull[0] = v0; hull[1] = v1; hull[2] = v2; return EPARecurse(ctx, 3, hull.ptr, 1); } //MARK: GJK Functions. ClosestPoints GJKRecurse(const SupportContext* ctx, const MinkowskiPoint v0, const MinkowskiPoint v1, const int iteration) { if (iteration > MAX_GJK_ITERATIONS) { cpAssertWarn(iteration < WARN_GJK_ITERATIONS, "High GJK iterations: %d", iteration); return ClosestPointsNew(v0, v1); } cpVect delta = cpvsub(v1.ab, v0.ab); if (cpvcross(delta, cpvadd(v0.ab, v1.ab)) > 0.0f) { // Origin is behind axis. Flip and try again. return GJKRecurse(ctx, v1, v0, iteration + 1); } else { cpFloat t = ClosestT(v0.ab, v1.ab); cpVect n = (-1.0f < t && t < 1.0f ? cpvperp(delta) : cpvneg(LerpT(v0.ab, v1.ab, t))); MinkowskiPoint p = Support(ctx, n); /+ #if DRAW_GJK ChipmunkDebugDrawSegment(v0.ab, v1.ab, RGBAColor(1, 1, 1, 1)); cpVect c = cpvlerp(v0.ab, v1.ab, 0.5); ChipmunkDebugDrawSegment(c, cpvadd(c, cpvmult(cpvnormalize(n), 5.0)), RGBAColor(1, 0, 0, 1)); ChipmunkDebugDrawPoints(5.0, 1, &p.ab, RGBAColor(1, 1, 1, 1)); #endif +/ if ( cpvcross(cpvsub(v1.ab, p.ab), cpvadd(v1.ab, p.ab)) > 0.0f && cpvcross(cpvsub(v0.ab, p.ab), cpvadd(v0.ab, p.ab)) < 0.0f ) { cpAssertWarn(iteration < WARN_GJK_ITERATIONS, "High GJK.EPA iterations: %d", iteration); // The triangle v0, p, v1 contains the origin. Use EPA to find the MSA. return EPA(ctx, v0, p, v1); } else { // The new point must be farther along the normal than the existing points. if (cpvdot(p.ab, n) <= cpfmax(cpvdot(v0.ab, n), cpvdot(v1.ab, n))) { cpAssertWarn(iteration < WARN_GJK_ITERATIONS, "High GJK iterations: %d", iteration); return ClosestPointsNew(v0, v1); } else { if (ClosestDist(v0.ab, p.ab) < ClosestDist(p.ab, v1.ab)) { return GJKRecurse(ctx, v0, p, iteration + 1); } else { return GJKRecurse(ctx, p, v1, iteration + 1); } } } } } SupportPoint ShapePoint(const cpShape* shape, const int i) { switch (shape.klass.type) { case CP_CIRCLE_SHAPE: { return SupportPointNew((cast(cpCircleShape*)shape).tc, 0); } case CP_SEGMENT_SHAPE: { cpSegmentShape* seg = cast(cpSegmentShape*)shape; return SupportPointNew(i == 0 ? seg.ta : seg.tb, i); } case CP_POLY_SHAPE: { cpPolyShape* poly = cast(cpPolyShape*)shape; // Poly shapes may change vertex count. int index = (i < poly.numVerts ? i : 0); return SupportPointNew(poly.tVerts[index], index); } default: { return SupportPointNew(cpvzero, 0); } } } ClosestPoints GJK(const SupportContext* ctx, cpCollisionID* id) { /+ #if DRAW_GJK || DRAW_EPA // draw the minkowski difference origin cpVect origin = cpvzero; ChipmunkDebugDrawPoints(5.0, 1, &origin, RGBAColor(1, 0, 0, 1)); int mdiffCount = ctx.count1 * ctx.count2; cpVect* mdiffVerts = alloca(mdiffCount * sizeof(cpVect)); for (int i = 0; i < ctx.count1; i++) { for (int j = 0; j < ctx.count2; j++) { cpVect v1 = ShapePoint(ctx.count1, ctx.verts1, i).p; cpVect v2 = ShapePoint(ctx.count2, ctx.verts2, j).p; mdiffVerts[i * ctx.count2 + j] = cpvsub(v2, v1); } } cpVect* hullVerts = alloca(mdiffCount * sizeof(cpVect)); int hullCount = cpConvexHull(mdiffCount, mdiffVerts, hullVerts, null, 0.0); ChipmunkDebugDrawPolygon(hullCount, hullVerts, RGBAColor(1, 0, 0, 1), RGBAColor(1, 0, 0, 0.25)); ChipmunkDebugDrawPoints(2.0, mdiffCount, mdiffVerts, RGBAColor(1, 0, 0, 1)); #endif +/ MinkowskiPoint v0, v1; if (*id && ENABLE_CACHING) { v0 = MinkowskiPointNew(ShapePoint(ctx.shape1, (*id >> 24) & 0xFF), ShapePoint(ctx.shape2, (*id >> 16) & 0xFF)); v1 = MinkowskiPointNew(ShapePoint(ctx.shape1, (*id >> 8) & 0xFF), ShapePoint(ctx.shape2, (*id ) & 0xFF)); } else { cpVect axis = cpvperp(cpvsub(cpBBCenter(ctx.shape1.bb), cpBBCenter(ctx.shape2.bb))); v0 = Support(ctx, axis); v1 = Support(ctx, cpvneg(axis)); } ClosestPoints points = GJKRecurse(ctx, v0, v1, 1); *id = points.id; return points; } //MARK: Contact Clipping void Contact1(cpFloat dist, cpVect a, cpVect b, cpFloat refr, cpFloat incr, cpVect n, cpHashValue hash, cpContact* arr) { cpFloat rsum = refr + incr; cpFloat alpha = (rsum > 0.0f ? refr / rsum : 0.5f); cpVect point = cpvlerp(a, b, alpha); cpContactInit(arr, point, n, dist - rsum, hash); } int Contact2(cpVect refp, cpVect inca, cpVect incb, cpFloat refr, cpFloat incr, cpVect refn, cpVect n, cpHashValue hash, cpContact* arr) { cpFloat cian = cpvcross(inca, refn); cpFloat cibn = cpvcross(incb, refn); cpFloat crpn = cpvcross(refp, refn); cpFloat t = 1.0f - cpfclamp01((cibn - crpn) / (cibn - cian)); cpVect point = cpvlerp(inca, incb, t); cpFloat pd = cpvdot(cpvsub(point, refp), refn); if (t > 0.0f && pd <= 0.0f) { cpFloat rsum = refr + incr; cpFloat alpha = (rsum > 0.0f ? incr * (1.0f - (rsum + pd) / rsum) : -0.5f * pd); cpContactInit(arr, cpvadd(point, cpvmult(refn, alpha)), n, pd, hash); return 1; } else { return 0; } } int ClipContacts(const Edge ref_, const Edge inc, const ClosestPoints points, const cpFloat nflip, cpContact* arr) { cpVect inc_offs = cpvmult(inc.n, inc.r); cpVect ref_offs = cpvmult(ref_.n, ref_.r); cpVect inca = cpvadd(inc.a.p, inc_offs); cpVect incb = cpvadd(inc.b.p, inc_offs); cpVect closest_inca = cpClosetPointOnSegment(inc.a.p, ref_.a.p, ref_.b.p); cpVect closest_incb = cpClosetPointOnSegment(inc.b.p, ref_.a.p, ref_.b.p); cpVect msa = cpvmult(points.n, nflip * points.d); cpFloat cost_a = cpvdistsq(cpvsub(inc.a.p, closest_inca), msa); cpFloat cost_b = cpvdistsq(cpvsub(inc.b.p, closest_incb), msa); /+ #if DRAW_CLIP ChipmunkDebugDrawSegment(ref_.a.p, ref_.b.p, RGBAColor(1, 0, 0, 1)); ChipmunkDebugDrawSegment(inc.a.p, inc.b.p, RGBAColor(0, 1, 0, 1)); ChipmunkDebugDrawSegment(inca, incb, RGBAColor(0, 1, 0, 1)); cpVect cref = cpvlerp(ref_.a.p, ref_.b.p, 0.5); ChipmunkDebugDrawSegment(cref, cpvadd(cref, cpvmult(ref_.n, 5.0)), RGBAColor(1, 0, 0, 1)); cpVect cinc = cpvlerp(inc.a.p, inc.b.p, 0.5); ChipmunkDebugDrawSegment(cinc, cpvadd(cinc, cpvmult(inc.n, 5.0)), RGBAColor(1, 0, 0, 1)); ChipmunkDebugDrawPoints(5.0, 2, (cpVect[]){ ref_.a.p, inc.a.p }, RGBAColor(1, 1, 0, 1)); ChipmunkDebugDrawPoints(5.0, 2, (cpVect[]){ ref_.b.p, inc.b.p }, RGBAColor(0, 1, 1, 1)); if (cost_a < cost_b) { ChipmunkDebugDrawSegment(closest_inca, inc.a.p, RGBAColor(1, 0, 1, 1)); } else { ChipmunkDebugDrawSegment(closest_incb, inc.b.p, RGBAColor(1, 0, 1, 1)); } #endif +/ cpHashValue hash_iarb = CP_HASH_PAIR(inc.a.hash, ref_.b.hash); cpHashValue hash_ibra = CP_HASH_PAIR(inc.b.hash, ref_.a.hash); if (cost_a < cost_b) { cpVect refp = cpvadd(ref_.a.p, ref_offs); Contact1(points.d, closest_inca, inc.a.p, ref_.r, inc.r, points.n, hash_iarb, arr); return Contact2(refp, inca, incb, ref_.r, inc.r, ref_.n, points.n, hash_ibra, arr + 1) + 1; } else { cpVect refp = cpvadd(ref_.b.p, ref_offs); Contact1(points.d, closest_incb, inc.b.p, ref_.r, inc.r, points.n, hash_ibra, arr); return Contact2(refp, incb, inca, ref_.r, inc.r, ref_.n, points.n, hash_iarb, arr + 1) + 1; } } int ContactPoints(const Edge e1, const Edge e2, const ClosestPoints points, cpContact* arr) { cpFloat mindist = e1.r + e2.r; if (points.d <= mindist) { cpFloat pick = cpvdot(e1.n, points.n) + cpvdot(e2.n, points.n); if ( (pick != 0.0f && pick > 0.0f) || // If the edges are both perfectly aligned weird things happen. // This is *very* common at the start of a simulation. // Pick the longest edge as the reference to break the tie. (pick == 0.0f && (cpvdistsq(e1.a.p, e1.b.p) > cpvdistsq(e2.a.p, e2.b.p))) ) { return ClipContacts(e1, e2, points, 1.0f, arr); } else { return ClipContacts(e2, e1, points, -1.0f, arr); } } else { return 0; } } //MARK: Collision Functions alias CollisionFunc = int function(const cpShape* a, const cpShape* b, cpCollisionID* id, cpContact* arr); // Collide circle shapes. int CircleToCircle(const cpCircleShape* c1, const cpCircleShape* c2, cpCollisionID* id, cpContact* arr) { return CircleToCircleQuery(c1.tc, c2.tc, c1.r, c2.r, 0, arr); } int CircleToSegment(const cpCircleShape* circleShape, const cpSegmentShape* segmentShape, cpCollisionID* id, cpContact* con) { cpVect seg_a = segmentShape.ta; cpVect seg_b = segmentShape.tb; cpVect center = circleShape.tc; cpVect seg_delta = cpvsub(seg_b, seg_a); cpFloat closest_t = cpfclamp01(cpvdot(seg_delta, cpvsub(center, seg_a)) / cpvlengthsq(seg_delta)); cpVect closest = cpvadd(seg_a, cpvmult(seg_delta, closest_t)); if (CircleToCircleQuery(center, closest, circleShape.r, segmentShape.r, 0, con)) { cpVect n = con[0].n; // Reject endcap collisions if tangents are provided. if ( (closest_t != 0.0f || cpvdot(n, cpvrotate(segmentShape.a_tangent, segmentShape.shape.body_.rot)) >= 0.0) && (closest_t != 1.0f || cpvdot(n, cpvrotate(segmentShape.b_tangent, segmentShape.shape.body_.rot)) >= 0.0) ) { return 1; } } return 0; } int SegmentToSegment(const cpSegmentShape* seg1, const cpSegmentShape* seg2, cpCollisionID* id, cpContact* arr) { SupportContext context = { cast(cpShape*)seg1, cast(cpShape*)seg2, safeCast!SupportPointFunc(&SegmentSupportPoint), safeCast!SupportPointFunc(&SegmentSupportPoint) }; ClosestPoints points = GJK(&context, id); /+ #if DRAW_CLOSEST #if PRINT_LOG // ChipmunkDemoPrintString("Distance: %.2f\n", points.d); #endif ChipmunkDebugDrawDot(6.0, points.a, RGBAColor(1, 1, 1, 1)); ChipmunkDebugDrawDot(6.0, points.b, RGBAColor(1, 1, 1, 1)); ChipmunkDebugDrawSegment(points.a, points.b, RGBAColor(1, 1, 1, 1)); ChipmunkDebugDrawSegment(points.a, cpvadd(points.a, cpvmult(points.n, 10.0)), RGBAColor(1, 0, 0, 1)); #endif +/ cpVect n = points.n; cpVect rot1 = seg1.shape.body_.rot; cpVect rot2 = seg2.shape.body_.rot; if ( points.d <= (seg1.r + seg2.r) && ( (!cpveql(points.a, seg1.ta) || cpvdot(n, cpvrotate(seg1.a_tangent, rot1)) <= 0.0) && (!cpveql(points.a, seg1.tb) || cpvdot(n, cpvrotate(seg1.b_tangent, rot1)) <= 0.0) && (!cpveql(points.b, seg2.ta) || cpvdot(n, cpvrotate(seg2.a_tangent, rot2)) >= 0.0) && (!cpveql(points.b, seg2.tb) || cpvdot(n, cpvrotate(seg2.b_tangent, rot2)) >= 0.0) ) ) { return ContactPoints(SupportEdgeForSegment(seg1, n), SupportEdgeForSegment(seg2, cpvneg(n)), points, arr); } else { return 0; } } int PolyToPoly(const cpPolyShape* poly1, const cpPolyShape* poly2, cpCollisionID* id, cpContact* arr) { SupportContext context = { cast(cpShape*)poly1, cast(cpShape*)poly2, safeCast!SupportPointFunc(&PolySupportPoint), safeCast!SupportPointFunc(&PolySupportPoint) }; ClosestPoints points = GJK(&context, id); /+ #if DRAW_CLOSEST #if PRINT_LOG // ChipmunkDemoPrintString("Distance: %.2f\n", points.d); #endif ChipmunkDebugDrawDot(3.0, points.a, RGBAColor(1, 1, 1, 1)); ChipmunkDebugDrawDot(3.0, points.b, RGBAColor(1, 1, 1, 1)); ChipmunkDebugDrawSegment(points.a, points.b, RGBAColor(1, 1, 1, 1)); ChipmunkDebugDrawSegment(points.a, cpvadd(points.a, cpvmult(points.n, 10.0)), RGBAColor(1, 0, 0, 1)); #endif +/ if (points.d - poly1.r - poly2.r <= 0.0) { return ContactPoints(SupportEdgeForPoly(poly1, points.n), SupportEdgeForPoly(poly2, cpvneg(points.n)), points, arr); } else { return 0; } } int SegmentToPoly(const cpSegmentShape* seg, const cpPolyShape* poly, cpCollisionID* id, cpContact* arr) { SupportContext context = { cast(cpShape*)seg, cast(cpShape*)poly, safeCast!SupportPointFunc(&SegmentSupportPoint), safeCast!SupportPointFunc(&PolySupportPoint) }; ClosestPoints points = GJK(&context, id); /+ #if DRAW_CLOSEST #if PRINT_LOG // ChipmunkDemoPrintString("Distance: %.2f\n", points.d); #endif ChipmunkDebugDrawDot(3.0, points.a, RGBAColor(1, 1, 1, 1)); ChipmunkDebugDrawDot(3.0, points.b, RGBAColor(1, 1, 1, 1)); ChipmunkDebugDrawSegment(points.a, points.b, RGBAColor(1, 1, 1, 1)); ChipmunkDebugDrawSegment(points.a, cpvadd(points.a, cpvmult(points.n, 10.0)), RGBAColor(1, 0, 0, 1)); #endif +/ // Reject endcap collisions if tangents are provided. cpVect n = points.n; cpVect rot = seg.shape.body_.rot; if ( points.d - seg.r - poly.r <= 0.0 && ( (!cpveql(points.a, seg.ta) || cpvdot(n, cpvrotate(seg.a_tangent, rot)) <= 0.0) && (!cpveql(points.a, seg.tb) || cpvdot(n, cpvrotate(seg.b_tangent, rot)) <= 0.0) ) ) { return ContactPoints(SupportEdgeForSegment(seg, n), SupportEdgeForPoly(poly, cpvneg(n)), points, arr); } else { return 0; } } // This one is less gross, but still gross. // TODO: Comment me! int CircleToPoly(const cpCircleShape* circle, const cpPolyShape* poly, cpCollisionID* id, cpContact* con) { SupportContext context = { cast(cpShape*)circle, cast(cpShape*)poly, safeCast!SupportPointFunc(&CircleSupportPoint), safeCast!SupportPointFunc(&PolySupportPoint) }; ClosestPoints points = GJK(&context, id); /+ #if DRAW_CLOSEST ChipmunkDebugDrawDot(3.0, points.a, RGBAColor(1, 1, 1, 1)); ChipmunkDebugDrawDot(3.0, points.b, RGBAColor(1, 1, 1, 1)); ChipmunkDebugDrawSegment(points.a, points.b, RGBAColor(1, 1, 1, 1)); ChipmunkDebugDrawSegment(points.a, cpvadd(points.a, cpvmult(points.n, 10.0)), RGBAColor(1, 0, 0, 1)); #endif +/ cpFloat mindist = circle.r + poly.r; if (points.d - mindist <= 0.0) { cpVect p = cpvlerp(points.a, points.b, circle.r / (mindist)); cpContactInit(con, p, points.n, points.d - mindist, 0); return 1; } else { return 0; } } /* const */ __gshared CollisionFunc[9] builtinCollisionFuncs; /* const */ __gshared CollisionFunc* colfuncs; /* const */ __gshared CollisionFunc[9] segmentCollisions; void _initModuleCtor_cpCollision() { builtinCollisionFuncs = [ safeCast!CollisionFunc(&CircleToCircle), null, null, safeCast!CollisionFunc(&CircleToSegment), null, null, safeCast!CollisionFunc(&CircleToPoly), safeCast!CollisionFunc(&SegmentToPoly), safeCast!CollisionFunc(&PolyToPoly), ]; colfuncs = builtinCollisionFuncs.ptr; segmentCollisions = [ safeCast!CollisionFunc(&CircleToCircle), null, null, safeCast!CollisionFunc(&CircleToSegment), safeCast!CollisionFunc(&SegmentToSegment), null, safeCast!CollisionFunc(&CircleToPoly), safeCast!CollisionFunc(&SegmentToPoly), safeCast!CollisionFunc(&PolyToPoly), ]; } void cpEnableSegmentToSegmentCollisions() { colfuncs = segmentCollisions.ptr; } int cpCollideShapes(const cpShape* a, const cpShape* b, cpCollisionID* id, cpContact* arr) { // Their shape types must be in order. cpAssertSoft(a.klass.type <= b.klass.type, "Internal Error: Collision shapes passed to cpCollideShapes() are not sorted."); CollisionFunc cfunc = colfuncs[a.klass.type + b.klass.type * CP_NUM_SHAPES]; int numContacts = (cfunc ? cfunc(a, b, id, arr) : 0); cpAssertSoft(numContacts <= CP_MAX_CONTACTS_PER_ARBITER, "Internal error: Too many contact points returned."); return numContacts; }
D
Long: ssl-auto-client-cert Help: Use auto client certificate (Schannel) Added: 7.77.0 See-also: proxy-ssl-auto-client-cert Category: tls --- Tell libcurl to automatically locate and use a client certificate for authentication, when requested by the server. This option is only supported for Schannel (the native Windows SSL library). Prior to 7.77.0 this was the default behavior in libcurl with Schannel. Since the server can request any certificate that supports client authentication in the OS certificate store it could be a privacy violation and unexpected.
D
import winrt; import std.traits; static import Windows.UI.Xaml; mixin WinRTMain; pragma(msg, winrtFactoryOf!(Windows.UI.Xaml.Application)); class MyApp : Windows.UI.Xaml.Application { override void OnLaunched(void* args) { Debug.WriteLine("Launched"); } } int rtmain() { //auto inspApp = roActivateInstance("Windows.UI.Xaml.Application"); auto app = new MyApp; auto inspApp = make(app); Debug.Inspect(inspApp.handle); return 0; }
D
/// MZ executable object format. /// /// Authors: dd86k <dd@dax.moe> /// Copyright: © dd86k <dd@dax.moe> /// License: BSD-3-Clause module adbg.v2.object.format.mz; import adbg.v2.object.server : adbg_object_t, AdbgObject; import adbg.utils.bit : CHAR16; /// Magic number for MZ objects. enum MAGIC_MZ = CHAR16!"MZ"; private enum ERESWDS = 16; private enum PAGE = 512; /// MZ header structure struct mz_hdr { ushort e_magic; /// Magic number ushort e_cblp; /// Bytes on last page of file ushort e_cp; /// Pages in file ushort e_crlc; /// Number of relocation entries in the table ushort e_cparh; /// Size of header in paragraphs ushort e_minalloc; /// Minimum extra paragraphs needed ushort e_maxalloc; /// Maximum extra paragraphs needed ushort e_ss; /// Initial (relative) SS value ushort e_sp; /// Initial SP value ushort e_csum; /// Checksum ushort e_ip; /// Initial IP value ushort e_cs; /// Initial (relative) CS value ushort e_lfarlc; /// File address of relocation table ushort e_ovno; /// Overlay number ushort[ERESWDS] e_res; /// Reserved words uint e_lfanew; /// File address of new exe header (usually at 3Ch) } static assert(mz_hdr.e_lfanew.offsetof == 0x3c); /// MZ relocation entry struct mz_reloc { ushort offset; ushort segment; } int adbg_object_mz_load(adbg_object_t *obj) { obj.format = AdbgObject.mz; obj.i.mz.header = cast(mz_hdr*)obj.buffer; with (obj.i.mz) if (header.e_lfarlc && header.e_crlc && header.e_lfarlc < obj.file_size) relocs = cast(mz_reloc*)(obj.buffer + header.e_lfarlc); return 0; }
D
module std.switcherr; public import std.exception; pragma(msg, "warning - STD.SWITCHERR:Now all exceptions and errors are situated in module std.exception");
D
/home/javed/Documents/Projects/RustRepo/ultimate_rust_crash_course/exercise/z_final_project/target/release/build/syn-65a89650853e59b6/build_script_build-65a89650853e59b6: /home/javed/.cargo/registry/src/github.com-1ecc6299db9ec823/syn-0.15.44/build.rs /home/javed/Documents/Projects/RustRepo/ultimate_rust_crash_course/exercise/z_final_project/target/release/build/syn-65a89650853e59b6/build_script_build-65a89650853e59b6.d: /home/javed/.cargo/registry/src/github.com-1ecc6299db9ec823/syn-0.15.44/build.rs /home/javed/.cargo/registry/src/github.com-1ecc6299db9ec823/syn-0.15.44/build.rs:
D
/// D translation of stb_truetype v0.7 by Sean Barrett /// More information on http://nothings.org/stb/stb_truetype.h /// Removed: /// - texture baking API /// - font finding in the TTF itself. Make sure there is only one font in the TTF. module dido.stb_truetype; import core.stdc.stdlib : malloc, free, qsort; import core.stdc.string : memcpy, memset; import std.math : ceil, floor, sqrt; //import dplug.core.nogc; int ifloor(float x) nothrow @nogc { return cast(int)(floor(x)); } int iceil(float x) nothrow @nogc { return cast(int)(ceil(x)); } /// The following structure is defined publically so you can declare one on /// the stack or as a global or etc, but you should treat it as opaque. struct stbtt_fontinfo { const(ubyte) * data; // pointer to .ttf file int fontstart; // offset of start of font int numGlyphs; // number of glyphs, needed for range checking int loca,head,glyf,hhea,hmtx,kern; // table locations as offset from start of .ttf int index_map; // a cmap mapping for our chosen character encoding int indexToLocFormat; // format needed to map from glyph index to glyph } enum STBTT_vmove = 1, STBTT_vline = 2, STBTT_vcurve = 3; alias stbtt_vertex_type = short; struct stbtt_vertex { stbtt_vertex_type x,y,cx,cy; ubyte type, padding; } struct stbtt__bitmap { int w,h,stride; ubyte *pixels; } enum // platformID STBTT_PLATFORM_ID_UNICODE =0, STBTT_PLATFORM_ID_MAC =1, STBTT_PLATFORM_ID_ISO =2, STBTT_PLATFORM_ID_MICROSOFT =3; enum // encodingID for STBTT_PLATFORM_ID_MICROSOFT STBTT_MS_EID_SYMBOL =0, STBTT_MS_EID_UNICODE_BMP =1, STBTT_MS_EID_SHIFTJIS =2, STBTT_MS_EID_UNICODE_FULL =10; // Accessors to parse data from file ubyte ttBYTE(const(ubyte)* p) nothrow @nogc { return *p; } byte ttCHAR(const(ubyte)* p) nothrow @nogc { return *p; } int ttFixed(const(ubyte)* p) nothrow @nogc { return ttLONG(p); } ushort ttUSHORT(const(ubyte) *p) nothrow @nogc { return p[0]*256 + p[1]; } short ttSHORT(const(ubyte) *p) nothrow @nogc { return cast(short)(p[0]*256 + p[1]); } uint ttULONG(const(ubyte) *p) nothrow @nogc { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } int ttLONG(const(ubyte) *p) nothrow @nogc { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } bool stbtt_tag4(const(ubyte) *p, ubyte c0, ubyte c1, ubyte c2, ubyte c3) nothrow @nogc { return (p[0] == c0 && p[1] == c1 && p[2] == c2 && p[3] == c3); } bool stbtt_tag(const(ubyte) *p, string s) nothrow @nogc { return stbtt_tag4(p, s[0], s[1], s[2], s[3]); } bool stbtt__isfont(const(ubyte) *font) nothrow @nogc { // check the version number if (stbtt_tag4(font, '1',0,0,0)) return true; // TrueType 1 if (stbtt_tag(font, "typ1")) return true; // TrueType with type 1 font -- we don't support this! if (stbtt_tag(font, "OTTO")) return true; // OpenType with CFF if (stbtt_tag4(font, 0,1,0,0)) return true; // OpenType 1.0 return false; } // @OPTIMIZE: binary search uint stbtt__find_table(const(ubyte)* data, uint fontstart, string tag) nothrow @nogc { int num_tables = ttUSHORT(data+fontstart+4); uint tabledir = fontstart + 12; for (int i=0; i < num_tables; ++i) { uint loc = tabledir + 16*i; if (stbtt_tag(data+loc+0, tag)) return ttULONG(data+loc+8); } return 0; } /// Each .ttf/.ttc file may have more than one font. Each font has a sequential /// index number starting from 0. Call this function to get the font offset for /// a given index; it returns -1 if the index is out of range. A regular .ttf /// file will only define one font and it always be at offset 0, so it will /// return '0' for index 0, and -1 for all other indices. You can just skip /// this step if you know it's that kind of font. int stbtt_GetFontOffsetForIndex(const(ubyte)* font_collection, int index) nothrow @nogc { // if it's just a font, there's only one valid index if (stbtt__isfont(font_collection)) return index == 0 ? 0 : -1; // check if it's a TTC if (stbtt_tag(font_collection, "ttcf")) { // version 1? if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { int n = ttLONG(font_collection+8); if (index >= n) return -1; return ttULONG(font_collection+12+index*14); } } return -1; } /// Given an offset into the file that defines a font, this function builds /// the necessary cached info for the rest of the system. You must allocate /// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't /// need to do anything special to free it, because the contents are pure /// value data with no additional data structures. Returns 0 on failure. int stbtt_InitFont(stbtt_fontinfo* info, const(ubyte)* data2, int fontstart) nothrow @nogc { const(ubyte) *data = data2; uint cmap, t; int i,numTables; info.data = data; info.fontstart = fontstart; cmap = stbtt__find_table(data, fontstart, "cmap"); // required info.loca = stbtt__find_table(data, fontstart, "loca"); // required info.head = stbtt__find_table(data, fontstart, "head"); // required info.glyf = stbtt__find_table(data, fontstart, "glyf"); // required info.hhea = stbtt__find_table(data, fontstart, "hhea"); // required info.hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required info.kern = stbtt__find_table(data, fontstart, "kern"); // not required if (!cmap || !info.loca || !info.head || !info.glyf || !info.hhea || !info.hmtx) return 0; t = stbtt__find_table(data, fontstart, "maxp"); if (t) info.numGlyphs = ttUSHORT(data+t+4); else info.numGlyphs = 0xffff; // find a cmap encoding table we understand *now* to avoid searching // later. (todo: could make this installable) // the same regardless of glyph. numTables = ttUSHORT(data + cmap + 2); info.index_map = 0; for (i=0; i < numTables; ++i) { uint encoding_record = cmap + 4 + 8 * i; // find an encoding we understand: switch(ttUSHORT(data+encoding_record)) { case STBTT_PLATFORM_ID_MICROSOFT: switch (ttUSHORT(data+encoding_record+2)) { case STBTT_MS_EID_UNICODE_BMP: case STBTT_MS_EID_UNICODE_FULL: // MS/Unicode info.index_map = cmap + ttULONG(data+encoding_record+4); break; default: assert(0); } break; default: break; } } if (info.index_map == 0) return 0; info.indexToLocFormat = ttUSHORT(data+info.head + 50); return 1; } /// If you're going to perform multiple operations on the same character /// and you want a speed-up, call this function with the character you're /// going to process, then use glyph-based functions instead of the /// codepoint-based functions. int stbtt_FindGlyphIndex(const(stbtt_fontinfo) *info, int unicode_codepoint) nothrow @nogc { const(ubyte)* data = info.data; uint index_map = info.index_map; ushort format = ttUSHORT(data + index_map + 0); if (format == 0) { // apple byte encoding int bytes = ttUSHORT(data + index_map + 2); if (unicode_codepoint < bytes-6) return ttBYTE(data + index_map + 6 + unicode_codepoint); return 0; } else if (format == 6) { uint first = ttUSHORT(data + index_map + 6); uint count = ttUSHORT(data + index_map + 8); if (cast(uint) unicode_codepoint >= first && cast(uint)unicode_codepoint < first+count) return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2); return 0; } else if (format == 2) { assert(0); // @TODO: high-byte mapping for japanese/chinese/korean } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges ushort segcount = ttUSHORT(data+index_map+6) >> 1; ushort searchRange = ttUSHORT(data+index_map+8) >> 1; ushort entrySelector = ttUSHORT(data+index_map+10); ushort rangeShift = ttUSHORT(data+index_map+12) >> 1; ushort item, offset, start, end; // do a binary search of the segments uint endCount = index_map + 14; uint search = endCount; if (unicode_codepoint > 0xffff) return 0; // they lie from endCount .. endCount + segCount // but searchRange is the nearest power of two, so... if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2)) search += rangeShift*2; // now decrement to bias correctly to find smallest search -= 2; while (entrySelector) { ushort start2, end2; searchRange >>= 1; start2 = ttUSHORT(data + search + 2 + segcount*2 + 2); end2 = ttUSHORT(data + search + 2); start2 = ttUSHORT(data + search + searchRange*2 + segcount*2 + 2); end2 = ttUSHORT(data + search + searchRange*2); if (unicode_codepoint > end2) search += searchRange*2; --entrySelector; } search += 2; item = cast(ushort) ((search - endCount) >> 1); assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item)); start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); end = ttUSHORT(data + index_map + 14 + 2 + 2*item); if (unicode_codepoint < start) return 0; offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); if (offset == 0) return cast(ushort) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); } else if (format == 12 || format == 13) { uint ngroups = ttULONG(data+index_map+12); int low,high; low = 0; high = ngroups; // Binary search the right group. while (low < high) { int mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high uint start_char = ttULONG(data+index_map+16+mid*12); uint end_char = ttULONG(data+index_map+16+mid*12+4); if (unicode_codepoint < start_char) high = mid; else if (unicode_codepoint > end_char) low = mid+1; else { uint start_glyph = ttULONG(data+index_map+16+mid*12+8); if (format == 12) return start_glyph + unicode_codepoint-start_char; else // format == 13 return start_glyph; } } return 0; // not found } // @TODO assert(0); } /// Returns: Number of vertices and fills *vertices with the pointer to them. /// These are expressed in "unscaled" coordinates. int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices) nothrow @nogc { return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices); } void stbtt_setvertex(stbtt_vertex *v, ubyte type, int x, int y, int cx, int cy) nothrow @nogc { v.type = type; v.x = cast(short) x; v.y = cast(short) y; v.cx = cast(short) cx; v.cy = cast(short) cy; } int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) nothrow @nogc { int g1,g2; if (glyph_index >= info.numGlyphs) return -1; // glyph index out of range if (info.indexToLocFormat >= 2) return -1; // unknown index.glyph map format if (info.indexToLocFormat == 0) { g1 = info.glyf + ttUSHORT(info.data + info.loca + glyph_index * 2) * 2; g2 = info.glyf + ttUSHORT(info.data + info.loca + glyph_index * 2 + 2) * 2; } else { g1 = info.glyf + ttULONG (info.data + info.loca + glyph_index * 4); g2 = info.glyf + ttULONG (info.data + info.loca + glyph_index * 4 + 4); } return g1==g2 ? -1 : g1; // if length is 0, return -1 } /// As above, but takes one or more glyph indices for greater efficiency int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) nothrow @nogc { int g = stbtt__GetGlyfOffset(info, glyph_index); if (g < 0) return 0; if (x0) *x0 = ttSHORT(info.data + g + 2); if (y0) *y0 = ttSHORT(info.data + g + 4); if (x1) *x1 = ttSHORT(info.data + g + 6); if (y1) *y1 = ttSHORT(info.data + g + 8); return 1; } /// Gets the bounding box of the visible part of the glyph, in unscaled coordinates int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1) nothrow @nogc { return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1); } /// Returns: non-zero if nothing is drawn for this glyph int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index) nothrow @nogc { short numberOfContours; int g = stbtt__GetGlyfOffset(info, glyph_index); if (g < 0) return 1; numberOfContours = ttSHORT(info.data + g); return numberOfContours == 0; } int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off, int sx, int sy, int scx, int scy, int cx, int cy) nothrow @nogc { if (start_off) { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy); } else { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy); else stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0); } return num_vertices; } /// Returns: Number of vertices and fills *vertices with the pointer to them. /// These are expressed in "unscaled" coordinates. int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) nothrow @nogc { short numberOfContours; const(ubyte)* endPtsOfContours; const(ubyte)* data = info.data; stbtt_vertex* vertices = null; int num_vertices=0; int g = stbtt__GetGlyfOffset(info, glyph_index); *pvertices = null; if (g < 0) return 0; numberOfContours = ttSHORT(data + g); if (numberOfContours > 0) { ubyte flags=0,flagcount; int ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; int x,y,cx,cy,sx,sy, scx,scy; const(ubyte)* points; endPtsOfContours = (data + g + 10); ins = ttUSHORT(data + g + 10 + numberOfContours * 2); points = data + g + 10 + numberOfContours * 2 + 2 + ins; n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2); m = n + 2*numberOfContours; // a loose bound on how many vertices we might need vertices = cast(stbtt_vertex *) malloc(m * stbtt_vertex.sizeof); if (vertices == null) return 0; next_move = 0; flagcount=0; // in first pass, we load uninterpreted data into the allocated array // above, shifted to the end of the array so we won't overwrite it when // we create our final data starting from the front off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated // first load flags for (i=0; i < n; ++i) { if (flagcount == 0) { flags = *points++; if (flags & 8) flagcount = *points++; } else --flagcount; vertices[off+i].type = flags; } // now load x coordinates x=0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; if (flags & 2) { short dx = *points++; x += (flags & 16) ? dx : -dx; // ??? } else { if (!(flags & 16)) { x = x + cast(short) (points[0]*256 + points[1]); points += 2; } } vertices[off+i].x = cast(short) x; } // now load y coordinates y=0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; if (flags & 4) { short dy = *points++; y += (flags & 32) ? dy : -dy; // ??? } else { if (!(flags & 32)) { y = y + cast(short) (points[0]*256 + points[1]); points += 2; } } vertices[off+i].y = cast(short) y; } // now convert them to our format num_vertices=0; sx = sy = cx = cy = scx = scy = 0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; x = cast(short) vertices[off+i].x; y = cast(short) vertices[off+i].y; if (next_move == i) { if (i != 0) num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); // now start the new one start_off = !(flags & 1); if (start_off) { // if we start off with an off-curve point, then when we need to find a point on the curve // where we can start, and we need to save some state for when we wraparound. scx = x; scy = y; if (!(vertices[off+i+1].type & 1)) { // next point is also a curve point, so interpolate an on-point curve sx = (x + cast(int) vertices[off+i+1].x) >> 1; sy = (y + cast(int) vertices[off+i+1].y) >> 1; } else { // otherwise just use the next point as our start point sx = cast(int) vertices[off+i+1].x; sy = cast(int) vertices[off+i+1].y; ++i; // we're using point i+1 as the starting point, so skip it } } else { sx = x; sy = y; } stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0); was_off = 0; next_move = 1 + ttUSHORT(endPtsOfContours+j*2); ++j; } else { if (!(flags & 1)) { // if it's a curve if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); cx = x; cy = y; was_off = 1; } else { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy); else stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0); was_off = 0; } } } num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); } else if (numberOfContours == -1) { // Compound shapes. int more = 1; const(ubyte)* comp = data + g + 10; num_vertices = 0; vertices = null; while (more) { ushort flags, gidx; int comp_num_verts = 0, i; stbtt_vertex* comp_verts = null, tmp = null; float[6] mtx = [1,0,0,1,0,0]; float m, n; flags = ttSHORT(comp); comp+=2; gidx = ttSHORT(comp); comp+=2; if (flags & 2) { // XY values if (flags & 1) { // shorts mtx[4] = ttSHORT(comp); comp+=2; mtx[5] = ttSHORT(comp); comp+=2; } else { mtx[4] = ttCHAR(comp); comp+=1; mtx[5] = ttCHAR(comp); comp+=1; } } else { // @TODO handle matching point assert(0); } if (flags & (1<<3)) { // WE_HAVE_A_SCALE mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = mtx[2] = 0; } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = mtx[2] = 0; mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = ttSHORT(comp)/16384.0f; comp+=2; mtx[2] = ttSHORT(comp)/16384.0f; comp+=2; mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; } // Find transformation scales. m = cast(float) sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); n = cast(float) sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); // Get indexed glyph. comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); if (comp_num_verts > 0) { // Transform vertices. for (i = 0; i < comp_num_verts; ++i) { stbtt_vertex* v = &comp_verts[i]; stbtt_vertex_type x,y; x=v.x; y=v.y; v.x = cast(stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); v.y = cast(stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); x=v.cx; y=v.cy; v.cx = cast(stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); v.cy = cast(stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); } // Append vertices. tmp = cast(stbtt_vertex*) malloc((num_vertices+comp_num_verts)*stbtt_vertex.sizeof); if (!tmp) { if (vertices) free(vertices); if (comp_verts) free(comp_verts); return 0; } if (num_vertices > 0) memcpy(tmp, vertices, num_vertices*stbtt_vertex.sizeof); memcpy(tmp+num_vertices, comp_verts, comp_num_verts*stbtt_vertex.sizeof); if (vertices) free(vertices); vertices = tmp; free(comp_verts); num_vertices += comp_num_verts; } // More components ? more = flags & (1<<5); } } else if (numberOfContours < 0) { // @TODO other compound variations? assert(0); } else { // numberOfCounters == 0, do nothing } *pvertices = vertices; return num_vertices; } void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) nothrow @nogc { ushort numOfLongHorMetrics = ttUSHORT(info.data+info.hhea + 34); if (glyph_index < numOfLongHorMetrics) { if (advanceWidth) *advanceWidth = ttSHORT(info.data + info.hmtx + 4*glyph_index); if (leftSideBearing) *leftSideBearing = ttSHORT(info.data + info.hmtx + 4*glyph_index + 2); } else { if (advanceWidth) *advanceWidth = ttSHORT(info.data + info.hmtx + 4*(numOfLongHorMetrics-1)); if (leftSideBearing) *leftSideBearing = ttSHORT(info.data + info.hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); } } int stbtt_GetGlyphKernAdvance(const(stbtt_fontinfo)* info, int glyph1, int glyph2) nothrow @nogc { const(ubyte)* data = info.data + info.kern; uint needle, straw; int l, r, m; // we only look at the first table. it must be 'horizontal' and format 0. if (!info.kern) return 0; if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 return 0; if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format return 0; l = 0; r = ttUSHORT(data+10) - 1; needle = glyph1 << 16 | glyph2; while (l <= r) { m = (l + r) >> 1; straw = ttULONG(data+18+(m*6)); // note: unaligned read if (needle < straw) r = m - 1; else if (needle > straw) l = m + 1; else return ttSHORT(data+22+(m*6)); } return 0; } /// an additional amount to add to the 'advance' value between ch1 and ch2 /// @TODO; for now always returns 0! int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2) nothrow @nogc { if (!info.kern) // if no kerning table, don't waste time looking up both codepoint.glyphs return 0; return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2)); } /// leftSideBearing is the offset from the current horizontal position to the left edge of the character /// advanceWidth is the offset from the current horizontal position to the next horizontal position /// these are expressed in unscaled coordinates void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing) nothrow @nogc { stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); } /// Ascent is the coordinate above the baseline the font extends; descent /// is the coordinate below the baseline the font extends (i.e. it is typically negative) /// lineGap is the spacing between one row's descent and the next row's ascent... /// so you should advance the vertical position by "*ascent - *descent + *lineGap" /// these are expressed in unscaled coordinates, so you must multiply by /// the scale factor for a given size void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) nothrow @nogc { if (ascent ) *ascent = ttSHORT(info.data+info.hhea + 4); if (descent) *descent = ttSHORT(info.data+info.hhea + 6); if (lineGap) *lineGap = ttSHORT(info.data+info.hhea + 8); } /// the bounding box around all possible characters void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1) nothrow @nogc { *x0 = ttSHORT(info.data + info.head + 36); *y0 = ttSHORT(info.data + info.head + 38); *x1 = ttSHORT(info.data + info.head + 40); *y1 = ttSHORT(info.data + info.head + 42); } /// Computes a scale factor to produce a font whose "height" is 'pixels' tall. /// Height is measured as the distance from the highest ascender to the lowest /// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics /// and computing: /// scale = pixels / (ascent - descent) /// so if you prefer to measure height by the ascent only, use a similar calculation. float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) nothrow @nogc { int fheight = ttSHORT(info.data + info.hhea + 4) - ttSHORT(info.data + info.hhea + 6); return cast(float) height / fheight; } /// computes a scale factor to produce a font whose EM size is mapped to /// 'pixels' tall. This is probably what traditional APIs compute, but /// I'm not positive. float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) nothrow @nogc { int unitsPerEm = ttUSHORT(info.data + info.head + 18); return pixels / unitsPerEm; } /// void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) nothrow @nogc { free(v); } ////////////////////////////////////////////////////////////////////////////// // // antialiasing software rasterizer // void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) nothrow @nogc { int x0, y0, x1, y1; if (!stbtt_GetGlyphBox(font, glyph, &x0, &y0, &x1, &y1)) { // e.g. space character if (ix0) *ix0 = 0; if (iy0) *iy0 = 0; if (ix1) *ix1 = 0; if (iy1) *iy1 = 0; } else { // move to integral bboxes (treating pixels as little squares, what pixels get touched)? if (ix0) *ix0 = ifloor( x0 * scale_x + shift_x); if (iy0) *iy0 = ifloor(-y1 * scale_y + shift_y); if (ix1) *ix1 = iceil( x1 * scale_x + shift_x); if (iy1) *iy1 = iceil(-y0 * scale_y + shift_y); } } void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) nothrow @nogc { stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); } /// Same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel /// shift for the character. void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) nothrow @nogc { stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1); } /// Gets the bbox of the bitmap centered around the glyph origin; so the /// bitmap width is ix1-ix0, height is iy1-iy0, and location to place /// the bitmap top left is (leftSideBearing*scale,iy0). /// (Note that the bitmap uses y-increases-down, but the shape uses /// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) nothrow @nogc { stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1); } struct stbtt__edge { float x0,y0, x1,y1; int invert; } struct stbtt__active_edge { int x,dx; float ey; stbtt__active_edge* next; int valid; } enum FIXSHIFT = 10; enum FIX = (1 << FIXSHIFT); enum FIXMASK = (FIX-1); stbtt__active_edge *new_active(stbtt__edge *e, int off_x, float start_point) nothrow @nogc { stbtt__active_edge *z = cast(stbtt__active_edge *) malloc(stbtt__active_edge.sizeof); // @TODO: make a pool of these!!! float dxdy = (e.x1 - e.x0) / (e.y1 - e.y0); assert(e.y0 <= start_point); if (!z) return z; // round dx down to avoid going too far if (dxdy < 0) z.dx = -ifloor(FIX * -dxdy); else z.dx = ifloor(FIX * dxdy); z.x = ifloor(FIX * (e.x0 + dxdy * (start_point - e.y0))); z.x -= off_x * FIX; z.ey = e.y1; z.next = null; z.valid = e.invert ? 1 : -1; return z; } // note: this routine clips fills that extend off the edges... ideally this // wouldn't happen, but it could happen if the truetype glyph bounding boxes // are wrong, or if the user supplies a too-small bitmap void stbtt__fill_active_edges(ubyte *scanline, int len, stbtt__active_edge *e, int max_weight) nothrow @nogc { // non-zero winding fill int x0=0, w=0; while (e) { if (w == 0) { // if we're currently at zero, we need to record the edge start point x0 = e.x; w += e.valid; } else { int x1 = e.x; w += e.valid; // if we went to zero, we need to draw if (w == 0) { int i = x0 >> FIXSHIFT; int j = x1 >> FIXSHIFT; if (i < len && j >= 0) { if (i == j) { // x0,x1 are the same pixel, so compute combined coverage scanline[i] = cast(ubyte)( scanline[i] + ((x1 - x0) * max_weight >> FIXSHIFT) ); } else { if (i >= 0) // add antialiasing for x0 scanline[i] = cast(ubyte)( scanline[i] + (((FIX - (x0 & FIXMASK)) * max_weight) >> FIXSHIFT) ) ; else i = -1; // clip if (j < len) // add antialiasing for x1 scanline[j] = cast(ubyte)( scanline[j] + (((x1 & FIXMASK) * max_weight) >> FIXSHIFT) ); else j = len; // clip for (++i; i < j; ++i) // fill pixels between x0 and x1 scanline[i] = cast(ubyte)( scanline[i] + max_weight ); } } } } e = e.next; } } void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y) nothrow @nogc { stbtt__active_edge* active = null; int y,j=0; int max_weight = (255 / vsubsample); // weight per vertical scanline int s; // vertical subsample index ubyte[512] scanline_data; ubyte* scanline; if (result.w > 512) scanline = cast(ubyte *) malloc(result.w); else scanline = scanline_data.ptr; y = off_y * vsubsample; e[n].y0 = (off_y + result.h) * cast(float) vsubsample + 1; while (j < result.h) { memset(scanline, 0, result.w); for (s=0; s < vsubsample; ++s) { // find center of pixel for this scanline float scan_y = y + 0.5f; stbtt__active_edge **step = &active; // update all active edges; // remove all active edges that terminate before the center of this scanline while (*step) { stbtt__active_edge * z = *step; if (z.ey <= scan_y) { *step = z.next; // delete from list assert(z.valid); z.valid = 0; free(z); } else { z.x += z.dx; // advance to position for current scanline step = &((*step).next); // advance through list } } // resort the list if needed for(;;) { int changed=0; step = &active; while (*step && (*step).next) { if ((*step).x > (*step).next.x) { stbtt__active_edge *t = *step; stbtt__active_edge *q = t.next; t.next = q.next; q.next = t; *step = q; changed = 1; } step = &(*step).next; } if (!changed) break; } // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline while (e.y0 <= scan_y) { if (e.y1 > scan_y) { stbtt__active_edge *z = new_active(e, off_x, scan_y); // find insertion point if (active == null) active = z; else if (z.x < active.x) { // insert at front z.next = active; active = z; } else { // find thing to insert AFTER stbtt__active_edge *p = active; while (p.next && p.next.x < z.x) p = p.next; // at this point, p.next.x is NOT < z.x z.next = p.next; p.next = z; } } ++e; } // now process all active edges in XOR fashion if (active) stbtt__fill_active_edges(scanline, result.w, active, max_weight); ++y; } memcpy(result.pixels + j * result.stride, scanline, result.w); ++j; } while (active) { stbtt__active_edge *z = active; active = active.next; free(z); } if (scanline != scanline_data.ptr) free(scanline); } struct stbtt__point { float x,y; } void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert) nothrow @nogc { float y_scale_inv = invert ? -scale_y : scale_y; stbtt__edge *e; int n,i,j,k,m; int vsubsample = result.h < 8 ? 15 : 5; // vsubsample should divide 255 evenly; otherwise we won't reach full opacity // now we have to blow out the windings into explicit edge lists n = 0; for (i=0; i < windings; ++i) n += wcount[i]; e = cast(stbtt__edge *) malloc(stbtt__edge.sizeof * (n+1)); // add an extra one as a sentinel if (e == null) return; n = 0; m=0; for (i=0; i < windings; ++i) { stbtt__point *p = pts + m; m += wcount[i]; j = wcount[i]-1; for (k=0; k < wcount[i]; j=k++) { int a=k,b=j; // skip the edge if horizontal if (p[j].y == p[k].y) continue; // add edge from j to k to the list e[n].invert = 0; if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { e[n].invert = 1; a=j,b=k; } e[n].x0 = p[a].x * scale_x + shift_x; e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample; e[n].x1 = p[b].x * scale_x + shift_x; e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample; ++n; } } int edgeCompare(const(stbtt__edge) a, const(stbtt__edge) b) nothrow @nogc { if (a.y0 < b.y0) return -1; if (a.y0 > b.y0) return 1; return 0; } // now sort the edges by their highest point (should snap to integer, and then by x) quicksort!stbtt__edge(e[0..n], &edgeCompare); // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y); free(e); } void stbtt__add_point(stbtt__point *points, int n, float x, float y) nothrow @nogc { if (!points) return; // during first pass, it's unallocated points[n].x = x; points[n].y = y; } // tesselate until threshhold p is happy... @TODO warped to compensate for non-linear stretching int stbtt__tesselate_curve(stbtt__point *points, int *num_points, double x0, double y0, double x1, double y1, double x2, double y2, double objspace_flatness_squared, int n) nothrow @nogc { bool stopSubdiv = (n > 16); // midpoint double mx = (x0 + 2*x1 + x2)*0.25f; double my = (y0 + 2*y1 + y2)*0.25f; // versus directly drawn line double dx = (x0+x2)*0.5f - mx; double dy = (y0+y2)*0.5f - my; double squarexy = dx*dx+dy*dy; bool addThisPoint = true; if (squarexy > objspace_flatness_squared && !stopSubdiv) { // half-pixel error allowed... need to be smaller if AA int res1, res2; { double x01h = (x0 + x1) * 0.5f; double y01h = (y0 + y1) * 0.5f; res1 = stbtt__tesselate_curve(points, num_points, x0, y0, x01h, y01h, mx,my, objspace_flatness_squared,n+1); } { double x12h = (x1 + x2) * 0.5f; double y12h = (y1 + y2) * 0.5f; res2 = stbtt__tesselate_curve(points, num_points, mx, my, x12h, y12h, x2,y2, objspace_flatness_squared,n+1); } addThisPoint = false; } if (addThisPoint) // do stuff here even in subdivided case to avoid TCO { stbtt__add_point(points, *num_points,x2,y2); *num_points = *num_points+1; } return 1; } // returns number of contours stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours) nothrow @nogc { stbtt__point* points = null; int num_points=0; float objspace_flatness_squared = objspace_flatness * objspace_flatness; int i,n=0,start=0, pass; // count how many "moves" there are to get the contour count for (i=0; i < num_verts; ++i) if (vertices[i].type == STBTT_vmove) ++n; *num_contours = n; if (n == 0) return null; *contour_lengths = cast(int *) malloc(int.sizeof * n); if (*contour_lengths == null) { *num_contours = 0; return null; } // make two passes through the points so we don't need to realloc for (pass=0; pass < 2; ++pass) { float x=0,y=0; if (pass == 1) { points = cast(stbtt__point *) malloc(num_points * stbtt__point.sizeof); if (points == null) goto error; } num_points = 0; n= -1; for (i=0; i < num_verts; ++i) { switch (vertices[i].type) { case STBTT_vmove: // start the next contour if (n >= 0) (*contour_lengths)[n] = num_points - start; ++n; start = num_points; x = vertices[i].x, y = vertices[i].y; stbtt__add_point(points, num_points++, x,y); break; case STBTT_vline: x = vertices[i].x, y = vertices[i].y; stbtt__add_point(points, num_points++, x, y); break; case STBTT_vcurve: stbtt__tesselate_curve(points, &num_points, x,y, vertices[i].cx, vertices[i].cy, vertices[i].x, vertices[i].y, objspace_flatness_squared, 0); x = vertices[i].x, y = vertices[i].y; break; default: assert(0); } } (*contour_lengths)[n] = num_points - start; } return points; error: free(points); free(*contour_lengths); *contour_lengths = null; *num_contours = 0; return null; } void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert) nothrow @nogc { float scale = scale_x > scale_y ? scale_y : scale_x; int winding_count; int* winding_lengths; stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count); if (windings) { stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert); free(winding_lengths); free(windings); } } /// Frees the allocated bitmap. void stbtt_FreeBitmap(ubyte *bitmap) nothrow @nogc { free(bitmap); } ubyte *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff) nothrow @nogc { int ix0,iy0,ix1,iy1; stbtt__bitmap gbm; stbtt_vertex *vertices; int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); if (scale_x == 0) scale_x = scale_y; if (scale_y == 0) { if (scale_x == 0) return null; scale_y = scale_x; } stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1); // now we get the size gbm.w = (ix1 - ix0); gbm.h = (iy1 - iy0); gbm.pixels = null; // in case we error if (width ) *width = gbm.w; if (height) *height = gbm.h; if (xoff ) *xoff = ix0; if (yoff ) *yoff = iy0; if (gbm.w && gbm.h) { gbm.pixels = cast(ubyte *) malloc(gbm.w * gbm.h); if (gbm.pixels) { gbm.stride = gbm.w; stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1); } } free(vertices); return gbm.pixels; } ubyte *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff) nothrow @nogc { return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff); } void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, ubyte *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph) nothrow @nogc { int ix0,iy0; stbtt_vertex *vertices; int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); stbtt__bitmap gbm; stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,null,null); gbm.pixels = output; gbm.w = out_w; gbm.h = out_h; gbm.stride = out_stride; if (gbm.w && gbm.h) stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1); free(vertices); } void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, ubyte *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph) nothrow @nogc { stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph); } /// The same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel /// shift for the character. ubyte *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff) nothrow @nogc { return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff); } /// Same as stbtt_MakeCodepointBitmap, but you can specify a subpixel /// shift for the character. void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, ubyte *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint) nothrow @nogc { stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint)); } /// Allocates a large-enough single-channel 8bpp bitmap and renders the /// specified character/glyph at the specified scale into it, with /// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). /// *width & *height are filled out with the width & height of the bitmap, /// which is stored left-to-right, top-to-bottom. /// /// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap ubyte *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff) nothrow @nogc { return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff); } /// The same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap /// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap /// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the /// width and height and positioning info for it first. void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, ubyte *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint) nothrow @nogc { stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint); } // // @nogc sorting. // /// Must return -1 if a < b /// 0 if a == b /// 1 if a > b alias nogcComparisonFunction(T) = int delegate(in T a, in T b) nothrow @nogc; /// @nogc quicksort /// From the excellent: http://codereview.stackexchange.com/a/77788 void quicksort(T)(T[] array, nogcComparisonFunction!T comparison) nothrow @nogc { if (array.length < 2) return; static void swapElem(ref T lhs, ref T rhs) { T tmp = lhs; lhs = rhs; rhs = tmp; } int partition(T* arr, int left, int right) nothrow @nogc { immutable int mid = left + (right - left) / 2; T pivot = arr[mid]; // move the mid point value to the front. swapElem(arr[mid],arr[left]); int i = left + 1; int j = right; while (i <= j) { while(i <= j && comparison(arr[i], pivot) <= 0 ) i++; while(i <= j && comparison(arr[j], pivot) > 0) j--; if (i < j) swapElem(arr[i], arr[j]); } swapElem(arr[i - 1], arr[left]); return i - 1; } void doQsort(T* array, int left, int right) nothrow @nogc { if (left >= right) return; int part = partition(array, left, right); doQsort(array, left, part - 1); doQsort(array, part + 1, right); } doQsort(array.ptr, 0, cast(int)(array.length) - 1); } unittest { int[] testData = [110, 5, 10, 3, 22, 100, 1, 23]; quicksort!int(testData, (a, b) => (a - b)); assert(testData == [1, 3, 5, 10, 22, 23, 100, 110]); }
D
/* Provides light-weight formatting utilities for pretty-printing on assertion failures */ module core.internal.dassert; /// Allows customized assert error messages string _d_assert_fail(string comp, A, B)(auto ref const A a, auto ref const B b) { /* The program will be terminated after the assertion error message has been printed and its not considered part of the "main" program. Also, catching an AssertError is Undefined Behavior Hence, we can fake purity and @nogc-ness here. */ auto valA = miniFormatFakeAttributes(a); auto valB = miniFormatFakeAttributes(b); enum token = invertCompToken(comp); const totalLen = valA.length + token.length + valB.length + 2; char[] buffer = cast(char[]) pureAlloc(totalLen)[0 .. totalLen]; // @nogc-concat of "<valA> <comp> <valB>" auto n = valA.length; buffer[0 .. n] = valA; buffer[n++] = ' '; buffer[n .. n + token.length] = token; n += token.length; buffer[n++] = ' '; buffer[n .. n + valB.length] = valB; return (() @trusted => cast(string) buffer)(); } // Yields the appropriate printf format token for a type T // Indended to be used by miniFormat private template getPrintfFormat(T) { static if (is(T == long)) { enum getPrintfFormat = "%lld"; } else static if (is(T == ulong)) { enum getPrintfFormat = "%llu"; } else static if (__traits(isIntegral, T)) { static if (__traits(isUnsigned, T)) { enum getPrintfFormat = "%u"; } else { enum getPrintfFormat = "%d"; } } else { static assert(0, "Unknown format"); } } /** Minimalistic formatting for use in _d_assert_fail to keep the compilation overhead small and avoid the use of Phobos. */ private string miniFormat(V)(const ref V v) { import core.stdc.stdio : sprintf; import core.stdc.string : strlen; static if (is(V : bool)) { return v ? "true" : "false"; } else static if (__traits(isIntegral, V)) { enum printfFormat = getPrintfFormat!V; char[20] val; const len = sprintf(&val[0], printfFormat, v); return val.idup[0 .. len]; } else static if (__traits(isFloating, V)) { char[60] val; const len = sprintf(&val[0], "%g", v); return val.idup[0 .. len]; } // special-handling for void-arrays else static if (is(V == typeof(null))) { return "`null`"; } else static if (__traits(compiles, { string s = v.toString(); })) { return v.toString(); } // Non-const toString(), e.g. classes inheriting from Object else static if (__traits(compiles, { string s = V.init.toString(); })) { return (cast() v).toString(); } else static if (is(V : U[], U)) { import core.internal.traits: Unqual; alias E = Unqual!U; // special-handling for void-arrays static if (is(E == void)) { const bytes = cast(byte[]) v; return miniFormat(bytes); } // anything string-like else static if (is(E == char) || is(E == dchar) || is(E == wchar)) { const s = `"` ~ v ~ `"`; // v could be a char[], dchar[] or wchar[] static if (is(typeof(s) : const char[])) return cast(immutable) s; else { import core.internal.utf: toUTF8; return toUTF8(s); } } else { string msg = "["; foreach (i, ref el; v) { if (i > 0) msg ~= ", "; // don't fully print big arrays if (i >= 30) { msg ~= "..."; break; } msg ~= miniFormat(el); } msg ~= "]"; return msg; } } else static if (is(V : Val[K], K, Val)) { size_t i; string msg = "["; foreach (k, ref val; v) { if (i++ > 0) msg ~= ", "; // don't fully print big AAs if (i >= 30) { msg ~= "..."; break; } msg ~= miniFormat(k) ~ ": " ~ miniFormat(val); } msg ~= "]"; return msg; } else static if (is(V == struct)) { string msg = V.stringof ~ "("; foreach (idx, mem; v.tupleof) { if (idx > 0) msg ~= ", "; msg ~= miniFormat(v.tupleof[idx]); } msg ~= ")"; return msg; } else { return V.stringof; } } // Inverts a comparison token for use in _d_assert_fail private string invertCompToken(string comp) { switch (comp) { case "==": return "!="; case "!=": return "=="; case "<": return ">="; case "<=": return ">"; case ">": return "<="; case ">=": return "<"; case "is": return "!is"; case "!is": return "is"; case "in": return "!in"; case "!in": return "in"; default: assert(0, "Invalid comparison operator: " ~ comp); } } private auto assumeFakeAttributes(T)(T t) @trusted { import core.internal.traits : Parameters, ReturnType; alias RT = ReturnType!T; alias P = Parameters!T; alias type = RT function(P) nothrow @nogc @safe pure; return cast(type) t; } private string miniFormatFakeAttributes(T)(const ref T t) { alias miniT = miniFormat!T; return assumeFakeAttributes(&miniT)(t); } private auto pureAlloc(size_t t) { static auto alloc(size_t len) { return new ubyte[len]; } return assumeFakeAttributes(&alloc)(t); }
D
/** * Windows API header module * * Translated from MinGW Windows headers * * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0) * Source: $(DRUNTIMESRC src/core/sys/windows/_lmaudit.d) */ // COMMENT: This file may be deprecated. module core.sys.windows.lmaudit; version (Windows): private import core.sys.windows.lmcons, core.sys.windows.windef; enum LOGFLAGS_FORWARD = 0; enum LOGFLAGS_BACKWARD = 1; enum LOGFLAGS_SEEK = 2; enum ACTION_LOCKOUT = 0; enum ACTION_ADMINUNLOCK = 1; enum AE_GUEST=0; enum AE_USER=1; enum AE_ADMIN=2; enum AE_NORMAL=0; enum AE_USERLIMIT=0; enum AE_GENERAL=0; enum AE_ERROR=1; enum AE_SESSDIS=1; enum AE_BADPW=1; enum AE_AUTODIS=2; enum AE_UNSHARE=2; enum AE_ADMINPRIVREQD=2; enum AE_ADMINDIS=3; enum AE_NOACCESSPERM=3; enum AE_ACCRESTRICT=4; enum AE_NORMAL_CLOSE=0; enum AE_SES_CLOSE=1; enum AE_ADMIN_CLOSE=2; enum AE_LIM_UNKNOWN=0; enum AE_LIM_LOGONHOURS=1; enum AE_LIM_EXPIRED=2; enum AE_LIM_INVAL_WKSTA=3; enum AE_LIM_DISABLED=4; enum AE_LIM_DELETED=5; enum AE_MOD=0; enum AE_DELETE=1; enum AE_ADD=2; enum AE_UAS_USER = 0; enum AE_UAS_GROUP = 1; enum AE_UAS_MODALS = 2; enum SVAUD_SERVICE = 1; enum SVAUD_GOODSESSLOGON = 6; enum SVAUD_BADSESSLOGON = 24; enum SVAUD_SESSLOGON = SVAUD_GOODSESSLOGON|SVAUD_BADSESSLOGON; enum SVAUD_GOODNETLOGON = 96; enum SVAUD_BADNETLOGON = 384; enum SVAUD_NETLOGON = SVAUD_GOODNETLOGON|SVAUD_BADNETLOGON; enum SVAUD_LOGON = SVAUD_NETLOGON|SVAUD_SESSLOGON; enum SVAUD_GOODUSE = 0x600; enum SVAUD_BADUSE = 0x1800; enum SVAUD_USE = SVAUD_GOODUSE|SVAUD_BADUSE; enum SVAUD_USERLIST = 8192; enum SVAUD_PERMISSIONS = 16384; enum SVAUD_RESOURCE = 32768; enum SVAUD_LOGONLIM = 65536; enum AA_AUDIT_ALL=1; enum AA_A_OWNER=4; enum AA_CLOSE=8; enum AA_S_OPEN=16; enum AA_S_WRITE=32; enum AA_S_CREATE=32; enum AA_S_DELETE=64; enum AA_S_ACL=128; enum AA_S_ALL=253; enum AA_F_OPEN=256; enum AA_F_WRITE=512; enum AA_F_CREATE=512; enum AA_F_DELETE=1024; enum AA_F_ACL=2048; enum AA_F_ALL = AA_F_OPEN|AA_F_WRITE|AA_F_DELETE|AA_F_ACL; enum AA_A_OPEN=2048; enum AA_A_WRITE=4096; enum AA_A_CREATE=8192; enum AA_A_DELETE=16384; enum AA_A_ACL=32768; enum AA_A_ALL = AA_F_OPEN|AA_F_WRITE|AA_F_DELETE|AA_F_ACL; struct AUDIT_ENTRY{ DWORD ae_len; DWORD ae_reserved; DWORD ae_time; DWORD ae_type; DWORD ae_data_offset; DWORD ae_data_size; } alias AUDIT_ENTRY* PAUDIT_ENTRY, LPAUDIT_ENTRY; struct HLOG{ DWORD time; DWORD last_flags; DWORD offset; DWORD rec_offset; } alias HLOG* PHLOG, LPHLOG; struct AE_SRVSTATUS{ DWORD ae_sv_status; } alias AE_SRVSTATUS* PAE_SRVSTATUS, LPAE_SRVSTATUS; struct AE_SESSLOGON{ DWORD ae_so_compname; DWORD ae_so_username; DWORD ae_so_privilege; } alias AE_SESSLOGON* PAE_SESSLOGON, LPAE_SESSLOGON; struct AE_SESSLOGOFF{ DWORD ae_sf_compname; DWORD ae_sf_username; DWORD ae_sf_reason; } alias AE_SESSLOGOFF* PAE_SESSLOGOFF, LPAE_SESSLOGOFF; struct AE_SESSPWERR{ DWORD ae_sp_compname; DWORD ae_sp_username; } alias AE_SESSPWERR* PAE_SESSPWERR, LPAE_SESSPWERR; struct AE_CONNSTART{ DWORD ae_ct_compname; DWORD ae_ct_username; DWORD ae_ct_netname; DWORD ae_ct_connid; } alias AE_CONNSTART* PAE_CONNSTART, LPAE_CONNSTART; struct AE_CONNSTOP{ DWORD ae_cp_compname; DWORD ae_cp_username; DWORD ae_cp_netname; DWORD ae_cp_connid; DWORD ae_cp_reason; } alias AE_CONNSTOP* PAE_CONNSTOP, LPAE_CONNSTOP; struct AE_CONNREJ{ DWORD ae_cr_compname; DWORD ae_cr_username; DWORD ae_cr_netname; DWORD ae_cr_reason; } alias AE_CONNREJ* PAE_CONNREJ, LPAE_CONNREJ; struct AE_RESACCESS{ DWORD ae_ra_compname; DWORD ae_ra_username; DWORD ae_ra_resname; DWORD ae_ra_operation; DWORD ae_ra_returncode; DWORD ae_ra_restype; DWORD ae_ra_fileid; } alias AE_RESACCESS* PAE_RESACCESS, LPAE_RESACCESS; struct AE_RESACCESSREJ{ DWORD ae_rr_compname; DWORD ae_rr_username; DWORD ae_rr_resname; DWORD ae_rr_operation; } alias AE_RESACCESSREJ* PAE_RESACCESSREJ, LPAE_RESACCESSREJ; struct AE_CLOSEFILE{ DWORD ae_cf_compname; DWORD ae_cf_username; DWORD ae_cf_resname; DWORD ae_cf_fileid; DWORD ae_cf_duration; DWORD ae_cf_reason; } alias AE_CLOSEFILE* PAE_CLOSEFILE, LPAE_CLOSEFILE; struct AE_SERVICESTAT{ DWORD ae_ss_compname; DWORD ae_ss_username; DWORD ae_ss_svcname; DWORD ae_ss_status; DWORD ae_ss_code; DWORD ae_ss_text; DWORD ae_ss_returnval; } alias AE_SERVICESTAT* PAE_SERVICESTAT, LPAE_SERVICESTAT; struct AE_ACLMOD{ DWORD ae_am_compname; DWORD ae_am_username; DWORD ae_am_resname; DWORD ae_am_action; DWORD ae_am_datalen; } alias AE_ACLMOD* PAE_ACLMOD, LPAE_ACLMOD; struct AE_UASMOD{ DWORD ae_um_compname; DWORD ae_um_username; DWORD ae_um_resname; DWORD ae_um_rectype; DWORD ae_um_action; DWORD ae_um_datalen; } alias AE_UASMOD* PAE_UASMOD, LPAE_UASMOD; struct AE_NETLOGON{ DWORD ae_no_compname; DWORD ae_no_username; DWORD ae_no_privilege; DWORD ae_no_authflags; } alias AE_NETLOGON* PAE_NETLOGON, LPAE_NETLOGON; struct AE_NETLOGOFF{ DWORD ae_nf_compname; DWORD ae_nf_username; DWORD ae_nf_reserved1; DWORD ae_nf_reserved2; } alias AE_NETLOGOFF* PAE_NETLOGOFF, LPAE_NETLOGOFF; struct AE_ACCLIM{ DWORD ae_al_compname; DWORD ae_al_username; DWORD ae_al_resname; DWORD ae_al_limit; } alias AE_ACCLIM* PAE_ACCLIM, LPAE_ACCLIM; struct AE_LOCKOUT{ DWORD ae_lk_compname; DWORD ae_lk_username; DWORD ae_lk_action; DWORD ae_lk_bad_pw_count; } alias AE_LOCKOUT* PAE_LOCKOUT, LPAE_LOCKOUT; struct AE_GENERIC{ DWORD ae_ge_msgfile; DWORD ae_ge_msgnum; DWORD ae_ge_params; DWORD ae_ge_param1; DWORD ae_ge_param2; DWORD ae_ge_param3; DWORD ae_ge_param4; DWORD ae_ge_param5; DWORD ae_ge_param6; DWORD ae_ge_param7; DWORD ae_ge_param8; DWORD ae_ge_param9; } alias AE_GENERIC* PAE_GENERIC, LPAE_GENERIC; extern (Windows) { deprecated { NET_API_STATUS NetAuditClear(LPCWSTR,LPCWSTR,LPCWSTR); NET_API_STATUS NetAuditRead(LPTSTR,LPTSTR,LPHLOG,DWORD,PDWORD,DWORD,DWORD,PBYTE*,DWORD,PDWORD,PDWORD); NET_API_STATUS NetAuditWrite(DWORD,PBYTE,DWORD,LPTSTR,PBYTE); } } /+ /* MinGW: These conflict with struct typedefs, why? */ enum AE_SRVSTATUS=0; enum AE_SESSLOGON=1; enum AE_SESSLOGOFF=2; enum AE_SESSPWERR=3; enum AE_CONNSTART=4; enum AE_CONNSTOP=5; enum AE_CONNREJ=6; enum AE_RESACCESS=7; enum AE_RESACCESSREJ=8; enum AE_CLOSEFILE=9; enum AE_SERVICESTAT=11; enum AE_ACLMOD=12; enum AE_UASMOD=13; enum AE_NETLOGON=14; enum AE_NETLOGOFF=15; enum AE_NETLOGDENIED=16; enum AE_ACCLIMITEXCD=17; enum AE_RESACCESS2=18; enum AE_ACLMODFAIL=19; enum AE_LOCKOUT=20; enum AE_GENERIC_TYPE=21; enum AE_SRVSTART=0; enum AE_SRVPAUSED=1; enum AE_SRVCONT=2; enum AE_SRVSTOP=3; +/
D
/** * 64 bit Kernel Startup Code * * Copyright: 2008 The Neptune Project */ module kernel.boot.startup; import modinit; import std.stdio; import std.string; import std.context; import util.spec.elf64; import kernel.core.env; import kernel.core.arch; import kernel.core.mem; import kernel.core.interrupt; import kernel.core.event; import util.arch.cpu; import util.arch.paging; import kernel.dev.screen; import kernel.dev.kb; import kernel.dev.timer; import kernel.task.scheduler; import kernel.task.process; extern(C) void _startup(ulong loader) { // Set the global loader data pointer loaderData = cast(LoaderData*)ptov(loader); // Set up basic runtime and hardware structures memory_setup(); root = new EventDomain(); // Initialize the screen screen = new Screen(SCREEN_MEM); screen.clear(); stdout = screen; arch_setup(); root.addHandler("int.pagefault", new FunctionEventHandler(&pagefault_handler)); // Turn on interrupts to catch page faults, GP faults, etc... CPU.enableInterrupts(); CPU.apic.setTimer(127, true, 10); // Run module constructors and unit tests writeln("Running module constructors"); _moduleCtor(); debug { writeln("Running module unit tests"); _moduleUnitTests(); } // Initialize the keyboard device kb.init(33); // Initialize the processor allocator and add the current processor to its pool scheduler = new Scheduler(); // Initialize the timer device timer = new Timer(); Elf64Header* elf; Elf64Header* exec; Elf64Header* lib; // Load modules passed from the loader as processes foreach(i, mod; loaderData.modules[0..loaderData.numModules]) { writefln("module: %s", ctodstr(mod.name)); elf = cast(Elf64Header*)mod.base; Process p = new Process(i, elf); scheduler.add(p); } // Idle until a task switch is performed for(;;){} } extern(C) void test_syscall() { writeln("syscall!"); for(size_t i=0; i<10000000; i++) { asm{"pause";} } } void pagefault_handler(char[] domain, EventSource source) { auto s = cast(InterruptEventSource)source; ulong addr = CPU.cr2; if(addr >= LINEAR_MEM.base && addr < LINEAR_MEM.top) { // Demand page memory in the linear-mapped region Page* p = (*CPU.pagetable)[addr]; p.address = addr - LINEAR_MEM.base; p.writable = true; p.present = true; p.user = false; } else if(addr >= m_base() && addr < m_limit()) { // Demand page the kernel heap Page* p = (*CPU.pagetable)[addr]; p.address = p_alloc(); p.writable = true; p.present = true; p.user = false; } else if(addr >= scheduler.current.thread.stack.base && addr < scheduler.current.thread.stack.top) { Page* stack_page = (*CPU.pagetable)[addr]; stack_page.address = p_alloc(); stack_page.writable = true; stack_page.present = true; stack_page.user = true; } else if(addr >= scheduler.current.thread.kernel_stack.base && addr < scheduler.current.thread.kernel_stack.top) { Page* p = (*CPU.pagetable)[addr]; p.address = p_alloc(); p.writable = true; p.present = true; p.user = true; } else { writefln("Unhandled page fault at address %p", addr); writefln("Error code %#x", s.context.error); writefln("%%rip: %p", s.context.rip); version(unwind) { writefln("%p: %s", s.context.rip, getSymbol(s.context.rip)); stackUnwind(cast(ulong*)s.context.rsp, cast(ulong*)s.context.rbp); } for(;;){} } }
D