code
stringlengths
3
10M
language
stringclasses
31 values
module more.io; import core.memory : GC; import std.format : format; import std.algorithm : copy; // NOTE: this is a c std library call, but D doesn't seem to have it right now inout(char)* strchrnul(inout(char)* str, char c) { for(; *str != c && *str != '\0';str++) { } return str; } alias ExpandDelegate = void* delegate(void* buffer, size_t preserveSize, size_t newSize); alias ExpandFunction = void* function(void* buffer, size_t preserveSize, size_t newSize); void* gcExpander(void* gcBuffer, size_t preserveSize, size_t newSize) { size_t result = GC.extend(gcBuffer, newSize, newSize); if(result != 0) { //writefln("[DEBUG] gcExtender (extended gc buffer to %s)", newSize); return gcBuffer; } auto newBuffer = GC.malloc(newSize); if(newBuffer == null) { assert(0, "out of memory"); } if(preserveSize > 0) { newBuffer[0..preserveSize] = gcBuffer[0..preserveSize]; } GC.free(gcBuffer); // writefln("[DEBUG] gcExtender allocated new buffer"); return newBuffer; } ExpandableGCBuffer!T expandable(T)(T[] buffer) { return ExpandableGCBuffer!T(buffer); } struct ExpandableGCBuffer(T) { T[] buffer; this(T[] buffer) { this.buffer = buffer; } void* expand(void* gcBuffer, size_t preserveSize, size_t newSize) { assert(gcBuffer == buffer.ptr); this.buffer = (cast(T*)gcExpander(gcBuffer, preserveSize, newSize))[0..newSize/T.sizeof]; return cast(ubyte*)this.buffer.ptr; } } /** Returns one or more lines of text as a character slice. All lines returned MUST be complete, it MUST not return partial lines. The preceding character after the returned slice must be a valid part of the array and must be set to '\0'. This allows code to determine the end of the lines without needing to pass around the length of all the slice. The template parameter $(D T) is used to define the return type, i.e. char => function will return char[] const(char) => function will return const(char)[] immutable(char) => function will return immutable(char)[] or string */ template LinesReaderDelegate(T) { alias LinesReaderDelegate = T[] delegate(); } struct LinesReaderDelegateRange(CharType) { LinesReaderDelegate!CharType linesReaderDelegate; CharType[] nextLine; this(LinesReaderDelegate!CharType linesReaderDelegate) in { assert(linesReaderDelegate); } body { this.linesReaderDelegate = linesReaderDelegate; popFront(); } @property bool empty() { return nextLine.ptr == null; } @property CharType[] front() { return nextLine; } void popFront() { auto nextPtr = nextLine.ptr; if(nextPtr != null) { nextPtr += nextLine.length; if(*nextPtr == '\0') { nextPtr = null; } } if(nextPtr == null) { auto chunk = linesReaderDelegate(); if(chunk.length == 0) { nextLine = null; // empty return; } assert(chunk.ptr[chunk.length] == '\0', "this LinesReaderDelegate returned an chunk that was not NULL terminated"); nextPtr = chunk.ptr; } auto endOfLine = strchrnul(nextPtr, '\n'); if(*endOfLine == '\n') { endOfLine++; } nextLine = nextPtr[0..endOfLine-nextPtr]; } } alias ReaderDelegate = size_t delegate(char[]); alias DelegateLinesReader = LinesReaderTemplate!(ReaderDelegate, ExpandDelegate); // LinesReader provides an interface to read data that // is returned in chunks of lines. It does not return // partial lines. It also make sure that the data // returned is ALWAYS terminated by a NULL character. // // The reason for this is that this interface is greate // for parsers, and parsers can be written more efficiently // when they are checking for a NULL character rather than // keeping an extra variable that indicates the end of the text. // // Note: since some IO streams may have NULL has a valid character, // it might make sense to make this terminating charater configurable // or even optional // struct LinesReaderTemplate(Reader,Expander) { // TODO: make this a delegate (or better yet a template parameter) // if a big project wants to prevent template bloat, they can // make the template parameter a delegate. Reader reader; char[] buffer; const Expander expander; char[] leftOver; char leftOverSaveFirstChar; // Need to save because it will be overwritten with '\0' temporarily const size_t sizeToTriggerResize; // when the free size of the buffer reaches this value, a resize will be triggered this(Reader reader, char[] buffer, Expander expander, size_t sizeToTriggerResize) { this.reader = reader; this.buffer = buffer; this.expander = expander; this.sizeToTriggerResize = sizeToTriggerResize; } private void resize(size_t currentDataLength) { if(expander == null) { if(currentDataLength >= (buffer.length-1)) { throw new Exception(format("the file contains a line that cannot fit in the given buffer (%s bytes) and no resize function was provided", buffer.length)); } } else { size_t newSize; if(buffer.length < sizeToTriggerResize) { newSize = buffer.length + sizeToTriggerResize; } else { newSize = buffer.length * 2; } //writefln("[DEBUG] expanding read buffer from %s to %s (currentDataLength=%s)", // buffer.length, newSize, currentDataLength); buffer = (cast(char*)(expander(buffer.ptr, currentDataLength, newSize)))[0..newSize]; } } char[] readLines() { //writeln("[DEBUG] readLines: enter"); //scope(exit) writeln("[DEBUG] readLines: exit"); auto currentDataLength = leftOver.length; // Shift left over data to start of buffer to prepare for next read if(currentDataLength) { leftOver[0] = leftOverSaveFirstChar; // TODO: check performance of copy vs memmove copy(leftOver, buffer[0..currentDataLength]); leftOver = null; } // Expand buffer if too small if(currentDataLength + sizeToTriggerResize > (buffer.length-1)) { resize(currentDataLength); } while(true) { // Read the next chunk of lines size_t readLength = (buffer.length-1) - currentDataLength; auto readResult = reader(buffer[currentDataLength..$-1]); //writefln("[DEBUG] read %s bytes", readResult); auto chunkSize = currentDataLength + readResult; if(readResult != readLength) { buffer[chunkSize] = '\0'; return buffer[0..chunkSize]; } // search for the end of the last line for(size_t i = chunkSize - 1; ; i--) { if(buffer[i] == '\n') { leftOver = buffer[i + 1..chunkSize]; leftOverSaveFirstChar = buffer[i + 1]; buffer[i + 1] = '\0'; return buffer[0..i+1]; } // the line must be too long, need to resize the buffer if(i == 0) { currentDataLength = chunkSize; resize(chunkSize); break; } } } } auto byLine() { return LinesReaderDelegateRange!char(&readLines); } } // implements the linesReader interface but for a single string struct StringReader(CharType) { CharType[] data; CharType[] readLines() { string currentData = this.data; this.data = null; return currentData; } } StringReader!CharType stringReader(CharType)(CharType[] str) { return StringReader!CharType(str); }
D
/** * This module contains the implementation of the C++ header generation available through * the command line switch -Hc. * * 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/dtohd, _dtoh.d) * Documentation: https://dlang.org/phobos/dmd_dtoh.html * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/dtoh.d */ module dmd.dtoh; import core.stdc.stdio; import core.stdc.string; import core.stdc.ctype; import dmd.astcodegen; import dmd.arraytypes; import dmd.dsymbol; import dmd.errors; import dmd.globals; import dmd.identifier; import dmd.root.filename; import dmd.visitor; import dmd.tokens; import dmd.root.outbuffer; import dmd.utils; //debug = Debug_DtoH; private struct DMDType { __gshared Identifier c_long; __gshared Identifier c_ulong; __gshared Identifier c_longlong; __gshared Identifier c_ulonglong; __gshared Identifier c_long_double; __gshared Identifier c_wchar_t; static void _init() { c_long = Identifier.idPool("__c_long"); c_ulong = Identifier.idPool("__c_ulong"); c_longlong = Identifier.idPool("__c_longlong"); c_ulonglong = Identifier.idPool("__c_ulonglong"); c_long_double = Identifier.idPool("__c_long_double"); c_wchar_t = Identifier.idPool("__c_wchar_t"); } } private void initialize() { __gshared bool initialized; if (!initialized) { initialized = true; DMDType._init(); } } void hashIf(ref OutBuffer buf, string content) { buf.writestring("#if "); buf.writestringln(content); } void hashElIf(ref OutBuffer buf, string content) { buf.writestring("#elif "); buf.writestringln(content); } void hashEndIf(ref OutBuffer buf) { buf.writestringln("#endif"); } void hashDefine(ref OutBuffer buf, string content) { buf.writestring("# define "); buf.writestringln(content); } void hashInclude(ref OutBuffer buf, string content) { buf.writestring("#include "); buf.writestringln(content); } extern(C++) void genCppHdrFiles(ref Modules ms) { initialize(); OutBuffer fwd; OutBuffer check; OutBuffer done; OutBuffer decl; // enable indent by spaces on buffers fwd.doindent = true; fwd.spaces = true; decl.doindent = true; decl.spaces = true; check.doindent = true; check.spaces = true; scope v = new ToCppBuffer(&check, &fwd, &done, &decl); OutBuffer buf; buf.doindent = true; buf.spaces = true; foreach (m; ms) m.accept(v); if (global.params.doCxxHdrGeneration == CxxHeaderMode.verbose) buf.printf("// Automatically generated by %s Compiler v%d", global.vendor.ptr, global.versionNumber()); else buf.printf("// Automatically generated by %s Compiler", global.vendor.ptr); buf.writenl(); buf.writenl(); buf.writestringln("#pragma once"); buf.writenl(); hashInclude(buf, "<assert.h>"); hashInclude(buf, "<stddef.h>"); hashInclude(buf, "<stdint.h>"); hashInclude(buf, "<math.h>"); // buf.writestring(buf, "#include <stdio.h>\n"); // buf.writestring("#include <string.h>\n"); // Emit array compatibility because extern(C++) types may have slices // as members (as opposed to function parameters) buf.writestring(` #ifdef CUSTOM_D_ARRAY_TYPE #define _d_dynamicArray CUSTOM_D_ARRAY_TYPE #else /// Represents a D [] array template<typename T> struct _d_dynamicArray { size_t length; T *ptr; _d_dynamicArray() : length(0), ptr(NULL) { } _d_dynamicArray(size_t length_in, T *ptr_in) : length(length_in), ptr(ptr_in) { } T& operator[](const size_t idx) { assert(idx < length); return ptr[idx]; } const T& operator[](const size_t idx) const { assert(idx < length); return ptr[idx]; } }; #endif `); if (v.hasReal) { hashIf(buf, "!defined(_d_real)"); { hashDefine(buf, "_d_real long double"); } hashEndIf(buf); } buf.writenl(); // buf.writestringln("// fwd:"); buf.write(&fwd); if (fwd.length > 0) buf.writenl(); // buf.writestringln("// done:"); buf.write(&done); // buf.writestringln("// decl:"); buf.write(&decl); debug (Debug_DtoH) { // buf.writestringln("// check:"); buf.writestring(` #if OFFSETS template <class T> size_t getSlotNumber(int dummy, ...) { T c; va_list ap; va_start(ap, dummy); void *f = va_arg(ap, void*); for (size_t i = 0; ; i++) { if ( (*(void***)&c)[i] == f) return i; } va_end(ap); } void testOffsets() { `); buf.write(&check); buf.writestring(` } #endif `); } if (global.params.cxxhdrname is null) { // Write to stdout; assume it succeeds size_t n = fwrite(buf[].ptr, 1, buf.length, stdout); assert(n == buf.length); // keep gcc happy about return values } else { const(char)[] name = FileName.combine(global.params.cxxhdrdir, global.params.cxxhdrname); writeFile(Loc.initial, name, buf[]); } } /**************************************************** */ extern(C++) final class ToCppBuffer : Visitor { alias visit = Visitor.visit; public: enum EnumKind { Int, Numeric, String, Enum, Other } alias AST = ASTCodegen; bool[void*] visited; bool[void*] forwarded; OutBuffer* fwdbuf; OutBuffer* checkbuf; OutBuffer* donebuf; OutBuffer* buf; AST.AggregateDeclaration adparent; AST.TemplateDeclaration tdparent; Identifier ident; LINK linkage = LINK.d; bool forwardedAA; AST.Type* origType; /// Last written visibility level AST.Visibility.Kind currentVisibility; AST.STC storageClass; /// Currently applicable storage classes int ignoredCounter; /// How many symbols were ignored bool hasReal; const bool printIgnored; this(OutBuffer* checkbuf, OutBuffer* fwdbuf, OutBuffer* donebuf, OutBuffer* buf) { this.checkbuf = checkbuf; this.fwdbuf = fwdbuf; this.donebuf = donebuf; this.buf = buf; this.printIgnored = global.params.doCxxHdrGeneration == CxxHeaderMode.verbose; } /// Visit `dsym` with `buf` while temporarily clearing **parent fields private void visitAsRoot(AST.Dsymbol dsym, OutBuffer* buf) { const stcStash = this.storageClass; auto adStash = this.adparent; auto tdStash = this.tdparent; auto bufStash = this.buf; auto countStash = this.ignoredCounter; this.storageClass = AST.STC.undefined_; this.adparent = null; this.tdparent = null; this.buf = buf; dsym.accept(this); this.storageClass = stcStash; this.adparent = adStash; this.tdparent = tdStash; this.buf = bufStash; this.ignoredCounter = countStash; } private EnumKind getEnumKind(AST.Type type) { if (type) switch (type.ty) { case AST.Tint32: return EnumKind.Int; case AST.Tbool, AST.Tchar, AST.Twchar, AST.Tdchar, AST.Tint8, AST.Tuns8, AST.Tint16, AST.Tuns16, AST.Tuns32, AST.Tint64, AST.Tuns64: return EnumKind.Numeric; case AST.Tarray: if (type.isString()) return EnumKind.String; break; case AST.Tenum: return EnumKind.Enum; default: break; } return EnumKind.Other; } private AST.Type determineEnumType(AST.Type type) { if (auto arr = type.isTypeDArray()) { switch (arr.next.ty) { case AST.Tchar: return AST.Type.tchar.constOf.pointerTo; case AST.Twchar: return AST.Type.twchar.constOf.pointerTo; case AST.Tdchar: return AST.Type.tdchar.constOf.pointerTo; default: break; } } return type; } void writeDeclEnd() { buf.writestringln(";"); if (!adparent) buf.writenl(); } /// Writes the corresponding access specifier if necessary private void writeProtection(const AST.Visibility.Kind kind) { // Don't write visibility for global declarations if (!adparent) return; string token; switch(kind) with(AST.Visibility.Kind) { case none, private_: if (this.currentVisibility == AST.Visibility.Kind.private_) return; this.currentVisibility = AST.Visibility.Kind.private_; token = "private:"; break; case package_, protected_: if (this.currentVisibility == AST.Visibility.Kind.protected_) return; this.currentVisibility = AST.Visibility.Kind.protected_; token = "protected:"; break; case undefined, public_, export_: if (this.currentVisibility == AST.Visibility.Kind.public_) return; this.currentVisibility = AST.Visibility.Kind.public_; token = "public:"; break; default: printf("Unexpected visibility: %d!\n", kind); assert(0); } buf.level--; buf.writestringln(token); buf.level++; } /** * Writes an identifier into `buf` and checks for reserved identifiers. The * parameter `canFix` determines how this function handles C++ keywords: * * `false` => Raise a warning and print the identifier as-is * `true` => Append an underscore to the identifier * * Params: * s = the symbol denoting the identifier * canFixup = whether the identifier may be changed without affecting * binary compatibility */ private void writeIdentifier(const AST.Dsymbol s, const bool canFix = false) { writeIdentifier(s.ident, s.loc, s.kind(), canFix); } /** Overload of `writeIdentifier` used for all AST nodes not descending from Dsymbol **/ private void writeIdentifier(const Identifier ident, const Loc loc, const char* kind, const bool canFix = false) { bool needsFix; void warnCxxCompat(const(char)* reason) { if (canFix) { needsFix = true; return; } static bool warned = false; warning(loc, "%s `%s` is a %s", kind, ident.toChars(), reason); if (!warned) { warningSupplemental(loc, "The generated C++ header will contain " ~ "identifiers that are keywords in C++"); warned = true; } } if (global.params.warnings != DiagnosticReporting.off || canFix) { // Warn about identifiers that are keywords in C++. switch (ident.toString()) { // C++ operators case "and": case "and_eq": case "bitand": case "bitor": case "compl": case "not": case "not_eq": case "or": case "or_eq": case "xor": case "xor_eq": warnCxxCompat("special operator in C++"); break; // C++ keywords case "const_cast": case "delete": case "dynamic_cast": case "explicit": case "friend": case "inline": case "mutable": case "namespace": case "operator": case "register": case "reinterpret_cast": case "signed": case "static_cast": case "typedef": case "typename": case "unsigned": case "using": case "virtual": case "volatile": warnCxxCompat("keyword in C++"); break; // C++11 keywords case "alignas": case "alignof": case "char16_t": case "char32_t": case "constexpr": case "decltype": case "noexcept": case "nullptr": case "static_assert": case "thread_local": if (global.params.cplusplus >= CppStdRevision.cpp11) warnCxxCompat("keyword in C++11"); break; // C++20 keywords case "char8_t": case "consteval": case "constinit": // Concepts-related keywords case "concept": case "requires": // Coroutines-related keywords case "co_await": case "co_yield": case "co_return": if (global.params.cplusplus >= CppStdRevision.cpp20) warnCxxCompat("keyword in C++20"); break; default: break; } } buf.writestring(ident.toString()); if (needsFix) buf.writeByte('_'); } override void visit(AST.Dsymbol s) { debug (Debug_DtoH) { printf("[AST.Dsymbol enter] %s\n", s.toChars()); import dmd.asttypename; printf("[AST.Dsymbol enter] %s\n", s.astTypeName().ptr); scope(exit) printf("[AST.Dsymbol exit] %s\n", s.toChars()); } } override void visit(AST.Import i) { debug (Debug_DtoH) { printf("[AST.Import enter] %s\n", i.toChars()); scope(exit) printf("[AST.Import exit] %s\n", i.toChars()); } } override void visit(AST.AttribDeclaration pd) { debug (Debug_DtoH) { printf("[AST.AttribDeclaration enter] %s\n", pd.toChars()); scope(exit) printf("[AST.AttribDeclaration exit] %s\n", pd.toChars()); } Dsymbols* decl = pd.include(null); if (!decl) return; foreach (s; *decl) { if (adparent || s.visible().kind >= AST.Visibility.Kind.public_) s.accept(this); } } override void visit(AST.StorageClassDeclaration scd) { debug (Debug_DtoH) { printf("[AST.StorageClassDeclaration enter] %s\n", scd.toChars()); scope(exit) printf("[AST.StorageClassDeclaration exit] %s\n", scd.toChars()); } const stcStash = this.storageClass; this.storageClass |= scd.stc; visit(cast(AST.AttribDeclaration) scd); this.storageClass = stcStash; } override void visit(AST.LinkDeclaration ld) { debug (Debug_DtoH) { printf("[AST.LinkDeclaration enter] %s\n", ld.toChars()); scope(exit) printf("[AST.LinkDeclaration exit] %s\n", ld.toChars()); } auto save = linkage; linkage = ld.linkage; visit(cast(AST.AttribDeclaration)ld); linkage = save; } override void visit(AST.CPPMangleDeclaration md) { const oldLinkage = this.linkage; this.linkage = LINK.cpp; visit(cast(AST.AttribDeclaration) md); this.linkage = oldLinkage; } override void visit(AST.Module m) { debug (Debug_DtoH) { printf("[AST.Module enter] %s\n", m.toChars()); scope(exit) printf("[AST.Module exit] %s\n", m.toChars()); } foreach (s; *m.members) { if (s.visible().kind < AST.Visibility.Kind.public_) continue; s.accept(this); } } override void visit(AST.FuncDeclaration fd) { debug (Debug_DtoH) { printf("[AST.FuncDeclaration enter] %s\n", fd.toChars()); scope(exit) printf("[AST.FuncDeclaration exit] %s\n", fd.toChars()); } if (cast(void*)fd in visited) return; // printf("FuncDeclaration %s %s\n", fd.toPrettyChars(), fd.type.toChars()); visited[cast(void*)fd] = true; // Note that tf might be null for templated (member) functions auto tf = cast(AST.TypeFunction)fd.type; if ((tf && tf.linkage != LINK.c && tf.linkage != LINK.cpp) || (!tf && fd.isPostBlitDeclaration())) { ignored("function %s because of linkage", fd.toPrettyChars()); // Virtual extern(D) functions require a dummy declaration to ensure proper // vtable layout - but omit redundant declarations - the slot was already // reserved in the base class if (fd.isVirtual() && fd.introducing) { // Hide placeholders because they are not ABI compatible writeProtection(AST.Visibility.Kind.private_); __gshared int counter; // Ensure unique names in all cases buf.printf("virtual void __vtable_slot_%u();", counter++); buf.writenl(); } return; } if (!adparent && !fd.fbody) { ignored("function %s because it is extern", fd.toPrettyChars()); return; } if (fd.visibility.kind == AST.Visibility.Kind.none || fd.visibility.kind == AST.Visibility.Kind.private_) { ignored("function %s because it is private", fd.toPrettyChars()); return; } writeProtection(fd.visibility.kind); if (tf && tf.linkage == LINK.c) buf.writestring("extern \"C\" "); else if (!adparent) buf.writestring("extern "); if (adparent && fd.isStatic()) buf.writestring("static "); else if (adparent && ( // Virtual functions in non-templated classes (fd.vtblIndex != -1 && !fd.isOverride()) || // Virtual functions in templated classes (fd.vtblIndex still -1) (tdparent && adparent.isClassDeclaration() && !(this.storageClass & AST.STC.final_ || fd.isFinal)))) buf.writestring("virtual "); if (adparent && !tdparent) { auto s = adparent.search(Loc.initial, fd.ident); auto cd = adparent.isClassDeclaration(); if (!(adparent.storage_class & AST.STC.abstract_) && !(cd && cd.isAbstract()) && s is fd && !fd.overnext) { const cn = adparent.ident.toChars(); const fn = fd.ident.toChars(); const vi = fd.vtblIndex; checkbuf.printf("assert(getSlotNumber <%s>(0, &%s::%s) == %d);", cn, cn, fn, vi); checkbuf.writenl(); } } if (adparent && fd.isDisabled && global.params.cplusplus < CppStdRevision.cpp11) writeProtection(AST.Visibility.Kind.private_); funcToBuffer(tf, fd); // FIXME: How to determine if fd is const without tf? if (adparent && tf && (tf.isConst() || tf.isImmutable())) { bool fdOverridesAreConst = true; foreach (fdv; fd.foverrides) { auto tfv = cast(AST.TypeFunction)fdv.type; if (!tfv.isConst() && !tfv.isImmutable()) { fdOverridesAreConst = false; break; } } buf.writestring(fdOverridesAreConst ? " const" : " /* const */"); } if (adparent && fd.isAbstract()) buf.writestring(" = 0"); if (adparent && fd.isDisabled && global.params.cplusplus >= CppStdRevision.cpp11) buf.writestring(" = delete"); buf.writestringln(";"); if (adparent && fd.isDisabled && global.params.cplusplus < CppStdRevision.cpp11) writeProtection(AST.Visibility.Kind.public_); if (!adparent) buf.writenl(); } override void visit(AST.UnitTestDeclaration utd) { debug (Debug_DtoH) { printf("[AST.UnitTestDeclaration enter] %s\n", utd.toChars()); scope(exit) printf("[AST.UnitTestDeclaration exit] %s\n", utd.toChars()); } } override void visit(AST.VarDeclaration vd) { debug (Debug_DtoH) { printf("[AST.VarDeclaration enter] %s\n", vd.toChars()); scope(exit) printf("[AST.VarDeclaration exit] %s\n", vd.toChars()); } if (cast(void*)vd in visited) return; visited[cast(void*)vd] = true; // Tuple field are expanded into multiple VarDeclarations // (we'll visit them later) if (vd.type && vd.type.isTypeTuple()) return; if (vd.type == AST.Type.tsize_t) origType = &vd.originalType; scope(exit) origType = null; if (vd.alignment != STRUCTALIGN_DEFAULT) { buf.printf("// Ignoring var %s alignment %u", vd.toChars(), vd.alignment); buf.writenl(); } if (vd.storage_class & AST.STC.manifest && vd._init && vd._init.isExpInitializer() && vd.type !is null) { if (linkage != LINK.c && linkage != LINK.cpp) { ignored("variable %s because of linkage", vd.toPrettyChars()); return; } AST.Type type = vd.type; EnumKind kind = getEnumKind(type); if (vd.visibility.kind == AST.Visibility.Kind.none || vd.visibility.kind == AST.Visibility.Kind.private_) { ignored("enum `%s` because it is `%s`.", vd.toPrettyChars(), AST.visibilityToChars(vd.visibility.kind)); return; } writeProtection(vd.visibility.kind); final switch (kind) { case EnumKind.Int, EnumKind.Numeric: // 'enum : type' is only available from C++-11 onwards. if (global.params.cplusplus < CppStdRevision.cpp11) goto case; buf.writestring("enum : "); determineEnumType(type).accept(this); buf.writestring(" { "); writeIdentifier(vd, true); buf.writestring(" = "); auto ie = AST.initializerToExpression(vd._init).isIntegerExp(); visitInteger(ie.toInteger(), type); buf.writestring(" };"); break; case EnumKind.String, EnumKind.Enum: buf.writestring("static "); auto target = determineEnumType(type); target.accept(this); buf.writestring(" const "); writeIdentifier(vd, true); buf.writestring(" = "); auto e = AST.initializerToExpression(vd._init); printExpressionFor(target, e); buf.writestring(";"); break; case EnumKind.Other: ignored("enum `%s` because type `%s` is currently not supported for enum constants.", vd.toPrettyChars(), type.toChars()); return; } buf.writenl(); buf.writenl(); return; } if (tdparent && vd.type && !vd.type.deco) { if (linkage != LINK.c && linkage != LINK.cpp) { ignored("variable %s because of linkage", vd.toPrettyChars()); return; } writeProtection(vd.visibility.kind); typeToBuffer(vd.type, vd, adparent && !(vd.storage_class & (AST.STC.static_ | AST.STC.gshared))); buf.writestringln(";"); return; } if (vd.storage_class & (AST.STC.static_ | AST.STC.extern_ | AST.STC.tls | AST.STC.gshared) || vd.parent && vd.parent.isModule()) { if (vd.linkage != LINK.c && vd.linkage != LINK.cpp) { ignored("variable %s because of linkage", vd.toPrettyChars()); return; } if (vd.storage_class & AST.STC.tls) { ignored("variable %s because of thread-local storage", vd.toPrettyChars()); return; } writeProtection(vd.visibility.kind); if (vd.linkage == LINK.c) buf.writestring("extern \"C\" "); else if (!adparent) buf.writestring("extern "); if (adparent) buf.writestring("static "); typeToBuffer(vd.type, vd); writeDeclEnd(); return; } if (adparent && vd.type && vd.type.deco) { writeProtection(vd.visibility.kind); typeToBuffer(vd.type, vd, true); buf.writestringln(";"); if (auto t = vd.type.isTypeStruct()) includeSymbol(t.sym); checkbuf.level++; const pn = adparent.ident.toChars(); const vn = vd.ident.toChars(); const vo = vd.offset; checkbuf.printf("assert(offsetof(%s, %s) == %d);", pn, vn, vo); checkbuf.writenl(); checkbuf.level--; return; } visit(cast(AST.Dsymbol)vd); } override void visit(AST.TypeInfoDeclaration tid) { debug (Debug_DtoH) { printf("[AST.TypeInfoDeclaration enter] %s\n", tid.toChars()); scope(exit) printf("[AST.TypeInfoDeclaration exit] %s\n", tid.toChars()); } } override void visit(AST.AliasDeclaration ad) { debug (Debug_DtoH) { printf("[AST.AliasDeclaration enter] %s\n", ad.toChars()); scope(exit) printf("[AST.AliasDeclaration exit] %s\n", ad.toChars()); } writeProtection(ad.visibility.kind); if (auto t = ad.type) { if (t.ty == AST.Tdelegate) { visit(cast(AST.Dsymbol)ad); return; } // for function pointers we need to original type if (ad.type.ty == AST.Tpointer && (cast(AST.TypePointer)t).nextOf.ty == AST.Tfunction) { origType = &ad.originalType; } scope(exit) origType = null; buf.writestring("typedef "); typeToBuffer(origType ? *origType : t, ad); writeDeclEnd(); return; } if (!ad.aliassym) { assert(0); } if (auto ti = ad.aliassym.isTemplateInstance()) { visitTi(ti); return; } if (auto sd = ad.aliassym.isStructDeclaration()) { buf.writestring("typedef "); sd.type.accept(this); buf.writestring(" "); writeIdentifier(ad); writeDeclEnd(); return; } else if (auto td = ad.aliassym.isTemplateDeclaration()) { if (global.params.cplusplus < CppStdRevision.cpp11) { ignored("%s because `using` declarations require C++ 11", ad.toPrettyChars()); return; } printTemplateParams(td); buf.writestring("using "); writeIdentifier(ad); buf.printf(" = %s<", td.ident.toChars()); foreach (const idx, const p; *td.parameters) { if (idx) buf.writestring(", "); writeIdentifier(p.ident, p.loc, "parameter", true); } buf.writestringln(">;"); return; } if (ad.aliassym.isDtorDeclaration()) { // Ignore. It's taken care of while visiting FuncDeclaration return; } ignored("%s %s", ad.aliassym.kind(), ad.aliassym.toPrettyChars()); } override void visit(AST.Nspace ns) { handleNspace(ns, ns.members); } override void visit(AST.CPPNamespaceDeclaration ns) { handleNspace(ns, ns.decl); } void handleNspace(AST.Dsymbol namespace, Dsymbols* members) { buf.writestring("namespace "); writeIdentifier(namespace); buf.writenl(); buf.writestring("{"); buf.writenl(); buf.level++; foreach(decl;(*members)) { decl.accept(this); } buf.level--; buf.writestring("}"); buf.writenl(); } override void visit(AST.AnonDeclaration ad) { debug (Debug_DtoH) { printf("[AST.AnonDeclaration enter] %s\n", ad.toChars()); scope(exit) printf("[AST.AnonDeclaration exit] %s\n", ad.toChars()); } buf.writestringln(ad.isunion ? "union" : "struct"); buf.writestringln("{"); buf.level++; foreach (s; *ad.decl) { s.accept(this); } buf.level--; buf.writestringln("};"); } private bool memberField(AST.VarDeclaration vd) { if (!vd.type || !vd.type.deco || !vd.ident) return false; if (!vd.isField()) return false; if (vd.type.ty == AST.Tfunction) return false; if (vd.type.ty == AST.Tsarray) return false; return true; } override void visit(AST.StructDeclaration sd) { debug (Debug_DtoH) { printf("[AST.StructDeclaration enter] %s\n", sd.toChars()); scope(exit) printf("[AST.StructDeclaration exit] %s\n", sd.toChars()); } if (isSkippableTemplateInstance(sd)) return; if (cast(void*)sd in visited) return; visited[cast(void*)sd] = true; if (linkage != LINK.c && linkage != LINK.cpp) { ignored("non-cpp struct %s because of linkage", sd.toChars()); return; } const ignoredStash = this.ignoredCounter; scope (exit) this.ignoredCounter = ignoredStash; pushAlignToBuffer(sd.alignment); writeProtection(sd.visibility.kind); const structAsClass = sd.cppmangle == CPPMANGLE.asClass; if (sd.isUnionDeclaration()) buf.writestring("union "); else buf.writestring(structAsClass ? "class " : "struct "); writeIdentifier(sd); if (!sd.members) { buf.writestringln(";"); buf.writenl(); return; } buf.writenl(); buf.writestring("{"); const protStash = this.currentVisibility; this.currentVisibility = structAsClass ? AST.Visibility.Kind.private_ : AST.Visibility.Kind.public_; scope (exit) this.currentVisibility = protStash; buf.level++; buf.writenl(); auto save = adparent; adparent = sd; foreach (m; *sd.members) { m.accept(this); } // Generate default ctor if (!sd.noDefaultCtor && !sd.isUnionDeclaration()) { writeProtection(AST.Visibility.Kind.public_); buf.printf("%s()", sd.ident.toChars()); size_t varCount; bool first = true; buf.level++; foreach (m; *sd.members) { if (auto vd = m.isVarDeclaration()) { if (!memberField(vd)) continue; varCount++; if (!vd._init && !vd.type.isTypeBasic() && !vd.type.isTypePointer && !vd.type.isTypeStruct && !vd.type.isTypeClass && !vd.type.isTypeDArray && !vd.type.isTypeSArray) { continue; } if (vd._init && vd._init.isVoidInitializer()) continue; if (first) { buf.writestringln(" :"); first = false; } else { buf.writestringln(","); } writeIdentifier(vd, true); buf.writeByte('('); if (vd._init) { auto e = AST.initializerToExpression(vd._init); printExpressionFor(vd.type, e, true); } buf.printf(")"); } } buf.level--; buf.writenl(); buf.writestringln("{"); buf.writestringln("}"); auto ctor = sd.ctor ? sd.ctor.isFuncDeclaration() : null; if (varCount && (!ctor || ctor.storage_class & AST.STC.disable)) { buf.printf("%s(", sd.ident.toChars()); first = true; foreach (m; *sd.members) { if (auto vd = m.isVarDeclaration()) { if (!memberField(vd)) continue; if (!first) buf.writestring(", "); assert(vd.type); assert(vd.ident); typeToBuffer(vd.type, vd, true); // Don't print default value for first parameter to not clash // with the default ctor defined above if (!first) { buf.writestring(" = "); if (vd._init && !vd._init.isVoidInitializer()) printExpressionFor(vd.type, AST.initializerToExpression(vd._init)); else printExpressionFor(vd.type, vd.type.defaultInitLiteral(Loc.initial)); } first = false; } } buf.writestring(") :"); buf.level++; buf.writenl(); first = true; foreach (m; *sd.members) { if (auto vd = m.isVarDeclaration()) { if (!memberField(vd)) continue; if (first) first = false; else buf.writestringln(","); writeIdentifier(vd, true); buf.writeByte('('); writeIdentifier(vd, true); buf.writeByte(')'); } } buf.writenl(); buf.writestringln("{}"); buf.level--; } } buf.level--; adparent = save; buf.writestringln("};"); popAlignToBuffer(sd.alignment); buf.writenl(); // Workaround because size triggers a forward-reference error // for struct templates (the size is undetermined even if the // size doesn't depend on the parameters) if (!tdparent) { checkbuf.level++; const sn = sd.ident.toChars(); const sz = sd.size(Loc.initial); checkbuf.printf("assert(sizeof(%s) == %llu);", sn, sz); checkbuf.writenl(); checkbuf.level--; } } private void pushAlignToBuffer(uint alignment) { // DMD ensures alignment is a power of two //assert(alignment > 0 && ((alignment & (alignment - 1)) == 0), // "Invalid alignment size"); // When no alignment is specified, `uint.max` is the default // FIXME: alignment is 0 for structs templated members if (alignment == STRUCTALIGN_DEFAULT || (tdparent && alignment == 0)) { return; } buf.printf("#pragma pack(push, %d)", alignment); buf.writenl(); } private void popAlignToBuffer(uint alignment) { if (alignment == STRUCTALIGN_DEFAULT || (tdparent && alignment == 0)) return; buf.writestringln("#pragma pack(pop)"); } private void includeSymbol(AST.Dsymbol ds) { debug (Debug_DtoH) { printf("[includeSymbol(AST.Dsymbol) enter] %s\n", ds.toChars()); scope(exit) printf("[includeSymbol(AST.Dsymbol) exit] %s\n", ds.toChars()); } if (cast(void*) ds in visited) return; OutBuffer decl; decl.doindent = true; decl.spaces = true; visitAsRoot(ds, &decl); donebuf.writestring(decl.peekChars()); } override void visit(AST.ClassDeclaration cd) { debug (Debug_DtoH) { printf("[AST.ClassDeclaration enter] %s\n", cd.toChars()); scope(exit) printf("[AST.ClassDeclaration exit] %s\n", cd.toChars()); } if (isSkippableTemplateInstance(cd)) return; if (cast(void*)cd in visited) return; visited[cast(void*)cd] = true; if (!cd.isCPPclass() && !(tdparent && linkage == LINK.cpp)) // FIXME: ClassKind not set for templated classes? { ignored("non-cpp class %s", cd.toChars()); return; } writeProtection(cd.visibility.kind); const classAsStruct = cd.cppmangle == CPPMANGLE.asStruct; buf.writestring(classAsStruct ? "struct " : "class "); writeIdentifier(cd); if (cd.storage_class & AST.STC.final_ || (tdparent && this.storageClass & AST.STC.final_)) buf.writestring(" final"); assert(cd.baseclasses); foreach (i, base; *cd.baseclasses) { buf.writestring(i == 0 ? " : public " : ", public "); // Base classes/interfaces might depend on template parameters, // e.g. class A(T) : B!T { ... } if (base.sym is null) { base.type.accept(this); } // base.type references onemember for template instances // and hence skips the TypeInstance... else if (auto ti = base.sym.isInstantiated()) { visitTi(ti); } else { buf.writestring(base.sym.toChars()); includeSymbol(base.sym); } } if (!cd.members) { buf.writestring(";"); buf.writenl(); buf.writenl(); return; } buf.writenl(); buf.writestringln("{"); const protStash = this.currentVisibility; this.currentVisibility = classAsStruct ? AST.Visibility.Kind.public_ : AST.Visibility.Kind.private_; scope (exit) this.currentVisibility = protStash; auto save = adparent; adparent = cd; buf.level++; foreach (m; *cd.members) { m.accept(this); } buf.level--; adparent = save; buf.writestringln("};"); buf.writenl(); } override void visit(AST.EnumDeclaration ed) { debug (Debug_DtoH) { printf("[AST.EnumDeclaration enter] %s\n", ed.toChars()); scope(exit) printf("[AST.EnumDeclaration exit] %s\n", ed.toChars()); } if (cast(void*)ed in visited) return; visited[cast(void*)ed] = true; //if (linkage != LINK.c && linkage != LINK.cpp) //{ //ignored("non-cpp enum %s because of linkage\n", ed.toChars()); //return; //} // we need to know a bunch of stuff about the enum... bool isAnonymous = ed.ident is null; const isOpaque = !ed.members; AST.Type type = ed.memtype; if (!type && !isOpaque) { // check all keys have matching type foreach (_m; *ed.members) { auto m = _m.isEnumMember(); if (!type) type = m.type; else if (m.type !is type) { type = null; break; } } } EnumKind kind = getEnumKind(type); if (isOpaque) { // Opaque enums were introduced in C++ 11 (workaround?) if (global.params.cplusplus < CppStdRevision.cpp11) { ignored("%s because opaque enums require C++ 11", ed.toPrettyChars()); return; } // Opaque enum defaults to int but the type might not be set else if (!type) { kind = EnumKind.Int; } // Cannot apply namespace workaround for non-integral types else if (kind != EnumKind.Int && kind != EnumKind.Numeric) { ignored("enum %s because of its base type", ed.toPrettyChars()); return; } } // determine if this is an enum, or just a group of manifest constants bool manifestConstants = !isOpaque && (!type || (isAnonymous && kind == EnumKind.Other)); assert(!manifestConstants || isAnonymous); writeProtection(ed.visibility.kind); // write the enum header if (!manifestConstants) { if (kind == EnumKind.Int || kind == EnumKind.Numeric) { buf.writestring("enum"); // D enums are strong enums, but there exists only a direct mapping // with 'enum class' from C++-11 onwards. if (global.params.cplusplus >= CppStdRevision.cpp11) { if (!isAnonymous) { buf.writestring(" class "); writeIdentifier(ed); } if (kind == EnumKind.Numeric) { buf.writestring(" : "); determineEnumType(type).accept(this); } } else if (!isAnonymous) { buf.writeByte(' '); writeIdentifier(ed); } } else { buf.writestring("namespace"); if(!isAnonymous) { buf.writeByte(' '); writeIdentifier(ed); } } // Opaque enums have no members, hence skip the body if (isOpaque) { buf.writestringln(";"); return; } else { buf.writenl(); buf.writestringln("{"); } } // emit constant for each member if (!manifestConstants) buf.level++; foreach (_m; *ed.members) { auto m = _m.isEnumMember(); AST.Type memberType = type ? type : m.type; const EnumKind memberKind = type ? kind : getEnumKind(memberType); if (!manifestConstants && (kind == EnumKind.Int || kind == EnumKind.Numeric)) { // C++-98 compatible enums must use the typename as a prefix to avoid // collisions with other identifiers in scope. For consistency with D, // the enum member `Type.member` is emitted as `Type_member` in C++-98. if (!isAnonymous && global.params.cplusplus < CppStdRevision.cpp11) { writeIdentifier(ed); buf.writeByte('_'); } writeIdentifier(m, true); buf.writestring(" = "); auto ie = cast(AST.IntegerExp)m.value; visitInteger(ie.toInteger(), memberType); buf.writestring(","); } else if (global.params.cplusplus >= CppStdRevision.cpp11 && manifestConstants && (memberKind == EnumKind.Int || memberKind == EnumKind.Numeric)) { buf.writestring("enum : "); determineEnumType(memberType).accept(this); buf.writestring(" { "); writeIdentifier(m, true); buf.writestring(" = "); auto ie = cast(AST.IntegerExp)m.value; visitInteger(ie.toInteger(), memberType); buf.writestring(" };"); } else { buf.writestring("static "); auto target = determineEnumType(memberType); target.accept(this); buf.writestring(" const "); writeIdentifier(m, true); buf.writestring(" = "); printExpressionFor(target, m.origValue); buf.writestring(";"); } buf.writenl(); } if (!manifestConstants) buf.level--; // write the enum tail if (!manifestConstants) buf.writestring("};"); buf.writenl(); buf.writenl(); } override void visit(AST.EnumMember em) { assert(false, "This node type should be handled in the EnumDeclaration"); } /** * Prints a member/parameter/variable declaration into `buf`. * * Params: * t = the type (used if `this.origType` is null) * s = the symbol denoting the identifier * canFixup = whether the identifier may be changed without affecting * binary compatibility (forwarded to `writeIdentifier`) */ private void typeToBuffer(AST.Type t, AST.Dsymbol s, const bool canFixup = false) { debug (Debug_DtoH) { printf("[typeToBuffer(AST.Type, AST.Dsymbol) enter] %s sym %s\n", t.toChars(), s.toChars()); scope(exit) printf("[typeToBuffer(AST.Type, AST.Dsymbol) exit] %s sym %s\n", t.toChars(), s.toChars()); } this.ident = s.ident; origType ? origType.accept(this) : t.accept(this); if (this.ident) { buf.writeByte(' '); writeIdentifier(s, canFixup); } this.ident = null; if (auto tsa = t.isTypeSArray()) { buf.writeByte('['); tsa.dim.accept(this); buf.writeByte(']'); } } override void visit(AST.Type t) { debug (Debug_DtoH) { printf("[AST.Type enter] %s\n", t.toChars()); scope(exit) printf("[AST.Type exit] %s\n", t.toChars()); } printf("Invalid type: %s\n", t.toPrettyChars()); assert(0); } override void visit(AST.TypeIdentifier t) { debug (Debug_DtoH) { printf("[AST.TypeIdentifier enter] %s\n", t.toChars()); scope(exit) printf("[AST.TypeIdentifier exit] %s\n", t.toChars()); } if (t.idents.length) buf.writestring("typename "); writeIdentifier(t.ident, t.loc, "type", tdparent !is null); foreach (arg; t.idents) { buf.writestring("::"); import dmd.root.rootobject; // Is this even possible? if (arg.dyncast != DYNCAST.identifier) { printf("arg.dyncast() = %d\n", arg.dyncast()); assert(false); } buf.writestring((cast(Identifier) arg).toChars()); } } override void visit(AST.TypeNull t) { debug (Debug_DtoH) { printf("[AST.TypeNull enter] %s\n", t.toChars()); scope(exit) printf("[AST.TypeNull exit] %s\n", t.toChars()); } if (global.params.cplusplus >= CppStdRevision.cpp11) buf.writestring("nullptr_t"); else buf.writestring("void*"); } override void visit(AST.TypeTypeof t) { debug (Debug_DtoH) { printf("[AST.TypeInstance enter] %s\n", t.toChars()); scope(exit) printf("[AST.TypeInstance exit] %s\n", t.toChars()); } assert(t.exp); if (t.exp.type) { t.exp.type.accept(this); } else if (t.exp.isThisExp()) { // Short circuit typeof(this) => <Aggregate name> assert(adparent); buf.writestring(adparent.ident.toChars()); } else { // Relying on C++'s typeof might produce wrong results // but it's the best we've got here. buf.writestring("typeof("); t.exp.accept(this); buf.writeByte(')'); } } override void visit(AST.TypeBasic t) { debug (Debug_DtoH) { printf("[AST.TypeBasic enter] %s\n", t.toChars()); scope(exit) printf("[AST.TypeBasic exit] %s\n", t.toChars()); } if (t.isConst() || t.isImmutable()) buf.writestring("const "); string typeName; switch (t.ty) { case AST.Tvoid: typeName = "void"; break; case AST.Tbool: typeName = "bool"; break; case AST.Tchar: typeName = "char"; break; case AST.Twchar: typeName = "char16_t"; break; case AST.Tdchar: typeName = "char32_t"; break; case AST.Tint8: typeName = "int8_t"; break; case AST.Tuns8: typeName = "uint8_t"; break; case AST.Tint16: typeName = "int16_t"; break; case AST.Tuns16: typeName = "uint16_t"; break; case AST.Tint32: typeName = "int32_t"; break; case AST.Tuns32: typeName = "uint32_t"; break; case AST.Tint64: typeName = "int64_t"; break; case AST.Tuns64: typeName = "uint64_t"; break; case AST.Tfloat32: typeName = "float"; break; case AST.Tfloat64: typeName = "double"; break; case AST.Tfloat80: typeName = "_d_real"; hasReal = true; break; default: //t.print(); assert(0); } buf.writestring(typeName); } override void visit(AST.TypePointer t) { debug (Debug_DtoH) { printf("[AST.TypePointer enter] %s\n", t.toChars()); scope(exit) printf("[AST.TypePointer exit] %s\n", t.toChars()); } auto ts = t.next.isTypeStruct(); if (ts && !strcmp(ts.sym.ident.toChars(), "__va_list_tag")) { buf.writestring("va_list"); return; } t.next.accept(this); if (t.next.ty != AST.Tfunction) buf.writeByte('*'); if (t.isConst() || t.isImmutable()) buf.writestring(" const"); } override void visit(AST.TypeSArray t) { debug (Debug_DtoH) { printf("[AST.TypeSArray enter] %s\n", t.toChars()); scope(exit) printf("[AST.TypeSArray exit] %s\n", t.toChars()); } t.next.accept(this); } override void visit(AST.TypeAArray t) { debug (Debug_DtoH) { printf("[AST.TypeAArray enter] %s\n", t.toChars()); scope(exit) printf("[AST.TypeAArray exit] %s\n", t.toChars()); } AST.Type.tvoidptr.accept(this); } override void visit(AST.TypeFunction tf) { debug (Debug_DtoH) { printf("[AST.TypeFunction enter] %s\n", tf.toChars()); scope(exit) printf("[AST.TypeFunction exit] %s\n", tf.toChars()); } tf.next.accept(this); buf.writeByte('('); buf.writeByte('*'); if (ident) buf.writestring(ident.toChars()); ident = null; buf.writeByte(')'); buf.writeByte('('); foreach (i, fparam; tf.parameterList) { if (i) buf.writestring(", "); fparam.accept(this); } if (tf.parameterList.varargs) { if (tf.parameterList.parameters.dim && tf.parameterList.varargs == 1) buf.writestring(", "); buf.writestring("..."); } buf.writeByte(')'); } private void enumToBuffer(AST.EnumDeclaration ed) { debug (Debug_DtoH) { printf("[enumToBuffer(AST.EnumDeclaration) enter] %s\n", ed.toChars()); scope(exit) printf("[enumToBuffer(AST.EnumDeclaration) exit] %s\n", ed.toChars()); } if (ed.isSpecial()) { if (ed.ident == DMDType.c_long) buf.writestring("long"); else if (ed.ident == DMDType.c_ulong) buf.writestring("unsigned long"); else if (ed.ident == DMDType.c_longlong) buf.writestring("long long"); else if (ed.ident == DMDType.c_ulonglong) buf.writestring("unsigned long long"); else if (ed.ident == DMDType.c_long_double) buf.writestring("long double"); else if (ed.ident == DMDType.c_wchar_t) buf.writestring("wchar_t"); else { //ed.print(); assert(0); } return; } const kind = getEnumKind(ed.memtype); // Check if the enum was emitted as a real enum if (kind == EnumKind.Int || kind == EnumKind.Numeric) buf.writestring(ed.toChars()); else { // Use the base type if the enum was emitted as a namespace buf.printf("/* %s */ ", ed.ident.toChars()); ed.memtype.accept(this); } } override void visit(AST.TypeEnum t) { debug (Debug_DtoH) { printf("[AST.TypeEnum enter] %s\n", t.toChars()); scope(exit) printf("[AST.TypeEnum exit] %s\n", t.toChars()); } if (cast(void*)t.sym !in forwarded) { forwarded[cast(void*)t.sym] = true; //printf("Visiting enum %s from module %s %s\n", t.sym.toPrettyChars(), t.toChars(), t.sym.loc.toChars()); visitAsRoot(t.sym, fwdbuf); } if (t.isConst() || t.isImmutable()) buf.writestring("const "); enumToBuffer(t.sym); } override void visit(AST.TypeStruct t) { debug (Debug_DtoH) { printf("[AST.TypeStruct enter] %s\n", t.toChars()); scope(exit) printf("[AST.TypeStruct exit] %s\n", t.toChars()); } if (cast(void*)t.sym !in forwarded && !t.sym.parent.isTemplateInstance()) { forwarded[cast(void*)t.sym] = true; fwdbuf.writestring(t.sym.isUnionDeclaration() ? "union " : "struct "); fwdbuf.writestring(t.sym.toChars()); fwdbuf.writestringln(";"); } if (t.isConst() || t.isImmutable()) buf.writestring("const "); if (auto ti = t.sym.parent.isTemplateInstance()) { visitTi(ti); return; } buf.writestring(t.sym.toChars()); } override void visit(AST.TypeDArray t) { debug (Debug_DtoH) { printf("[AST.TypeDArray enter] %s\n", t.toChars()); scope(exit) printf("[AST.TypeDArray exit] %s\n", t.toChars()); } if (t.isConst() || t.isImmutable()) buf.writestring("const "); buf.writestring("_d_dynamicArray< "); t.next.accept(this); buf.writestring(" >"); } override void visit(AST.TypeInstance t) { debug (Debug_DtoH) { printf("[AST.TypeInstance enter] %s\n", t.toChars()); scope(exit) printf("[AST.TypeInstance exit] %s\n", t.toChars()); } visitTi(t.tempinst); } private void visitTi(AST.TemplateInstance ti) { debug (Debug_DtoH) { printf("[visitTi(AST.TemplateInstance) enter] %s\n", ti.toChars()); scope(exit) printf("[visitTi(AST.TemplateInstance) exit] %s\n", ti.toChars()); } foreach (o; *ti.tiargs) { if (!AST.isType(o)) return; } buf.writestring(ti.name.toChars()); buf.writeByte('<'); foreach (i, o; *ti.tiargs) { if (i) buf.writestring(", "); if (auto tt = AST.isType(o)) { tt.accept(this); } else { //ti.print(); //o.print(); assert(0); } } buf.writestring(" >"); } override void visit(AST.TemplateDeclaration td) { debug (Debug_DtoH) { printf("[AST.TemplateDeclaration enter] %s\n", td.toChars()); scope(exit) printf("[AST.TemplateDeclaration exit] %s\n", td.toChars()); } if (cast(void*)td in visited) return; visited[cast(void*)td] = true; if (!td.parameters || !td.onemember || (!td.onemember.isStructDeclaration && !td.onemember.isClassDeclaration && !td.onemember.isFuncDeclaration)) { visit(cast(AST.Dsymbol)td); return; } // Explicitly disallow templates with non-type parameters or specialization. foreach (p; *td.parameters) { if (!p.isTemplateTypeParameter() || p.specialization()) { visit(cast(AST.Dsymbol)td); return; } } if (linkage != LINK.c && linkage != LINK.cpp) { ignored("template %s because of linkage", td.toPrettyChars()); return; } auto save = tdparent; tdparent = td; const bookmark = buf.length; printTemplateParams(td); const oldIgnored = this.ignoredCounter; td.onemember.accept(this); // Remove "template<...>" if the symbol could not be emitted if (oldIgnored != this.ignoredCounter) buf.setsize(bookmark); tdparent = save; } private void printTemplateParams(const AST.TemplateDeclaration td) { buf.writestring("template <"); bool first = true; foreach (p; *td.parameters) { if (first) first = false; else buf.writestring(", "); buf.writestring("typename "); writeIdentifier(p.ident, p.loc, "template parameter", true); } buf.writestringln(">"); } override void visit(AST.TypeClass t) { debug (Debug_DtoH) { printf("[AST.TypeClass enter] %s\n", t.toChars()); scope(exit) printf("[AST.TypeClass exit] %s\n", t.toChars()); } if (cast(void*)t.sym !in forwarded) { forwarded[cast(void*)t.sym] = true; fwdbuf.writestring("class "); fwdbuf.writestring(t.sym.toChars()); fwdbuf.writestringln(";"); } if (t.isConst() || t.isImmutable()) buf.writestring("const "); buf.writestring(t.sym.toChars()); buf.writeByte('*'); if (t.isConst() || t.isImmutable()) buf.writestring(" const"); } /** * Writes the function signature to `buf`. * * Params: * fd = the function to print * tf = fd's type */ private void funcToBuffer(AST.TypeFunction tf, AST.FuncDeclaration fd) { debug (Debug_DtoH) { printf("[funcToBuffer(AST.TypeFunction) enter] %s\n", fd.toChars()); scope(exit) printf("[funcToBuffer(AST.TypeFunction) exit] %s\n", fd.toChars()); } auto originalType = cast(AST.TypeFunction)fd.originalType; if (fd.isCtorDeclaration() || fd.isDtorDeclaration()) { if (fd.isDtorDeclaration()) { buf.writeByte('~'); } buf.writestring(adparent.toChars()); if (!tf) { assert(fd.isDtorDeclaration()); buf.writestring("()"); return; } } else { import dmd.root.string : toDString; assert(tf.next, fd.loc.toChars().toDString()); tf.next == AST.Type.tsize_t ? originalType.next.accept(this) : tf.next.accept(this); if (tf.isref) buf.writeByte('&'); buf.writeByte(' '); writeIdentifier(fd); } buf.writeByte('('); foreach (i, fparam; tf.parameterList) { if (i) buf.writestring(", "); if (fparam.type == AST.Type.tsize_t && originalType) { fparam = originalType.parameterList[i]; } fparam.accept(this); } if (tf.parameterList.varargs) { if (tf.parameterList.parameters.dim && tf.parameterList.varargs == 1) buf.writestring(", "); buf.writestring("..."); } buf.writeByte(')'); } override void visit(AST.Parameter p) { debug (Debug_DtoH) { printf("[AST.Parameter enter] %s\n", p.toChars()); scope(exit) printf("[AST.Parameter exit] %s\n", p.toChars()); } ident = p.ident; p.type.accept(this); if (p.storageClass & AST.STC.ref_) buf.writeByte('&'); buf.writeByte(' '); if (ident) // FIXME: Parameter is missing a Loc writeIdentifier(ident, Loc.initial, "parameter", true); ident = null; if (p.defaultArg) { //printf("%s %d\n", p.defaultArg.toChars, p.defaultArg.op); buf.writestring(" = "); printExpressionFor(p.type, p.defaultArg); } } /** * Prints `exp` as an expression of type `target` while inserting * appropriate code when implicit conversion does not translate * directly to C++, e.g. from an enum to its base type. * * Params: * target = the type `exp` is converted to * exp = the expression to print * isCtor = if `exp` is a ctor argument */ private void printExpressionFor(AST.Type target, AST.Expression exp, const bool isCtor = false) { /// Determines if a static_cast is required static bool needsCast(AST.Type target, AST.Expression exp) { // import std.stdio; // writefln("%s:%s: target = %s, type = %s (%s)", exp.loc.linnum, exp.loc.charnum, target, exp.type, exp.op); auto source = exp.type; // DotVarExp resolve conversions, e.g from an enum to its base type if (auto dve = exp.isDotVarExp()) source = dve.var.type; if (!source) // Defensively assume that the cast is required return true; // Conversions from enum class to base type require static_cast if (global.params.cplusplus >= CppStdRevision.cpp11 && source.isTypeEnum && !target.isTypeEnum) return true; return false; } // Slices are emitted as a special struct, hence we need to fix up // any expression initialising a slice variable/member if (auto ta = target.isTypeDArray()) { if (exp.isNullExp()) { if (isCtor) { // Don't emit, use default ctor } else if (global.params.cplusplus >= CppStdRevision.cpp11) { // Prefer initializer list buf.writestring("{}"); } else { // Write __d_dynamic_array<TYPE>() visit(ta); buf.writestring("()"); } return; } if (auto se = exp.isStringExp()) { // Rewrite as <length> + <literal> pair optionally // wrapped in a initializer list/ctor call const initList = global.params.cplusplus >= CppStdRevision.cpp11; if (!isCtor) { if (initList) buf.writestring("{ "); else { visit(ta); buf.writestring("( "); } } buf.printf("%zu, ", se.len); visit(se); if (!isCtor) buf.writestring(initList ? " }" : " )"); return; } } else if (needsCast(target, exp)) { buf.writestring("static_cast<"); target.accept(this); buf.writestring(">("); exp.accept(this); buf.writeByte(')'); } else { exp.accept(this); } } override void visit(AST.Expression e) { debug (Debug_DtoH) { printf("[AST.Expression enter] %s\n", e.toChars()); scope(exit) printf("[AST.Expression exit] %s\n", e.toChars()); } // Valid in most cases, others should be overriden below // to use the appropriate operators (:: and ->) buf.writestring(e.toString()); } override void visit(AST.VarExp e) { debug (Debug_DtoH) { printf("[AST.VarExp enter] %s\n", e.toChars()); scope(exit) printf("[AST.VarExp exit] %s\n", e.toChars()); } /// Partially prints the FQN including parent aggregates void printPrefix(AST.Dsymbol var) { if (!var || !var.isAggregateDeclaration()) return; printPrefix(var.parent); includeSymbol(var); buf.writestring(var.toString()); buf.writestring("::"); } // Static members are not represented as DotVarExp, hence // manually print the full name here if (e.var.storage_class & AST.STC.static_) printPrefix(e.var.parent); includeSymbol(e.var); writeIdentifier(e.var, !!e.var.isThis()); } override void visit(AST.CallExp e) { debug (Debug_DtoH) { printf("[AST.CallExp enter] %s\n", e.toChars()); scope(exit) printf("[AST.CallExp exit] %s\n", e.toChars()); } // Dereferencing function pointers requires additional braces: (*f)(args) const isFp = e.e1.isPtrExp(); if (isFp) buf.writeByte('('); else if (e.f) includeSymbol(e.f); e.e1.accept(this); if (isFp) buf.writeByte(')'); assert(e.arguments); buf.writeByte('('); foreach (i, arg; *e.arguments) { if (i) buf.writestring(", "); arg.accept(this); } buf.writeByte(')'); } override void visit(AST.DotVarExp e) { debug (Debug_DtoH) { printf("[AST.DotVarExp enter] %s\n", e.toChars()); scope(exit) printf("[AST.DotVarExp exit] %s\n", e.toChars()); } // Accessing members through a pointer? if (auto pe = e.e1.isPtrExp) { pe.e1.accept(this); buf.writestring("->"); } else { e.e1.accept(this); buf.writeByte('.'); } // Should only be used to access non-static members assert(e.var.isThis()); writeIdentifier(e.var, true); } override void visit(AST.DotIdExp e) { debug (Debug_DtoH) { printf("[AST.DotIdExp enter] %s\n", e.toChars()); scope(exit) printf("[AST.DotIdExp exit] %s\n", e.toChars()); } e.e1.accept(this); buf.writestring("::"); buf.writestring(e.ident.toChars()); } override void visit(AST.NullExp e) { debug (Debug_DtoH) { printf("[AST.NullExp enter] %s\n", e.toChars()); scope(exit) printf("[AST.NullExp exit] %s\n", e.toChars()); } if (global.params.cplusplus >= CppStdRevision.cpp11) buf.writestring("nullptr"); else buf.writestring("NULL"); } override void visit(AST.ArrayLiteralExp e) { debug (Debug_DtoH) { printf("[AST.ArrayLiteralExp enter] %s\n", e.toChars()); scope(exit) printf("[AST.ArrayLiteralExp exit] %s\n", e.toChars()); } buf.writestring("arrayliteral"); } override void visit(AST.StringExp e) { debug (Debug_DtoH) { printf("[AST.StringExp enter] %s\n", e.toChars()); scope(exit) printf("[AST.StringExp exit] %s\n", e.toChars()); } if (e.sz == 2) buf.writeByte('u'); else if (e.sz == 4) buf.writeByte('U'); buf.writeByte('"'); for (size_t i = 0; i < e.len; i++) { uint c = e.charAt(i); switch (c) { case '"': case '\\': buf.writeByte('\\'); goto default; default: if (c <= 0xFF) { if (c >= 0x20 && c < 0x80) buf.writeByte(c); else buf.printf("\\x%02x", c); } else if (c <= 0xFFFF) buf.printf("\\u%04x", c); else buf.printf("\\U%08x", c); break; } } buf.writeByte('"'); } override void visit(AST.RealExp e) { debug (Debug_DtoH) { printf("[AST.RealExp enter] %s\n", e.toChars()); scope(exit) printf("[AST.RealExp exit] %s\n", e.toChars()); } import dmd.root.ctfloat : CTFloat; // Special case NaN and Infinity because floatToBuffer // uses D literals (`nan` and `infinity`) if (CTFloat.isNaN(e.value)) { buf.writestring("NAN"); } else if (CTFloat.isInfinity(e.value)) { if (e.value < 0) buf.writeByte('-'); buf.writestring("INFINITY"); } else { import dmd.hdrgen; // Hex floating point literals were introduced in C++ 17 const allowHex = global.params.cplusplus >= CppStdRevision.cpp17; floatToBuffer(e.type, e.value, buf, allowHex); } } override void visit(AST.IntegerExp e) { debug (Debug_DtoH) { printf("[AST.IntegerExp enter] %s\n", e.toChars()); scope(exit) printf("[AST.IntegerExp exit] %s\n", e.toChars()); } visitInteger(e.toInteger, e.type); } private void visitInteger(dinteger_t v, AST.Type t) { debug (Debug_DtoH) { printf("[visitInteger(AST.Type) enter] %s\n", t.toChars()); scope(exit) printf("[visitInteger(AST.Type) exit] %s\n", t.toChars()); } switch (t.ty) { case AST.Tenum: auto te = cast(AST.TypeEnum)t; buf.writestring("("); enumToBuffer(te.sym); buf.writestring(")"); visitInteger(v, te.sym.memtype); break; case AST.Tbool: buf.writestring(v ? "true" : "false"); break; case AST.Tint8: buf.printf("%d", cast(byte)v); break; case AST.Tuns8: buf.printf("%uu", cast(ubyte)v); break; case AST.Tint16: buf.printf("%d", cast(short)v); break; case AST.Tuns16: case AST.Twchar: buf.printf("%uu", cast(ushort)v); break; case AST.Tint32: case AST.Tdchar: buf.printf("%d", cast(int)v); break; case AST.Tuns32: buf.printf("%uu", cast(uint)v); break; case AST.Tint64: buf.printf("%lldLL", v); break; case AST.Tuns64: buf.printf("%lluLLU", v); break; case AST.Tchar: if (v > 0x20 && v < 0x80) buf.printf("'%c'", cast(int)v); else buf.printf("%uu", cast(ubyte)v); break; default: //t.print(); assert(0); } } override void visit(AST.StructLiteralExp sle) { debug (Debug_DtoH) { printf("[AST.StructLiteralExp enter] %s\n", sle.toChars()); scope(exit) printf("[AST.StructLiteralExp exit] %s\n", sle.toChars()); } sle.sd.type.accept(this); buf.writeByte('('); foreach(i, e; *sle.elements) { if (i) buf.writestring(", "); printExpressionFor(sle.sd.fields[i].type, e); } buf.writeByte(')'); } static if (__VERSION__ < 2092) { private void ignored(const char* format, ...) nothrow { this.ignoredCounter++; import core.stdc.stdarg; if (!printIgnored) return; va_list ap; va_start(ap, format); buf.writestring("// Ignored "); buf.vprintf(format, ap); buf.writenl(); va_end(ap); } } else { // Writes a formatted message into `buf` if `printIgnored` is true. pragma(printf) private void ignored(const char* format, ...) nothrow { this.ignoredCounter++; import core.stdc.stdarg; if (!printIgnored) return; va_list ap; va_start(ap, format); buf.writestring("// Ignored "); buf.vprintf(format, ap); buf.writenl(); va_end(ap); } } /** Checks whether s is a template instance that should not be emitted **/ private bool isSkippableTemplateInstance(AST.Dsymbol s) { auto td = s.isInstantiated(); return td && td !is tdparent; } }
D
/******************************************************************************* * Main entry point for ncurses * * Provides functions to initialize and deinitialize the main windows. * This would be done as static this()/static ~this(), but we need to * have the ability to exit ncurses mode and reenter it later. * * Authors: Matthew Soucy, msoucy@csh.rit.edu * Date: Nov 12, 2012 * Version: 0.0.1 */ module metus.dncurses.dncurses; public import metus.dncurses.window; public import metus.dncurses.mode; /** * Standard window * * Equivalent to ncurses' stdscr */ public Window stdwin; /** * Initialize the screen * * Creates stdwin and forces echo to be true * * Returns: stdwin */ Window initscr() { // Call library initscr and bind our standard window stdwin = new Window(nc.initscr()); echo = true; mode = Cooked(SetFlags.No); return stdwin; } /** * End all windows * * Cleans up the library and leaves ncurses mode */ void endwin() { stdwin = null; if(nc.endwin() != nc.OK) { throw new NCursesException("Could not end window properly"); } }
D
a long stout staff used as a weapon
D
module jobs.jobTypes.setKey; import jobs.Job; import jobs.jobTypes.KeyValues.KeyValue; class setKey : Job { string keyName; KeyValue keyValue; this(string keyName, KeyValue keyValue) { super("setKey"); this.keyName = keyName; this.keyValue = keyValue; } }
D
instance KDW_605_Riordian(Npc_Default) { name[0] = "Riordian"; npcType = npctype_friend; guild = GIL_KDW; level = 25; voice = 14; id = 605; flags = NPC_FLAG_IMMORTAL; attribute[ATR_STRENGTH] = 65; attribute[ATR_DEXTERITY] = 45; attribute[ATR_MANA_MAX] = 106; attribute[ATR_MANA] = 106; attribute[ATR_HITPOINTS_MAX] = 358; attribute[ATR_HITPOINTS] = 358; Mdl_SetVisual(self,"HUMANS.MDS"); Mdl_ApplyOverlayMds(self,"Humans_Mage.mds"); Mdl_SetVisualBody(self,"hum_body_Naked0",0,0,"Hum_Head_Bald",9,1,kdw_armor_l); B_Scale(self); Mdl_SetModelFatness(self,0); fight_tactic = FAI_HUMAN_MAGE; Npc_SetTalentSkill(self,NPC_TALENT_MAGE,6); CreateInvItem(self,ItArRuneThunderball); B_GiveRiordianChapter1Potions(); daily_routine = Rtn_start_605; senses = SENSE_SEE | SENSE_HEAR | SENSE_SMELL; }; func void Rtn_start_605() { TA_Sleep(23,0,4,0,"NC_KDW06_IN"); TA_PotionAlchemy(4,0,23,0,"NC_KDW06_IN"); }; func void Rtn_FoundUrShak_605() { TA_PracticeMagic(1,0,5,0,"NC_KDW_CAVE_STAIRS_MOVEMENT2"); TA_PracticeMagic(5,0,1,0,"NC_KDW_CAVE_STAIRS_MOVEMENT2"); };
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.bpmn.converter.converter.child.EscalationEventDefinitionParser; import flow.bpmn.converter.converter.util.BpmnXMLUtil; import flow.bpmn.model.BaseElement; import flow.bpmn.model.BpmnModel; import flow.bpmn.model.EscalationEventDefinition; import flow.bpmn.model.Event; import flow.bpmn.converter.converter.child.BaseChildElementParser; import flow.bpmn.converter.constants.BpmnXMLConstants; import hunt.xml; import std.uni; import hunt.logging; /** * @author Tijs Rademakers */ class EscalationEventDefinitionParser : BaseChildElementParser { override public string getElementName() { return ELEMENT_EVENT_ESCALATIONDEFINITION; } override public void parseChildElement(Element xtr, BaseElement parentElement, BpmnModel model) { if (cast(Event)parentElement is null) return; EscalationEventDefinition eventDefinition = new EscalationEventDefinition(); BpmnXMLUtil.addXMLLocation(eventDefinition, xtr); eventDefinition.setEscalationCode(xtr.firstAttribute(ATTRIBUTE_ESCALATION_REF) is null ? "" : xtr.firstAttribute(ATTRIBUTE_ESCALATION_REF).getValue); BpmnXMLUtil.parseChildElements(ELEMENT_EVENT_ESCALATIONDEFINITION, eventDefinition, xtr, model); (cast(Event) parentElement).getEventDefinitions().add(eventDefinition); } }
D
// This file is part of Visual D // // Visual D integrates the D programming language into Visual Studio // Copyright (c) 2010 by Rainer Schuetze, All Rights Reserved // // 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 // /////////////////////////////////////////////////////////////////////// // // idl2d - convert IDL or header files to D // // // module c2d.idl2d; import c2d.tokenizer; import c2d.tokutil; import c2d.dgutil; import std.string; import std.file; import std.path; import std.stdio; import std.ascii; import std.algorithm; import std.getopt; import std.utf; import std.array; import std.windows.charset; import core.memory; version = remove_pp; version = static_if_to_version; version = vsi; version = macro2template; version = targetD2; //version = Win8; class Source { string filename; string text; TokenList tokens; } // endsWith does not work reliable and crashes on page end bool _endsWith(string s, string e) { return (s.length >= e.length && s[$-e.length .. $] == e); } alias std.string.indexOf indexOf; class idl2d { /////////////////////////////////////////////////////// // configuration version(Win8) { string vsi_base_path = r"c:\l\vs9SDK"; // r"c:\l\vs9SDK"; string dte_path = r"m:\s\d\visuald\trunk\sdk\vsi\idl\"; string win_path = r"c:\l\vs11\Windows Kits\8.0\Include\"; string sdk_d_path = r"m:\s\d\visuald\trunk\sdk\"; } else version(all) { string vsi_base_path; string dte_path; string win_path; string sdk_d_path; } else version(all) { string vsi_base_path = r"c:\l\vs9SDK"; string dte_path = r"m:\s\d\visuald\trunk\sdk\vsi\idl\"; string win_path = r"c:\Programme\Microsoft SDKs\Windows\v6.0A\Include\"; string sdk_d_path = r"m:\s\d\visuald\trunk\sdk\"; } else { string vsi_base_path = r"c:\Program Files\Microsoft Visual Studio 2010 SDK"; // r"c:\l\vs9SDK"; string dte_path = r"c:\s\d\visuald\trunk\sdk\vsi\idl\"; string win_path = r"c:\Program Files\Microsoft SDKs\Windows\v7.1\Include\"; string sdk_d_path = r"c:\s\d\visuald\trunk\sdk\"; } static const string dirVSI = "vsi"; static const string dirWin = "win32"; string packageVSI = "sdk." ~ dirVSI ~ "."; string packageWin = "sdk." ~ dirWin ~ "."; string packageNF = "sdk.port."; string keywordPrefix = "sdk_"; string vsi_path; // = vsi_base_path ~ r"\VisualStudioIntegration\Common\IDL\"; string vsi_hpath; // = vsi_base_path ~ r"\VisualStudioIntegration\Common\Inc\"; string vsi_d_path; // = sdk_d_path ~ r"vsi\"; string win_d_path; // = sdk_d_path ~ r"win32\"; string[] win_idl_files; string[] vsi_idl_files; string[] vsi_h_files; string[] dte_idl_files; version(vsi) bool vsi = true; else bool vsi = false; void initFiles() { win_idl_files = [ "windef.h", "sdkddkver.h", "basetsd.h", "ntstatus.h", "winnt.h", "winbase.h", "winuser.h", "ktmtypes.h", "winerror.h", "winreg.h", "reason.h", "commctrl.h", "wingdi.h", "prsht.h", "iphlpapi.h", "iprtrmib.h", "ipexport.h", "iptypes.h", "tcpestats.h", /*"inaddr.h", "in6addr.h",*/ "ipifcons.h", "ipmib.h", "tcpmib.h", "udpmib.h", "ifmib.h", "ifdef.h", "nldef.h", "winnls.h", "shellapi.h", "rpcdce.h" /*, "rpcdcep.h"*/ ]; win_idl_files ~= [ "unknwn.idl", "oaidl.idl", "wtypes.idl", "oleidl.idl", "ocidl.idl", "objidl.idl", "docobj.idl", "oleauto.h", "objbase.h", "mshtmcid.h", "xmldom.idl", "xmldso.idl", "xmldomdid.h", "xmldsodid.h", "idispids.h", "activdbg.id*", "activscp.id*", "dbgprop.id*", // only available in Windows SDK v7.x ]; // only available (and are required for successfull compilation) in Windows SDK v8 foreach(f; [ "wtypesbase.idl", //"winapifamily.h", "apisetcconv.h", "apiset.h", // commented because it is difficult to convert this file "minwinbase.h", "processenv.h", "minwindef.h", "fileapi.h", "debugapi.h", "handleapi.h", "errhandlingapi.h", "fibersapi.h", "namedpipeapi.h", "profileapi.h", "heapapi.h", "synchapi.h", "interlockedapi.h", "processthreadsapi.h", "sysinfoapi.h", "memoryapi.h", "threadpoollegacyapiset.h", "utilapiset.h", "ioapiset.h", "threadpoolprivateapiset.h", "threadpoolapiset.h", "bemapiset.h", "wow64apiset.h", "jobapi.h", "timezoneapi.h", "datetimeapi.h", "stringapiset.h", "libloaderapi.h", "securitybaseapi.h", "namespaceapi.h", "systemtopologyapi.h", "processtopologyapi.h", "securityappcontainer.h", "realtimeapiset.h", "unknwnbase.idl", "objidlbase.idl", "combaseapi.h", // Win SDK 8.1 "mprapidef.h", "lmerr.h", "lmcons.h", ]) win_idl_files ~= f ~ "*"; // make it optional if(vsi) { vsi_idl_files = [ "shared.idh", "vsshell.idl", "*.idl", "*.idh" ]; vsi_h_files = [ "completionuuids.h", "contextuuids.h", "textmgruuids.h", "vsshelluuids.h", "vsdbgcmd.h", "venusids.h", "stdidcmd.h", "vsshlids.h", "mnuhelpids.h", "WCFReferencesIds.h", "vsdebugguids.h", "VSRegKeyNames.h", "SCGuids.h", "wbids.h", "sharedids.h", "vseeguids.h", "version.h", "scc.h", "vsplatformuiuuids.*", // only in VS2010 SDK // no longer in SDK2010: "DSLToolsCmdID.h", ]; dte_idl_files = [ "*.idl" ]; } } // see also preDefined, isExpressionToken, convertDefine, convertText, translateToken /////////////////////////////////////////////////////// string[string] tokImports; int[string] disabled_defines; int[string] disabled_ifdef; string[string] converted_defines; bool[] pp_enable_stack; string[] elif_braces_stack; bool convert_next_cpp_quote = true; bool cpp_quote_in_comment = false; bool[string] classes; string[string] aliases; bool[string] enums; string[] currentImports; string[] addedImports; void reinsert_cpp_quote(ref TokenIterator tokIt) { TokenIterator it = tokIt; string text; while(!it.atEnd() && it.text == "cpp_quote") { assert(it[1].text == "("); assert(it[2].type == Token.String); assert(it[3].text == ")"); text ~= it.pretext; text ~= strip(it[2].text[1..$-1]); it += 4; } bool endsWithBS = text.endsWith("\\") != 0; bool quote = text.indexOf("\\\n") >= 0 || endsWithBS || !convert_next_cpp_quote; if(quote) text = tokIt.pretext ~ "/+" ~ text[tokIt.pretext.length .. $] ~ "+/"; convert_next_cpp_quote = !endsWithBS; TokenList tokens = scanText(text, tokIt.lineno, true); tokIt.eraseUntil(it); tokIt = insertTokenList(tokIt, tokens); } bool handle_cpp_quote(ref TokenIterator tokIt, bool inEnum) { // tokIt on "cpp_quote" TokenIterator it = tokIt; assert(it[1].text == "("); assert(it[2].type == Token.String); assert(it[3].text == ")"); string text = strip(it[2].text[1..$-1]); string txt = text; bool convert = convert_next_cpp_quote; convert_next_cpp_quote = true; if(cpp_quote_in_comment || text.startsWith("/*")) { txt = replace(text, "\\\"", "\""); cpp_quote_in_comment = (text.indexOf("*/") < 0); } else if(text.startsWith("//")) txt = replace(text, "\\\"", "\""); else if(text.endsWith("\\")) // do not convert multi-line #define { convert_next_cpp_quote = false; convert = false; } else if(text.startsWith("#")) { txt = replace(txt, "\\\"", "\""); txt = convertPP(txt, tokIt.lineno, inEnum); } if(convert) { string pretext = tokIt.pretext; tokIt.erase(); tokIt.erase(); tokIt.erase(); tokIt.erase(); txt = cpp_string(txt); TokenList tokens = scanText(txt, tokIt.lineno, false); tokIt = insertTokenList(tokIt, tokens); tokIt.pretext = pretext ~ tokIt.pretext; } else tokIt.pretext ~= "// "; return convert; } void reinsertTextTokens(ref TokenIterator tokIt, string text) { string pretext; if(!tokIt.atEnd()) { pretext = tokIt.pretext; tokIt.erase(); } TokenList tokens = scanText(text, tokIt.lineno, false); tokIt = insertTokenList(tokIt, tokens); tokIt.pretext = pretext ~ tokIt.pretext; } bool isExpressionToken(TokenIterator tokIt, bool first) { int type = tokIt.type; switch(type) { case Token.Identifier: switch(tokIt.text) { case "_far": case "_pascal": case "_cdecl": case "void": return false; default: return !(tokIt.text in disabled_defines); } case Token.String: case Token.Number: case Token.ParenL: case Token.BracketL: case Token.BraceL: return true; case Token.ParenR: case Token.BracketR: case Token.BraceR: if(!first) return tokIt.type != Token.Identifier && tokIt.type != Token.Number && tokIt.type != Token.ParenL; return !first; case Token.Equal: case Token.Unequal: case Token.LessThan: case Token.LessEq: case Token.GreaterThan: case Token.GreaterEq: case Token.Shl: case Token.Shr: case Token.Ampersand: case Token.Assign: case Token.Dot: case Token.Div: case Token.Mod: case Token.Xor: case Token.Or: case Token.OrOr: case Token.AmpAmpersand: return !first; case Token.Plus: case Token.Minus: case Token.Asterisk: case Token.Tilde: return true; // can be unary or binary operator case Token.Colon: case Token.Question: if(vsi) goto default; return !first; case Token.Comma: return !first && !(tokIt + 1).atEnd() && tokIt[1].type != Token.EOF; case Token.Struct: // struct at beginning of a cast? if(!tokIt.atBegin() && tokIt[-1].type == Token.ParenL) return true; return false; default: return false; } } bool isExpression(TokenIterator start, TokenIterator end) { if(start == end || start.type == Token.EOF) return false; if(!isExpressionToken(start, true)) return false; for(TokenIterator it = start + 1; it != end && !it.atEnd() && it.type != Token.EOF; ++it) if(!isExpressionToken(it, false)) return false; return true; } bool isPrimaryExpr(TokenIterator it) { if(it.atEnd()) return false; if(it.text == "(" || it.type == Token.Number || it.type == Token.Identifier) return true; return false; } string getExpressionType(string ident, TokenIterator start, TokenIterator end) { while(start != end && start.text == "(" && start[1].text == "(") ++start; if(start.text == "(" && start[1].type == Token.Identifier && start[2].text == ")" && isPrimaryExpr(start + 3)) return start[1].text; if(start.text == "(" && start[1].type == Token.Identifier && start[2].text == "*" && start[3].text == ")" && isPrimaryExpr(start + 4)) return start[1].text ~ start[2].text; if(start.text == "(" && start[1].text == "struct" && start[2].type == Token.Identifier && start[3].text == "*" && start[4].text == ")" && isPrimaryExpr(start + 5)) return start[2].text ~ start[3].text; return "int"; } string getArgumentType(string ident, TokenIterator start, TokenIterator end, string rettype) { switch(ident) { case "IS_INTRESOURCE": case "MAKEINTRESOURCEA": case "MAKEINTRESOURCEW": case "MAKEINTATOM": return "int"; default: return rettype; } } void collectClasses(TokenList tokens) { for(TokenIterator tokIt = tokens.begin(); tokIt != tokens.end; ++tokIt) if(tokIt.text == "class" || tokIt.text == "interface" || tokIt.text == "coclass") classes[tokIt[1].text] = true; } bool isClassIdentifier(string ident) { if(ident in classes) return true; return false; } // 1: yes, 0: undecided, -1: no int _preDefined(string cond) { switch(cond) { case "FALSE": return -2; // not defined for expression, but for #define case "_WIN64": return 4; // special cased case "0": case "MAC": case "_MAC": case "_WIN32_WCE": case "_IA64_": case "_M_AMD64": case "RC_INVOKED": case "MIDL_PASS": case "DO_NO_IMPORTS": case "_IMM_": case "NONAMELESSUNION": case "WIN16": case "INTEROPLIB": case "__INDENTSTYLE__": case "__CTC__": case "_CTC_GUIDS_": case "CTC_INVOKED": case "VS_PACKAGE_INCLUDE": case "URTBUILD": case "NOGUIDS": case "SHOW_INCLUDES": case "RGS_INVOKED": case "__RE_E_DEFINED__": case "OLE2ANSI": // for winbase case "STRICT": case "_M_CEE": case "_M_CEE_PURE": case "_DCOM_OA_REMOTING_": case "_DCOM_OC_REMOTING_": case "_SLIST_HEADER_": case "_RTL_RUN_ONCE_DEF": case "__midl": // Windows SDK 8.0 case "NOAPISET": return -1; case "WINAPI": case "WINAPI_INLINE": case "APIENTRY": case "NTAPI": case "NTAPI_INLINE": case "interface": case "PtrToPtr64": case "Ptr64ToPtr": case "HandleToHandle64": case "Handle64ToHandle": return 3; // predefined for #define, but not in normal text case "TRUE": return 2; // predefined for expression, but not for #define case "1": case "__cplusplus": case "UNICODE": case "DEFINE_GUID": case "UNIX": case "_X86_": case "_M_IX86": case "MULTIPLE_WATCH_WINDOWS": case "PROXYSTUB_BUILD": case "(defined(_WIN32)||defined(_WIN64))&&!defined(OLE2ANSI)": case "defined(_INTEGRAL_MAX_BITS)&&_INTEGRAL_MAX_BITS>=64": // needed to define LONGLONG case "!defined SENTINEL_Reason": // reason.h //case "!defined(CTC_INVOKED)&&!defined(RGS_INVOKED)": //case "!defined(_DCOM_OA_REMOTING_)&&!defined(_DCOM_OC_REMOTING_)": //case "!defined(_DCOM_OA_REMOTING_)": //case "!defined(_DCOM_OC_REMOTING_)": case "_HRESULT_DEFINED": // case "_PALETTEENTRY_DEFINED": // case "_LOGPALETTE_DEFINED": case "_REFPOINTS_DEFINED": case "COMBOX_SANDBOX": // defined to avoid #define translation case "MAKE_HRESULT": case "CBPCLIPDATA": //case "FACILITY_ITF": case "PFN_TSHELL_TMP": case "V_INT_PTR": case "VT_INT_PTR": case "V_UINT_PTR": case "VT_UINT_PTR": case "PKGRESETFLAGS": case "VSLOCALREGISTRYROOTHANDLE_TO_HKEY": case "DTE": case "Project": case "ProjectItem": case "CodeModel": case "FileCodeModel": case "IDebugMachine2_V7": case "EnumMachines_V7": case "IEnumDebugMachines2_V7": case "IID_IEnumDebugMachines2_V7": // defined with both enum and #define in ipimb.h case "MIB_IPROUTE_TYPE_OTHER": case "MIB_IPROUTE_TYPE_INVALID": case "MIB_IPROUTE_TYPE_DIRECT": case "MIB_IPROUTE_TYPE_INDIRECT": case "NULL": case "VOID": case "CONST": case "CALLBACK": case "NOP_FUNCTION": case "DECLARE_HANDLE": case "STDMETHODCALLTYPE": case "STDMETHODVCALLTYPE": case "STDAPICALLTYPE": case "STDAPIVCALLTYPE": case "STDMETHODIMP": case "STDMETHODIMP_": case "STDOVERRIDEMETHODIMP": case "STDOVERRIDEMETHODIMP_": case "IFACEMETHODIMP": case "IFACEMETHODIMP_": case "STDMETHODIMPV": case "STDMETHODIMPV_": case "STDOVERRIDEMETHODIMPV": case "STDOVERRIDEMETHODIMPV_": case "IFACEMETHODIMPV": case "IFACEMETHODIMPV_": case "_WIN32_WINNT": case "GetLastError": case "MF_END": // defined twice in winuser.h, but said to be obsolete case "__int3264": return 1; case "_NO_SCRIPT_GUIDS": // used in activdbg.h, disable to avoid duplicate GUID definitions case "EnumStackFramesEx": // used in activdbg.h, but in wrong scope case "SynchronousCallIntoThread": // used in activdbg.h, but in wrong scope return 1; // winnt.h case "_WINDEF_": case "_WINBASE_": //if(vsi) // return 1; break; case "_WIN32": //if(!vsi) return 1; //break; // Windows SDK 8.0 case "_CONTRACT_GEN": return -1; default: break; } // header double include protection if(_endsWith(cond, "_DEFINED") || _endsWith(cond, "_INCLUDED") || _endsWith(cond, "_h__") || _endsWith(cond, "_H__") || _endsWith(cond, "_H_") || startsWith(cond, "_INC_") || _endsWith(cond, "_IDH")) return -1; if(cond == "_" ~ toUpper(currentModule) ~ "_") return -1; if(startsWith(cond, "WINAPI_FAMILY_PARTITION")) return 1; if(indexOf(cond, "(") < 0 && indexOf(cond, "|") < 0 && indexOf(cond, "&") < 0) { if (startsWith(cond, "CMD_ZOOM_")) return 1; cond = cond.replace(" ", ""); if(startsWith(cond, "WINVER>") || startsWith(cond, "_WIN32_WINNT>") || startsWith(cond, "NTDDI_VERSION>")) return 1; if(startsWith(cond, "WINVER<") || startsWith(cond, "_WIN32_WINNT<") || startsWith(cond, "NTDDI_VERSION<")) return -1; if(startsWith(cond, "_MSC_VER>") || startsWith(cond, "_MSC_FULL_VER>")) return -1; // disable all msc specials if(startsWith(cond, "_MSC_VER<") || startsWith(cond, "_MSC_FULL_VER<")) return 1; // disable all msc specials if(startsWith(cond, "_WIN32_IE>")) return 1; // assue newest IE if(startsWith(cond, "NO")) return -1; // used to disable parts, we want it all } return 0; } int findLogicalOp(string cond, string op) { int paren = 0; for(int i = 0; i <= cond.length - op.length; i++) { if(paren == 0 && cond[i .. i+op.length] == op) return i; if(cond[i] == '(') paren++; else if(cond[i] == ')') paren--; } return -1; } int preDefined(string cond) { int sign = 1; for( ; ; ) { int rc = _preDefined(cond); if(rc != 0) return sign * rc; if(startsWith(cond, "(") && _endsWith(cond, ")") && findLogicalOp(cond[1..$], ")") == cond.length - 2) cond = cond[1..$-1]; else if(startsWith(cond, "defined(") && findLogicalOp(cond[8..$], ")") == cond.length - 9) cond = cond[8..$-1]; else if(startsWith(cond, "!") && indexOf(cond[1..$-1], "&") < 0 && indexOf(cond[1..$-1], "|") < 0) { cond = cond[1..$]; sign = -sign; } else { int idx = findLogicalOp(cond, "||"); if(idx < 0) idx = findLogicalOp(cond, "&&"); if(idx >= 0) { int rc1 = preDefined(cond[0..idx]); int rc2 = preDefined(cond[idx+2..$]); if(cond[idx] == '|') return rc1 > 0 || rc2 > 0 ? 1 : rc1 < 0 && rc2 < 0 ? -1 : 0; else // '&' return rc1 > 0 && rc2 > 0 ? 1 : rc1 < 0 || rc2 < 0 ? -1 : 0; } break; } } return 0; } int preDefined(TokenIterator start, TokenIterator end) { string txt = tokenListToString(start, end, false, true); int rc = preDefined(txt); if(rc == 0 && verbose) writefln("\"" ~ txt ~ "\" not defined/undefined"); return rc; } void handleCondition(TokenIterator tokIt, TokenIterator lastIt, string pp) { string elif_braces; int predef = preDefined(tokIt + 1, lastIt + 1); if(pp == "pp_ifndef") predef = -predef; if(predef < 0) { string ver = (predef == -4 ? "Win32" : "none"); tokIt.text = "version(" ~ ver ~ ") /* " ~ tokIt.text; lastIt.text ~= " */ {/+"; elif_braces = "+/} "; } else if(predef > 0) { string ver = (predef == 4 ? "Win64" : "all"); tokIt.text = "version(" ~ ver ~ ") /* " ~ tokIt.text; lastIt.text ~= " */ {"; elif_braces = "} "; } else { version(static_if_to_version) { string cond = pp; version(remove_pp) if(pp == "pp_ifndef") cond = "all"; tokIt.text = "version(" ~ cond ~ ") /* " ~ tokIt.text; lastIt.text ~= " */ {"; } else { tokIt.text = "static if(" ~ pp ~ "(r\""; tokIt[1].pretext = ""; lastIt.text ~= "\")) {"; } elif_braces = "} "; } if(pp == "pp_elif") { tokIt.text = elif_braces_stack[$-1] ~ "else " ~ tokIt.text; elif_braces_stack[$-1] = elif_braces; } else { elif_braces_stack ~= elif_braces; pp_enable_stack ~= true; } } bool inDisabledPPBranch() { foreach (string s; elif_braces_stack) if(startsWith(s, "+/")) return true; return false; } string convertPP(string text, int lineno, bool inEnum) { version(remove_pp) {} else if(inEnum) return "// " ~ text; TokenList tokens = scanText(text, lineno, false); TokenIterator tokIt = tokens.begin(); TokenIterator lastIt = tokens.end() - 1; if(lastIt.type == Token.EOF) --lastIt; switch(tokIt.text) { case "#include": tokIt.text = "public import"; if(tokIt[1].type == Token.String) tokIt[1].text = fixImport(tokIt[1].text) ~ ";"; else if(tokIt[1].text == "<") { string inc; TokenIterator it = tokIt + 2; for( ; !it.atEnd() && it.text != ">"; it.erase()) inc ~= it.pretext ~ it.text; tokIt[1].text = fixImport(inc); if(!it.atEnd()) it.text = ";"; } break; case "#if": handleCondition(tokIt, lastIt, "pp_if"); break; case "#ifndef": handleCondition(tokIt, lastIt, "pp_ifndef"); break; case "#ifdef": handleCondition(tokIt, lastIt, "pp_ifdef"); break; case "#endif": if(pp_enable_stack.length == 0) throwException(tokIt.lineno, "unbalanced #endif"); bool enabled = pp_enable_stack[$-1]; pp_enable_stack = pp_enable_stack[0 .. $-1]; if(!enabled) tokIt.pretext = "+/" ~ tokIt.pretext; version(remove_pp) tokIt.text = elif_braces_stack[$-1] ~ "\n"; else tokIt.text = elif_braces_stack[$-1] ~ "// " ~ tokIt.text; elif_braces_stack = elif_braces_stack[0 .. $-1]; break; case "#else": if(pp_enable_stack.length == 0) throwException(tokIt.lineno, "unbalanced #else"); if(!pp_enable_stack[$-1]) { tokIt.pretext = "+/" ~ tokIt.pretext; pp_enable_stack[$-1] = true; } if(elif_braces_stack[$-1].startsWith("+/")) { version(remove_pp) tokIt.text = "+/} else {\n"; else tokIt.text = "+/} else { // " ~ tokIt.text; elif_braces_stack[$-1] = elif_braces_stack[$-1][2..$]; } else { version(remove_pp) tokIt.text = "} else {\n"; else tokIt.text = "} else { // " ~ tokIt.text; } break; case "#elif": if(pp_enable_stack.length == 0) throwException(tokIt.lineno, "unbalanced #elif"); if(!pp_enable_stack[$-1]) { tokIt.pretext = "+/" ~ tokIt.pretext; pp_enable_stack[$-1] = true; } handleCondition(tokIt, lastIt, "pp_elif"); //tokIt[1].pretext = ""; //lastIt.text ~= "\")) {"; break; case "#define": convertDefine(tokIt); break; default: return "// " ~ text; } string txt = tokenListToString(tokens); return txt; } bool convertDefine(ref TokenIterator tokIt) { // tokIt on "#define" bool convert = true; bool predef = false; bool convertMacro = false; string argtype; string rettype; TokenIterator it = tokIt + 1; string ident = it.text; for( ; !it.atEnd(); ++it) {} version(none){ if(indexOf(it.pretext, "\\\n") >= 0) { convert = false; it.pretext = replace(it.pretext, "\\\n", "\\\n//"); } // if(indexOf(it.pretext, '\n') >= 0) // break; } TokenIterator endIt = it; if(it[-1].type == Token.EOF) --endIt; int preDefType = preDefined(ident); if(ident in disabled_defines) predef = true; else if (preDefType == 3) { predef = true; convert = false; } else if (preDefType == 1 || preDefined("_" ~ ident ~ "_DEFINED") == 1) predef = true; else if(tokIt[2].text == "(" && tokIt[2].pretext.length == 0) { convert = false; if(tokIt[3].text == ")") { convertMacro = true; argtype = ""; if(isExpression(tokIt + 4, endIt)) rettype = getExpressionType(ident, tokIt + 4, endIt); else rettype = "void"; } if(tokIt[3].type == Token.Identifier && tokIt[4].text == ")" && isExpression(tokIt + 5, endIt)) { convertMacro = true; rettype = getExpressionType(ident, tokIt + 5, endIt); argtype = getArgumentType(ident, tokIt + 5, endIt, rettype); } } else if(ident.startsWith("CF_VS")) { convertMacro = true; rettype = "UINT"; } else if(!isExpression(tokIt + 2, endIt)) convert = false; else if(string* m = ident in converted_defines) if(*m != currentModule) predef = true; if((!convert && !convertMacro) || it[-1].text == "\\" || predef) { tokIt.pretext ~= "// "; convert = false; } if(convertMacro) { TokenIterator lastit = endIt; version(macro2template) tokIt.text = "auto"; else tokIt.text = rettype; string ret = (rettype != "void" ? "return " : ""); if(argtype.length) { version(macro2template) tokIt[3].pretext ~= "ARG)(ARG "; else tokIt[3].pretext ~= argtype ~ " "; tokIt[5].pretext ~= "{ " ~ ret; lastit = tokIt + 5; } else if(tokIt[2].text != "(" || tokIt[2].pretext != "") { tokIt[2].pretext = "() { " ~ ret ~ tokIt[2].pretext; lastit = tokIt + 2; } else { tokIt[4].pretext = " { " ~ ret ~ tokIt[4].pretext; lastit = tokIt + 4; } if(lastit == endIt) // empty? endIt.text ~= " }"; else endIt[-1].text ~= "; }"; if(!inDisabledPPBranch()) converted_defines[ident] = currentModule; } else if(convert) { if(it != tokIt + 1 && it != tokIt + 2 && it != tokIt + 3) { if(endIt == tokIt + 3 && tokIt[2].type == Token.Identifier && !(tokIt[2].text in enums) && tokIt[2].text != "NULL") { if(tokIt[2].text in disabled_defines) tokIt.pretext ~= "// "; tokIt.text = "alias"; tokIt[1].text = tokIt[2].text; tokIt[2].text = ident; } else { tokIt.text = "denum"; (tokIt+2).insertBefore(createToken(" ", "=", Token.Assign, tokIt.lineno)); if(ident.startsWith("uuid_")) { tokIt.insertAfter(createToken(" ", "GUID", Token.Identifier, tokIt.lineno)); tokIt[4].pretext ~= "uuid(\""; endIt[-1].text ~= "\")"; } else if(ident.startsWith("SID_S") || ident.startsWith("guid")) { tokIt.insertAfter(createToken(" ", "GUID", Token.Identifier, tokIt.lineno)); } // winnt.h else if(ident.startsWith("SECURITY_") && tokIt[3].text == "{" && tokIt[15].text == "}") { tokIt.insertAfter(createToken(" ", "SID_IDENTIFIER_AUTHORITY", Token.Identifier, tokIt.lineno)); tokIt[4].text = "{["; tokIt[16].text = "]}"; } else if(_endsWith(ident, "_LUID") && tokIt[3].text == "{") { tokIt.insertAfter(createToken(" ", "LUID", Token.Identifier, tokIt.lineno)); } } } else tokIt.pretext ~= "// "; Token tok = createToken("", ";", Token.Comma, tokIt.lineno); endIt.insertBefore(tok); if(!inDisabledPPBranch()) converted_defines[ident] = currentModule; } else if (!predef) disabled_defines[ident] = 1; string repl = (convert || convertMacro ? "\n" : "\\\n//"); for(it = tokIt; !it.atEnd(); ++it) if(indexOf(it.pretext, "\\\n") >= 0) it.pretext = replace(it.pretext, "\\\n", repl); tokIt = it - 1; return convert || convertMacro; } void disable_macro(ref TokenIterator tokIt) { TokenIterator it = tokIt + 1; if(it.text == "(") { if(!advanceToClosingBracket(it)) return; } version(all) { tokIt.insertBefore(createToken("", "/", Token.Div, tokIt.lineno)); tokIt.insertBefore(createToken("", "+", Token.Plus, tokIt.lineno)); tokIt[-2].pretext = tokIt.pretext; tokIt.pretext = " "; it.insertBefore(createToken(" ", "+", Token.Plus, tokIt.lineno)); it.insertBefore(createToken("", "/", Token.Div, tokIt.lineno)); tokIt = it - 1; } else { tokIt.pretext ~= "/+"; it[-1].text ~= "+/"; // it.pretext = "+/" ~ it.pretext; tokIt = it - 1; } } void replaceExpressionTokens(TokenList tokens) { //replaceTokenSequence(tokens, "= (", "= cast(", true); replaceTokenSequence(tokens, "$_not $_ident($_ident1)$_ident2", "$_not cast($_ident1)$_ident2", true); replaceTokenSequence(tokens, "$_not $_ident($_ident1)$_num2", "$_not cast($_ident1)$_num2", true); replaceTokenSequence(tokens, "$_not $_ident($_ident1)-$_num2", "$_not cast($_ident1)-$_num2", true); replaceTokenSequence(tokens, "$_not $_ident($_ident1)~", "$_not cast($_ident1)~", true); while(replaceTokenSequence(tokens, "$_not $_ident($_ident1)($expr)", "$_not cast($_ident1)($expr)", true) > 0) {} replaceTokenSequence(tokens, "$_not $_ident($_ident1)cast", "$_not cast($_ident1)cast", true); replaceTokenSequence(tokens, "$_not $_ident($_ident1*)$_not_semi;", "$_not cast($_ident1*)$_not_semi", true); replaceTokenSequence(tokens, "$_not $_ident(struct $_ident1*)$_not_semi;", "$_not cast(struct $_ident1*)$_not_semi", true); replaceTokenSequence(tokens, "$_not $_ident($_ident1 $_ident2*)", "$_not cast($_ident1 $_ident2*)", true); replaceTokenSequence(tokens, "HRESULT cast", "HRESULT", true); replaceTokenSequence(tokens, "extern cast", "extern", true); replaceTokenSequence(tokens, "!cast", "!", true); replaceTokenSequence(tokens, "reinterpret_cast<$_ident>", "cast($_ident)", true); replaceTokenSequence(tokens, "reinterpret_cast<$_ident*>", "cast($_ident*)", true); replaceTokenSequence(tokens, "const_cast<$_ident*>", "cast($_ident*)", true); } string translateModuleName(string name) { name = toLower(name); if(name == "version" || name == "shared" || name == "align") return keywordPrefix ~ name; return name; } string translatePackageName(string fname) { return fname.replace("\\shared\\", "\\").replace("\\um\\", "\\"); } string translateFilename(string fname) { string name = getNameWithoutExt(fname); string nname = translateModuleName(name); if(name == nname) return translatePackageName(fname); string dir = dirName(fname); if(dir == ".") dir = ""; else dir ~= "\\"; string ext = extension(fname); return translatePackageName(dir ~ nname ~ ext); } string _fixImport(string text) { text = replace(text, "/", "\\"); text = replace(text, "\"", ""); text = toLower(getNameWithoutExt(text)); string ntext = translateFilename(text); string name = translateModuleName(text); foreach(string file; srcfiles) { if(translateModuleName(getNameWithoutExt(file)) == name) { if(file.startsWith(win_path)) return packageWin ~ ntext; else return packageVSI ~ ntext; } } return packageNF ~ ntext; } string fixImport(string text) { string imp = _fixImport(text); currentImports.addunique(imp); return imp; } void convertGUID(TokenIterator tokIt) { // tokIt after "{" static bool numberOrIdent(Token tok) { return tok.type == Token.Identifier || tok.type == Token.Number; } static string toByteArray(string txt) { string ntxt; for(int i = 0; i + 1 < txt.length; i += 2) { if(i > 0) ntxt ~= ","; ntxt ~= "0x" ~ txt[i .. i + 2]; } return ntxt; } if (numberOrIdent(tokIt[0]) && tokIt[1].text == "-" && numberOrIdent(tokIt[2]) && tokIt[3].text == "-" && numberOrIdent(tokIt[4]) && tokIt[5].text == "-" && numberOrIdent(tokIt[6]) && tokIt[7].text == "-" && numberOrIdent(tokIt[8]) && tokIt[9].text == "}" && tokIt[8].text.length == 12) { // 00020405-0000-0000-C000-000000000046 tokIt[0].text = "0x" ~ tokIt[0].text; tokIt[1].text = ","; tokIt[2].text = "0x" ~ tokIt[2].text; tokIt[3].text = ","; tokIt[4].text = "0x" ~ tokIt[4].text; tokIt[5].text = ","; tokIt[6].text = "[ " ~ toByteArray(tokIt[6].text); tokIt[7].text = ","; tokIt[8].text = toByteArray(tokIt[8].text) ~ " ]"; } else if (tokIt[0].type == Token.Identifier && tokIt[1].text == "}") { // simple identifer defined elsewhere tokIt[-1].text = ""; tokIt[1].text = ""; } else if (tokIt[0].type == Token.Number && tokIt[1].text == "," && tokIt[2].type == Token.Number && tokIt[3].text == "," && tokIt[4].type == Token.Number && tokIt[5].text == ",") { // 0x0c539790, 0x12e4, 0x11cf, 0xb6, 0x61, 0x00, 0xaa, 0x00, 0x4c, 0xd6, 0xd8 if(tokIt[6].text == "{") { tokIt[6].pretext ~= "["; // use pretext to avoid later substitution tokIt[6].text = ""; tokIt[22].pretext ~= "]"; tokIt[22].text = ""; } else if(tokIt[6].text != "[") { int i; for(i = 0; i < 8; i++) if(tokIt[5 + 2*i].text != "," || tokIt[6 + 2*i].type != Token.Number) break; if (i >= 8) { tokIt[6].pretext = " [" ~ tokIt[6].pretext; tokIt[21].pretext = " ]" ~ tokIt[21].pretext; } } } else if(tokIt.type == Token.String) { string txt = tokIt.text; // "af855397-c4dc-478b-abd4-c3dbb3759e72" if(txt.length == 38 && txt[9] == '-' && txt[14] == '-' && txt[19] == '-' && txt[24] == '-') { tokIt.text = "0x" ~ txt[1..9] ~ ", 0x" ~ txt[10..14] ~ ", 0x" ~ txt[15..19] ~ ", [ " ~ "0x" ~ txt[20..22] ~ ", 0x" ~ txt[22..24]; for(int i = 0; i < 6; i++) tokIt.text ~= ", 0x" ~ txt[25 + 2*i .. 27 + 2*i]; tokIt.text ~= " ]"; } } else { tokIt.pretext ~= "\""; while(tokIt.text != "}") { ++tokIt; if(tokIt.atEnd()) return; } tokIt.pretext = "\"" ~ tokIt.pretext; } } string convertText(TokenList tokens) { string prevtext; int braceCount; int parenCount; int brackCount; int enumLevel = -1; //replaceTokenSequence(tokens, "enum Kind { $enums ;", "class Kind { /+ $enums; +/", false); // do some preprocessor replacements to make the text bracket-balanced if(currentModule == "oaidl") { replaceTokenSequence(tokens, "__VARIANT_NAME_1", "", true); replaceTokenSequence(tokens, "__VARIANT_NAME_2", "", true); replaceTokenSequence(tokens, "__VARIANT_NAME_3", "", true); replaceTokenSequence(tokens, "__VARIANT_NAME_4", "", true); } if(currentModule == "windef") { // avoid removal of #define TRUE 1 replaceTokenSequence(tokens, "#ifndef TRUE\n#define TRUE$def\n#endif\n", "#define TRUE 1\n", false); } if(currentModule == "winnt") { replaceTokenSequence(tokens, "#if defined(MIDL_PASS)\ntypedef struct $_ident {\n" ~ "#else$comment_else\n$else\n#endif$comment_endif", "$else", false); // remove int64 operations replaceTokenSequence(tokens, "#if defined(MIDL_PASS)$if_more\n#define Int32x32To64$def_more\n$defines\n" ~ "#error Must define a target architecture.\n#endif\n", "/+\n$*\n+/", false); // remove rotate operations replaceTokenSequence(tokens, "#define RotateLeft8$def_more\n$defines\n" ~ "#pragma intrinsic(_rotr16)\n", "/+\n$*\n+/", false); replaceTokenSequence(tokens, "typedef struct DECLSPEC_ALIGN($_num)", "align($_num) typedef struct", true); replaceTokenSequence(tokens, "typedef union DECLSPEC_ALIGN($_num)", "align($_num) typedef union", true); replaceTokenSequence(tokens, "struct DECLSPEC_ALIGN($_num)", "align($_num) struct", true); // win 8.1: remove template _ENUM_FLAG_INTEGER_FOR_SIZE replaceTokenSequence(tokens, "template $args _ENUM_FLAG_INTEGER_FOR_SIZE;", "/*$0*/", true); replaceTokenSequence(tokens, "template <> struct _ENUM_FLAG_INTEGER_FOR_SIZE <$arg> { $def };", "/*$0*/", true); replaceTokenSequence(tokens, "template <$arg> struct _ENUM_FLAG_SIZED_INTEGER { $def };", "/*$0*/", true); } if(currentModule == "commctrl") { // typos replaceTokenSequence(tokens, "PCCOMBOEXITEMW", "PCCOMBOBOXEXITEMW", true); replaceTokenSequence(tokens, "LPTBSAVEPARAMW", "LPTBSAVEPARAMSW", true); } if(currentModule == "oleauto") { replaceTokenSequence(tokens, "WINOLEAUTAPI_($_rettype)", "extern(Windows) $_rettype", true); replaceTokenSequence(tokens, "WINOLEAUTAPI", "extern(Windows) HRESULT", true); } if(currentModule == "shellapi") { replaceTokenSequence(tokens, "SHSTDAPI_($_rettype)", "extern(Windows) $_rettype", true); replaceTokenSequence(tokens, "SHSTDAPI", "extern(Windows) HRESULT", true); replaceTokenSequence(tokens, "LWSTDAPIV_($_rettype)", "extern(Windows) $_rettype", true); } replaceTokenSequence(tokens, "STDAPI_($_rettype)", "extern(Windows) $_rettype", true); replaceTokenSequence(tokens, "STDAPI", "extern(Windows) HRESULT", true); replaceTokenSequence(tokens, "STDMETHODCALLTYPE", "extern(Windows)", true); replaceTokenSequence(tokens, "STDAPICALLTYPE", "extern(Windows)", true); replaceTokenSequence(tokens, "WINOLEAPI_($_rettype)", "extern(Windows) $_rettype", true); replaceTokenSequence(tokens, "WINOLEAPI", "extern(Windows) HRESULT", true); replaceTokenSequence(tokens, "$_ident WINAPIV", "extern(C) $_ident", true); replaceTokenSequence(tokens, "RPCRTAPI", "export", true); replaceTokenSequence(tokens, "RPC_STATUS", "int", true); replaceTokenSequence(tokens, "RPC_ENTRY", "extern(Windows)", true); replaceTokenSequence(tokens, "__RPC_USER", "extern(Windows)", true); replaceTokenSequence(tokens, "__RPC_STUB", "extern(Windows)", true); replaceTokenSequence(tokens, "__RPC_API", "extern(Windows)", true); replaceTokenSequence(tokens, "RPC_MGR_EPV", "void", true); replaceTokenSequence(tokens, "__RPC_FAR", "", true); replaceTokenSequence(tokens, "POINTER_32", "", true); replaceTokenSequence(tokens, "POINTER_64", "", true); replaceTokenSequence(tokens, "UNREFERENCED_PARAMETER($arg);", "/*UNREFERENCED_PARAMETER($arg);*/", true); if(currentModule == "rpcdce") { replaceTokenSequence(tokens, "RPC_INTERFACE_GROUP_IDLE_CALLBACK_FN($args);", "function($args) RPC_INTERFACE_GROUP_IDLE_CALLBACK_FN;", true); } // windef.h and ktmtypes.h replaceTokenSequence(tokens, "UOW UOW;", "UOW uow;", true); // enc.idl (FIELD_OFFSET already defined in winnt.h) replaceTokenSequence(tokens, "typedef struct _FIELD_OFFSET { $data } FIELD_OFFSET;", "struct _FIELD_OFFSET { $data };", true); // IP_DEST_PORT_UNREACHABLE defined twice if(currentModule == "ipexport") { replaceTokenSequence(tokens, "#define IP_DEST_PORT_UNREACHABLE (IP_STATUS_BASE + 5)\n" "#define IP_HOP_LIMIT_EXCEEDED (IP_STATUS_BASE + 13)\n", "#define IP_HOP_LIMIT_EXCEEDED (IP_STATUS_BASE + 13)\n", false); } if(currentModule == "nldef") { // expand MAKE_ROUTE_PROTOCOL replaceTokenSequence(tokens, "MAKE_ROUTE_PROTOCOL($_ident,$_num),", "MIB_IPPROTO_ __ $_ident = $_num, PROTO_IP_ __ $_ident = $_num,", true); } if(currentModule == "iphlpapi") { // imports inside extern(C) {} replaceTokenSequence(tokens, "extern \"C\" { $_data }", "$_data", true); } // select unicode version of the API when defining without postfix A/W replaceTokenSequence(tokens, "#ifdef UNICODE\nreturn $_identW(\n#else\nreturn $_identA(\n#endif\n", " return $_identW(", false); replaceTokenSequence(tokens, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n", "extern \"C\" {\n", false); replaceTokenSequence(tokens, "#ifdef defined(__cplusplus)\nextern \"C\" {\n#endif\n", "extern \"C\" {\n", false); replaceTokenSequence(tokens, "#ifdef defined __cplusplus\nextern \"C\" {\n#endif\n", "extern \"C\" {\n", false); replaceTokenSequence(tokens, "#ifdef __cplusplus\n}\n#endif\n", "}\n", false); for(TokenIterator tokIt = tokens.begin(); tokIt != tokens.end; ) { Token tok = *tokIt; switch(tok.text) { case "(": parenCount++; break; case ")": parenCount--; break; case "[": brackCount++; break; case "]": brackCount--; break; case "{": braceCount++; break; case "}": braceCount--; if(braceCount <= enumLevel) enumLevel = -1; break; case "enum": enumLevel = braceCount; break; case ";": enumLevel = -1; break; case "importlib": if(tokIt[1].text == "(" && tokIt[2].type == Token.String && tokIt[3].text == ")") { tokIt.text = "import"; tokIt[1].text = ""; tokIt[2].pretext = " "; tokIt[2].text = fixImport(tokIt[2].text); tokIt[3].text = ""; } break; case "import": if(tokIt[1].type == Token.String) { tokIt.pretext ~= "public "; tokIt[1].text = fixImport(tokIt[1].text); } break; case "midl_pragma": comment_line(tokIt); continue; case "cpp_quote": //reinsert_cpp_quote(tokIt); if(handle_cpp_quote(tokIt, enumLevel >= 0)) continue; break; case "version": case "align": case "package": case "function": if(tokIt[1].text != "(") tok.text = keywordPrefix ~ tok.text; break; case "unsigned": { string t; bool skipNext = true; switch(tokIt[1].text) { case "__int64": t = "ulong"; break; case "long": t = "uint"; break; case "int": t = "uint"; break; case "__int32": t = "uint"; break; case "__int3264": t = "uint"; break; case "short": t = "ushort"; break; case "char": t = "ubyte"; break; default: t = "uint"; skipNext = false; break; } tok.text = t; if(skipNext) (tokIt + 1).erase(); break; } case "signed": { string t; bool skipNext = true; switch(tokIt[1].text) { case "__int64": t = "long"; break; case "long": t = "int"; break; case "int": t = "int"; break; case "__int32": t = "int"; break; case "__int3264": t = "int"; break; case "short": t = "short"; break; case "char": t = "byte"; break; default: t = "int"; skipNext = false; break; } tok.text = t; if(skipNext) (tokIt + 1).erase(); break; } // Windows SDK 8.0 => 7.1 case "_Null_terminated_": tok.text = "__nullterminated"; break; case "_NullNull_terminated_": tok.text = "__nullnullterminated"; break; case "_Success_": tok.text = "__success"; break; case "_In_": tok.text = "__in"; break; case "_Inout_": tok.text = "__inout"; break; case "_In_opt_": tok.text = "__in_opt"; break; case "_Inout_opt_": tok.text = "__inout_opt"; break; case "_Inout_z_": tok.text = "__inout_z"; break; case "_Deref_out_": tok.text = "__deref_out"; break; case "_Out_": tok.text = "__out"; break; case "_Out_opt_": tok.text = "__out_opt"; break; case "_Field_range_": tok.text = "__range"; break; case "_Field_size_": tok.text = "__field_ecount"; break; case "_Field_size_opt_": tok.text = "__field_ecount_opt"; break; case "_Field_size_bytes_": tok.text = "__field_bcount"; break; case "_Field_size_bytes_opt_":tok.text = "__field_bcount_opt"; break; default: if(tok.type == Token.Macro && tok.text.startsWith("$")) tok.text = "_d_" ~ tok.text[1..$]; else if(tok.type == Token.Number && (tok.text._endsWith("l") || tok.text._endsWith("L"))) tok.text = tok.text[0..$-1]; else if(tok.type == Token.Number && tok.text._endsWith("i64")) tok.text = tok.text[0..$-3] ~ "L"; else if(tok.type == Token.Number && tok.text._endsWith("UI64")) tok.text = tok.text[0..$-4] ~ "UL"; else if(tok.type == Token.String && tok.text.startsWith("L\"")) tok.text = tok.text[1..$] ~ "w.ptr"; else if(tok.type == Token.String && tok.text.startsWith("L\'")) tok.text = tok.text[1..$]; else if(tok.text.startsWith("#")) { string txt = convertPP(tok.text, tok.lineno, enumLevel >= 0); reinsertTextTokens(tokIt, txt); continue; } else if(tok.text in disabled_defines) disable_macro(tokIt); else if(parenCount > 0) { // in function argument //if(tok.text == "const" || tok.text == "CONST") // tok.text = "/*const*/"; //else if (tok.text.startsWith("REF") && tok.text != "REFSHOWFLAGS" && !tok.text.startsWith("REFERENCE")) { tokIt.insertBefore(createToken(tok.pretext, "ref", Token.Identifier, tokIt.lineno)); tok.pretext = " "; tok.text = tok.text[3..$]; } } else if(tok.type == Token.Identifier && enumLevel >= 0 && (tokIt[-1].text == "{" || tokIt[-1].text == ",")) enums[tok.text] = true; break; } prevtext = tok.text; ++tokIt; } version(none) version(vsi) { // wtypes.idl: replaceTokenSequence(tokens, "typedef ubyte UCHAR;", "typedef ubyte idl_UCHAR;", true); replaceTokenSequence(tokens, "typedef short SHORT;", "typedef short idl_SHORT;", true); replaceTokenSequence(tokens, "typedef ushort USHORT;", "typedef ushort idl_USHORT;", true); replaceTokenSequence(tokens, "typedef DWORD ULONG;", "typedef DWORD idl_ULONG;", true); replaceTokenSequence(tokens, "typedef double DOUBLE;", "typedef double idl_DOUBLE;", true); replaceTokenSequence(tokens, "typedef char OLECHAR;", "typedef char idl_OLECHAR;", true); replaceTokenSequence(tokens, "typedef LPSTR LPOLESTR;", "typedef LPSTR idl_LPOLESTR;", true); replaceTokenSequence(tokens, "typedef LPCSTR LPCOLESTR;", "typedef LPCSTR idl_LPCOLESTR;", true); replaceTokenSequence(tokens, "WCHAR OLECHAR;", "WCHAR idl_OLECHAR;", true); replaceTokenSequence(tokens, "OLECHAR *LPOLESTR;", "OLECHAR *idl_LPOLESTR;", true); replaceTokenSequence(tokens, "const OLECHAR *LPCOLESTR;", "OLECHAR *idl_LPCOLESTR;", true); replaceTokenSequence(tokens, "typedef LONG SCODE;", "typedef LONG vsi_SCODE;", true); } //replaceTokenSequence(tokens, "interface IWinTypes { $data }", // "/+interface IWinTypes {+/\n$data\n/+ } /+IWinTypes+/ +/", true); // docobj.idl (v6.0a) if(currentModule == "docobj") { replaceTokenSequence(tokens, "OLECMDIDF_REFRESH_PROMPTIFOFFLINE = 0x2000, OLECMDIDF_REFRESH_THROUGHSCRIPT = 0x4000 $_not,", "OLECMDIDF_REFRESH_PROMPTIFOFFLINE = 0x2000,\nOLECMDIDF_REFRESH_THROUGHSCRIPT = 0x4000, $_not", true); replaceTokenSequence(tokens, "OLECMDIDF_REFRESH_PROMPTIFOFFLINE = 0x2000 $_not,", "OLECMDIDF_REFRESH_PROMPTIFOFFLINE = 0x2000, $_not", true); // win SDK 8.1: double define replaceTokenSequence(tokens, "typedef struct tagPAGESET {} PAGESET;", "", true); } //vsshell.idl if(currentModule == "vsshell") { replaceTokenSequence(tokens, "typedef DWORD PFN_TSHELL_TMP;", "typedef PfnTshell PFN_TSHELL_TMP;", true); replaceTokenSequence(tokens, "MENUEDITOR_TRANSACTION_ALL,", "MENUEDITOR_TRANSACTION_ALL = 0,", true); replaceTokenSequence(tokens, "SCC_STATUS_INVALID = -1L,", "SCC_STATUS_INVALID = cast(DWORD)-1L,", true); } if(currentModule == "vsshell80") { replaceTokenSequence(tokens, "MENUEDITOR_TRANSACTION_ALL,", "MENUEDITOR_TRANSACTION_ALL = 0,", true); // overflow from -1u } // vslangproj90.idl if(currentModule == "vslangproj90") replaceTokenSequence(tokens, "CsharpProjectConfigurationProperties3", "CSharpProjectConfigurationProperties3", true); if(currentModule == "msdbg") replaceTokenSequence(tokens, "const DWORD S_UNKNOWN = 0x3;", "denum DWORD S_UNKNOWN = 0x3;", true); if(currentModule == "activdbg") replaceTokenSequence(tokens, "const THREAD_STATE", "denum THREAD_STATE", true); if(currentModule == "objidl") { replaceTokenSequence(tokens, "const OLECHAR *COLE_DEFAULT_PRINCIPAL", "denum const OLECHAR *COLE_DEFAULT_PRINCIPAL", true); replaceTokenSequence(tokens, "const void *COLE_DEFAULT_AUTHINFO", "denum const void *COLE_DEFAULT_AUTHINFO", true); } if(currentModule == "combaseapi") { replaceTokenSequence(tokens, "typedef enum CWMO_FLAGS", "typedef enum tagCWMO_FLAGS", true); } if(currentModule == "lmcons") { replaceTokenSequence(tokens, "alias NERR_BASE MIN_LANMAN_MESSAGE_ID;", "enum MIN_LANMAN_MESSAGE_ID = 2100;", true); // missing lmerr.h } if(currentModule == "winnt") { // Win SDK 8.1: remove translation to intrinsics replaceTokenSequence(tokens, "alias _InterlockedAnd InterlockedAnd;", "/+ $*", true); replaceTokenSequence(tokens, "InterlockedCompareExchange($args __in LONG ExChange, __in LONG Comperand);", "$* +/", true); replaceTokenSequence(tokens, "InterlockedOr(&Barrier, 0);", "InterlockedExchangeAdd(&Barrier, 0);", true); // InterlockedOr exist only as intrinsic } if(currentModule == "ocidl") { // move alias out of interface declaration, it causes circular definitions with dmd 2.065+ replaceTokenSequence(tokens, "interface IOleUndoManager : IUnknown { alias IID_IOleUndoManager SID_SOleUndoManager; $data }", "interface IOleUndoManager : IUnknown { $data }\n\nalias IID_IOleUndoManager SID_SOleUndoManager;", true); } replaceTokenSequence(tokens, "extern const __declspec(selectany)", "dconst", true); replaceTokenSequence(tokens, "EXTERN_C $args;", "/+EXTERN_C $args;+/", true); replaceTokenSequence(tokens, "SAFEARRAY($args)", "SAFEARRAY/*($args)*/", true); // remove forward declarations replaceTokenSequence(tokens, "enum $_ident;", "/+ enum $_ident; +/", true); replaceTokenSequence(tokens, "struct $_ident;", "/+ struct $_ident; +/", true); replaceTokenSequence(tokens, "class $_ident;", "/+ class $_ident; +/", true); replaceTokenSequence(tokens, "interface $_ident;", "/+ interface $_ident; +/", true); replaceTokenSequence(tokens, "dispinterface $_ident;", "/+ dispinterface $_ident; +/", true); replaceTokenSequence(tokens, "coclass $_ident;", "/+ coclass $_ident; +/", true); replaceTokenSequence(tokens, "library $_ident {", "version(all)\n{ /+ library $_ident +/", true); replaceTokenSequence(tokens, "importlib($expr);", "/+importlib($expr);+/", true); version(remove_pp) { string tsttxt = tokenListToString(tokens); while(replaceTokenSequence(tokens, "$_note else version(all) { $if } else { $else }", "$_note $if", true) > 0 || replaceTokenSequence(tokens, "$_note else version(all) { $if } else version($ver) { $else_ver } else { $else }", "$_note $if", true) > 0 || replaceTokenSequence(tokens, "$_note else version(all) { $if } $_not else", "$_note $if\n$_not", true) > 0 || replaceTokenSequence(tokens, "$_note else version(none) { $if } else { $else }", "$_note $else", true) > 0 || replaceTokenSequence(tokens, "$_note else version(none) { $if } $_not else", "$_note $_not", true) > 0 || replaceTokenSequence(tokens, "version(pp_if) { $if } else { $else }", "$else", true) > 0 || replaceTokenSequence(tokens, "version(pp_if) { $if } $_not else", "$_not", true) > 0 || replaceTokenSequence(tokens, "version(pp_ifndef) { $if } else { $else }", "$if", true) > 0 || replaceTokenSequence(tokens, "version(pp_ifndef) { $if } $_not else", "$if\n$_not", true) > 0) { string rtsttxt = tokenListToString(tokens); } string ntsttxt = tokenListToString(tokens); } while(replaceTokenSequence(tokens, "static if($expr) { } else { }", "", true) > 0 || replaceTokenSequence(tokens, "static if($expr) { } $_not else", "$_not", true) > 0 || replaceTokenSequence(tokens, "version($expr) { } else { }", "", true) > 0 || replaceTokenSequence(tokens, "version($expr) { } $_not else", "$_not", true) > 0) {} // move declaration at the top of the interface below the interface while keeping the order replaceTokenSequence(tokens, "interface $_ident1 : $_identbase { $data }", "interface $_ident1 : $_identbase { $data\n} __eo_interface", true); while(replaceTokenSequence(tokens, "interface $_ident1 : $_identbase { typedef $args; $data } $tail __eo_interface", "interface $_ident1 : $_identbase\n{ $data\n}\n$tail\ntypedef $args; __eo_interface", true) > 0 || replaceTokenSequence(tokens, "interface $_ident1 : $_identbase { denum $args; $data } $tail __eo_interface", "interface $_ident1 : $_identbase\n{ $data\n}\n$tail\ndenum $args; __eo_interface", true) > 0 || replaceTokenSequence(tokens, "interface $_ident1 : $_identbase { enum $args; $data } $tail __eo_interface", "interface $_ident1 : $_identbase\n{ $data\n}\n$tail\nenum $args; __eo_interface", true) > 0 || replaceTokenSequence(tokens, "interface $_ident1 : $_identbase { dconst $_ident = $expr; $data } $tail __eo_interface", "interface $_ident1 : $_identbase\n{ $data\n}\n$tail\ndconst $_ident = $expr; __eo_interface", true) > 0 || replaceTokenSequence(tokens, "interface $_ident1 : $_identbase { const $_identtype $_ident = $expr; $data } $tail __eo_interface", "interface $_ident1 : $_identbase\n{ $data\n}\n$tail\nconst $_identtype $_ident = $expr; __eo_interface", true) > 0 || replaceTokenSequence(tokens, "interface $_ident1 : $_identbase { const $_identtype *$_ident = $expr; $data } $tail __eo_interface", "interface $_ident1 : $_identbase\n{ $data\n}\n$tail\nconst $_identtype *$_ident = $expr; __eo_interface", true) > 0 || replaceTokenSequence(tokens, "interface $_ident1 : $_identbase { struct $args; $data } $tail __eo_interface", "interface $_ident1 : $_identbase\n{ $data\n}\n$tail\nstruct $args; __eo_interface", true) > 0 || replaceTokenSequence(tokens, "interface $_ident1 : $_identbase { union $args; $data } $tail __eo_interface", "interface $_ident1 : $_identbase\n{ $data\n}\n$tail\nunion $args; __eo_interface", true) > 0 || replaceTokenSequence(tokens, "interface $_ident1 : $_identbase { static if($expr) { $if } else { $else } $data } $tail __eo_interface", "interface $_ident1 : $_identbase\n{ $data\n}\n$tail\nstatic if($expr) {\n$if\n} else {\n$else\n} __eo_interface", true) > 0 || replaceTokenSequence(tokens, "interface $_ident1 : $_identbase { version($expr) {/+ typedef $if } else { $else } $data } $tail __eo_interface", "interface $_ident1 : $_identbase\n{ $data\n}\n$tail\nversion($expr) {/+\ntypedef $if\n} else {\n$else\n} __eo_interface", true) > 0 ) {} replaceTokenSequence(tokens, "__eo_interface", "", true); replaceTokenSequence(tokens, "interface $_ident1 : $_identbase { $data const DISPID $constids }", "interface $_ident1 : $_identbase { $data\n}\n\nconst DISPID $constids\n", true); version(none) { replaceTokenSequence(tokens, "typedef enum $_ident1 { $enums } $_ident2;", "enum $_ident2\n{\n$enums\n}", true); replaceTokenSequence(tokens, "typedef enum { $enums } $_ident2;", "enum $_ident2\n{\n$enums\n}", true); replaceTokenSequence(tokens, "typedef [$_ident3] enum $_ident1 { $enums } $_ident2;", "enum $_ident2\n{\n$enums\n}", true); replaceTokenSequence(tokens, "enum $_ident1 { $enums }; typedef $_identbase $_ident2;", "enum $_ident2 : $_identbase\n{\n$enums\n}", true); } else { replaceTokenSequence(tokens, "typedef enum $_ident1 { $enums } $_ident1;", "enum /+$_ident1+/\n{\n$enums\n}\ntypedef int $_ident1;", true); replaceTokenSequence(tokens, "typedef enum $_ident1 { $enums } $ident2;", "enum /+$_ident1+/\n{\n$enums\n}\ntypedef int $_ident1;\ntypedef int $ident2;", true); replaceTokenSequence(tokens, "typedef enum { $enums } $ident2;", "enum\n{\n$enums\n}\ntypedef int $ident2;", true); replaceTokenSequence(tokens, "typedef [$info] enum $_ident1 { $enums } $_ident1;", "enum [$info] /+$_ident1+/\n{\n$enums\n}\ntypedef int $_ident1;", true); replaceTokenSequence(tokens, "typedef [$info] enum $_ident1 { $enums } $ident2;", "enum [$info] /+$_ident1+/\n{\n$enums\n}\ntypedef int $_ident1;\ntypedef int $ident2;", true); replaceTokenSequence(tokens, "typedef [$info] enum { $enums } $ident2;", "enum [$info]\n{\n$enums\n}\ntypedef int $ident2;", true); replaceTokenSequence(tokens, "enum $_ident1 { $enums }; typedef $_identbase $_ident2;", "enum /+$_ident1+/ : $_identbase \n{\n$enums\n}\ntypedef $_identbase $_ident1;\ntypedef $_identbase $_ident2;", true); replaceTokenSequence(tokens, "enum $_ident1 { $enums }; typedef [$info] $_identbase $_ident2;", "enum /+$_ident1+/ : $_identbase \n{\n$enums\n}\ntypedef [$info] $_identbase $_ident2;", true); replaceTokenSequence(tokens, "enum $_ident1 { $enums };", "enum /+$_ident1+/ : int \n{\n$enums\n}\ntypedef int $_ident1;", true); replaceTokenSequence(tokens, "typedef enum $_ident1 $_ident1;", "/+ typedef enum $_ident1 $_ident1; +/", true); replaceTokenSequence(tokens, "enum $_ident1 $_ident2", "$_ident1 $_ident2", true); } replaceTokenSequence(tokens, "typedef _Struct_size_bytes_($args)", "typedef", true); replaceTokenSequence(tokens, "__struct_bcount($args)", "[__struct_bcount($args)]", true); replaceTokenSequence(tokens, "struct $_ident : $_opt public $_ident2 {", "struct $_ident { $_ident2 base;", true); replaceTokenSequence(tokens, "typedef struct { $data } $_ident2;", "struct $_ident2\n{\n$data\n}", true); replaceTokenSequence(tokens, "typedef struct { $data } $_ident2, $expr;", "struct $_ident2\n{\n$data\n}\ntypedef $_ident2 $expr;", true); replaceTokenSequence(tokens, "typedef struct $_ident1 { $data } $_ident2;", "struct $_ident1\n{\n$data\n}\ntypedef $_ident1 $_ident2;", true); replaceTokenSequence(tokens, "typedef struct $_ident1 { $data } $expr;", "struct $_ident1\n{\n$data\n}\ntypedef $_ident1 $expr;", true); replaceTokenSequence(tokens, "typedef [$props] struct $_ident1 { $data } $expr;", "[$props] struct $_ident1\n{\n$data\n}\ntypedef $_ident1 $expr;", true); //replaceTokenSequence(tokens, "typedef struct $_ident1 { $data } *$_ident2;", // "struct $_ident1\n{\n$data\n}\ntypedef $_ident1 *$_ident2;", true); //replaceTokenSequence(tokens, "typedef [$props] struct $_ident1 { $data } *$_ident2;", // "[$props] struct $_ident1\n{\n$data\n}\ntypedef $_ident1 *$_ident2;", true); while(replaceTokenSequence(tokens, "struct { $data } $_ident2 $expr;", "struct _ __ $_ident2 {\n$data\n} _ __ $_ident2 $_ident2 $expr;", true) > 0) {} replaceTokenSequence(tokens, "[$_expr1 uuid($_identIID) $_expr2] interface $_identClass : $_identBase {", "dconst GUID IID_ __ $_identClass = $_identClass.iid;\n\n" ~ "interface $_identClass : $_identBase\n{\n static dconst GUID iid = $_identIID;\n\n", true); replaceTokenSequence(tokens, "[$_expr1 uuid($IID) $_expr2] interface $_identClass : $_identBase {", "dconst GUID IID_ __ $_identClass = $_identClass.iid;\n\n" ~ "interface $_identClass : $_identBase\n{\n static dconst GUID iid = { $IID };\n\n", true); replaceTokenSequence(tokens, "[$_expr1 uuid($_identIID) $_expr2] coclass $_identClass {", "dconst GUID CLSID_ __ $_identClass = $_identClass.iid;\n\n" ~ "class $_identClass\n{\n static dconst GUID iid = $_identIID;\n\n", true); replaceTokenSequence(tokens, "[$_expr1 uuid($IID) $_expr2] coclass $_identClass {", "dconst GUID CLSID_ __ $_identClass = $_identClass.iid;\n\n" ~ "interface $_identClass\n{\n static dconst GUID iid = { $IID };\n\n", true); replaceTokenSequence(tokens, "coclass $_ident1 { $data }", "class $_ident1 { $data }", true); // replaceTokenSequence(tokens, "assert $expr;", "assert($expr);", true); replaceTokenSequence(tokens, "typedef union $_ident1 { $data } $_ident2 $expr;", "union $_ident1\n{\n$data\n}\ntypedef $_ident1 $_ident2 $expr;", true); replaceTokenSequence(tokens, "typedef union $_ident1 switch($expr) $_ident2 { $data } $_ident3;", "union $_ident3 /+switch($expr) $_ident2 +/ { $data };", true); replaceTokenSequence(tokens, "typedef union switch($expr) { $data } $_ident3;", "union $_ident3 /+switch($expr) +/ { $data };", true); replaceTokenSequence(tokens, "union $_ident1 switch($expr) $_ident2 { $data };", "union $_ident1 /+switch($expr) $_ident2 +/ { $data };", true); replaceTokenSequence(tokens, "union $_ident1 switch($expr) $_ident2 { $data }", "union $_ident1 /+switch($expr) $_ident2 +/ { $data }", true); replaceTokenSequence(tokens, "case $_ident1:", "[case $_ident1:]", true); replaceTokenSequence(tokens, "default:", "[default:]", true); replaceTokenSequence(tokens, "union { $data } $_ident2 $expr;", "union _ __ $_ident2 {\n$data\n} _ __ $_ident2 $_ident2 $expr;", true); replaceTokenSequence(tokens, "typedef struct $_ident1 $expr;", "typedef $_ident1 $expr;", true); replaceTokenSequence(tokens, "typedef [$props] struct $_ident1 $expr;", "typedef [$props] $_ident1 $expr;", true); while (replaceTokenSequence(tokens, "typedef __nullterminated CONST $_identtype $_expr1, $args;", "typedef __nullterminated CONST $_identtype $_expr1; typedef __nullterminated CONST $_identtype $args;", true) > 0) {} while (replaceTokenSequence(tokens, "typedef CONST $_identtype $_expr1, $args;", "typedef CONST $_identtype $_expr1; typedef CONST $_identtype $args;", true) > 0) {} while (replaceTokenSequence(tokens, "typedef __nullterminated $_identtype $_expr1, $args;", "typedef __nullterminated $_identtype $_expr1; typedef __nullterminated $_identtype $args;", true) > 0) {} while (replaceTokenSequence(tokens, "typedef [$info] $_identtype $_expr1, $args;", "typedef [$info] $_identtype $_expr1; typedef [$info] $_identtype $args;", true) > 0) {} while (replaceTokenSequence(tokens, "typedef /+$info+/ $_identtype $_expr1, $args;", "typedef /+$info+/ $_identtype $_expr1; typedef /+$info+/ $_identtype $args;", true) > 0) {} while (replaceTokenSequence(tokens, "typedef $_identtype $_expr1, $args;", "typedef $_identtype $_expr1; typedef $_identtype $args;", true) > 0) {} while (replaceTokenSequence(tokens, "typedef void $_expr1, $args;", "typedef void $_expr1; typedef void $args;", true) > 0) {}; replaceTokenSequence(tokens, "typedef $_ident1 $_ident1;", "", true); replaceTokenSequence(tokens, "typedef interface $_ident1 $_ident1;", "", true); // Remote/Local version are made final to avoid placing them into the vtbl replaceTokenSequence(tokens, "[$pre call_as($arg) $post] $_not final", "[$pre call_as($arg) $post] final $_not", true); // Some properties use the same name as the type of the return value replaceTokenSequence(tokens, "$_identFun([$data] $_identFun $arg)", "$_identFun([$data] .$_identFun $arg)", true); // properties that have identically named getter and setter methods have reversed vtbl entries, // so we prepend put_,get_ or putref_ to the property if(startsWith(currentModule, "debugger80")) replaceTokenSequence(tokens, "HRESULT _stdcall", "HRESULT", true); // confusing following rules replaceTokenSequence(tokens, "[$attr1 propput $attr2] HRESULT $_identFun", "[$attr1 propput $attr2]\n\tHRESULT put_ __ $_identFun", true); replaceTokenSequence(tokens, "[$attr1 propget $attr2] HRESULT $_identFun", "[$attr1 propget $attr2]\n\tHRESULT get_ __ $_identFun", true); replaceTokenSequence(tokens, "[$attr1 propputref $attr2] HRESULT $_identFun", "[$attr1 propputref $attr2]\n\tHRESULT putref_ __ $_identFun", true); // VS2012 SDK if(currentModule == "webproperties") { replaceTokenSequence(tokens, "ClassFileItem([$data] ProjectItem $arg)", "ClassFileItem([$data] .ProjectItem $arg)", true); replaceTokenSequence(tokens, "Discomap([$data] ProjectItem $arg)", "Discomap([$data] .ProjectItem $arg)", true); } if(currentModule == "vsshell110") { // not inside #ifdef PROXYSTUB_BUILD replaceTokenSequence(tokens, "alias IID_SVsFileMergeService SID_SVsFileMergeService;", "// $*", true); replaceTokenSequence(tokens, "__uuidof(SVsHierarchyManipulation)", "SVsHierarchyManipulation.iid", true); } if(currentModule == "vapiemp") { // CLSID_CVapiEMPDataSource undefined, create one replaceTokenSequence(tokens, "CVapiEMPDataSource.iid;", "uuid(\"{F1357394-9545-4cfd-AE2B-219C2A30C096}\");", true); } // interface without base class is used as namespace replaceTokenSequence(tokens, "interface $_notIFace IUnknown { $_not static $data }", "/+interface $_notIFace {+/ $_not $data /+} interface $_notIFace+/", true); replaceTokenSequence(tokens, "dispinterface $_ident1 { $data }", "interface $_ident1 { $data }", true); replaceTokenSequence(tokens, "module $_ident1 { $data }", "/+module $_ident1 {+/ $data /+}+/", true); replaceTokenSequence(tokens, "properties:", "/+properties:+/", true); replaceTokenSequence(tokens, "methods:", "/+methods:+/", true); replaceTokenSequence(tokens, "(void)", "()", true); replaceTokenSequence(tokens, "(VOID)", "()", true); replaceTokenSequence(tokens, "[in] ref $_ident", "in $_ident*", true); // in passes by value otherwise replaceTokenSequence(tokens, "[in,$data] ref $_ident", "[$data] in $_ident*", true); // in passes by value otherwise replaceTokenSequence(tokens, "[in]", "in", true); replaceTokenSequence(tokens, "[in,$_not out $data]", "[$_not $data] in", true); replaceTokenSequence(tokens, "[$args1]in[$args2]in", "[$args1][$args2]in", true); replaceTokenSequence(tokens, "in in", "in", true); replaceTokenSequence(tokens, "[*]", "[0]", true); replaceTokenSequence(tokens, "[default]", "/+[default]+/", true); replaceExpressionTokens(tokens); replaceTokenSequence(tokens, "__success($args)", "/+__success($args)+/", true); version(all) { replaceTokenSequence(tokens, "typedef const", "typedef CONST", true); replaceTokenSequence(tokens, "extern \"C\"", "extern(C)", true); replaceTokenSequence(tokens, "extern \"C++\"", "extern(C++)", true); replaceTokenSequence(tokens, "__bcount($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__bcount_opt($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__in_bcount($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__in_ecount($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__in_xcount($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__in_bcount_opt($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__in_ecount_opt($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__out_bcount($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__out_xcount($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__out_bcount_opt($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__out_bcount_part($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__out_bcount_part_opt($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__out_bcount_full($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__out_ecount($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__out_ecount_opt($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__out_ecount_part($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__out_ecount_part_opt($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__out_ecount_full($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__out_data_source($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__out_xcount_opt($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__out_has_type_adt_props($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__inout_bcount($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__inout_ecount($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__inout_xcount($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__inout_bcount_opt($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__inout_ecount_opt($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__inout_bcount_part($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__inout_ecount_part($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__inout_bcount_part_opt($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__inout_ecount_part_opt($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__deref_out_ecount($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__deref_out_bcount($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__deref_out_xcount($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__deref_out_ecount_opt($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__deref_out_bcount_opt($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__deref_out_xcount_opt($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__deref_opt_out_bcount_full($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__deref_inout_ecount_z($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__field_bcount($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__field_bcount_opt($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__field_ecount($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__field_ecount_opt($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__in_range($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__range($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__declspec($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__in_range($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__transfer($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__drv_functionClass($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__drv_maxIRQL($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__drv_when($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__drv_freesMem($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__drv_preferredFunction($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__drv_allocatesMem($args)", "/+$*+/", true); // Win SDK 8.0 replaceTokenSequence(tokens, "_IRQL_requires_same_", "/+$*+/", true); replaceTokenSequence(tokens, "_Function_class_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Inout_cap_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Inout_count_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Inout_updates_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Inout_updates_z_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Inout_updates_opt_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Inout_updates_bytes_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Inout_updates_bytes_opt_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Inout_updates_bytes_to_opt_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Interlocked_operand_", "/+$*+/", true); replaceTokenSequence(tokens, "_Struct_size_bytes_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Out_writes_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Out_writes_opt_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Out_writes_to_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Out_writes_to_opt_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Out_writes_bytes_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Out_writes_bytes_opt_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Out_writes_bytes_to_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Out_writes_bytes_to_opt_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Out_writes_bytes_all_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Out_cap_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Out_z_cap_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_In_reads_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_In_count_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_In_reads_opt_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_In_reads_bytes_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_In_reads_bytes_opt_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_In_NLS_string_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_When_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_At_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Post_readable_size_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Post_writable_byte_size_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Post_equal_to_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Ret_writes_maybenull_z_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Ret_writes_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Ret_range_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Return_type_success_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Outptr_result_buffer_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Outptr_result_bytebuffer_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Outptr_result_buffer_maybenull_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Outptr_opt_result_bytebuffer_all_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Outptr_opt_result_buffer_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Releases_exclusive_lock_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Releases_shared_lock_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Acquires_exclusive_lock_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Acquires_shared_lock_($args)", "/+$*+/", true); // Win SDK 8.1 replaceTokenSequence(tokens, "_Post_satisfies_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Post_readable_byte_size_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "_Ret_reallocated_bytes_($args)", "/+$*+/", true); replaceTokenSequence(tokens, "__assume_bound($args);", "/+$*+/", true); replaceTokenSequence(tokens, "__asm{$args}$_opt;", "assert(false, \"asm not translated\"); asm{naked; nop; /+$args+/}", true); replaceTokenSequence(tokens, "__asm $_not{$stmt}", "assert(false, \"asm not translated\"); asm{naked; nop; /+$_not $stmt+/} }", true); replaceTokenSequence(tokens, "sizeof($_ident)", "$_ident.sizeof", true); replaceTokenSequence(tokens, "sizeof($args)", "($args).sizeof", true); // bitfields: replaceTokenSequence(tokens, "$_identtype $_identname : $_num;", "__bf $_identtype, __quote $_identname __quote, $_num __eobf", true); replaceTokenSequence(tokens, "$_identtype $_identname : $_ident;", "__bf $_identtype, __quote $_identname __quote, $_ident __eobf", true); replaceTokenSequence(tokens, "$_identtype : $_num;", "__bf $_identtype, __quote __quote, $_num __eobf", true); replaceTokenSequence(tokens, "__eobf __bf", ",\n\t", true); replaceTokenSequence(tokens, "__bf", "mixin(bitfields!(", true); replaceTokenSequence(tokens, "__eobf", "));", true); // remove version between identifiers, must be declaration while(replaceTokenSequence(tokens, "$_ident1 version(all) { $if } else { $else } $_ident2", "$_ident1 $if $_ident2", true) > 0 || replaceTokenSequence(tokens, "$_ident1 version(all) { $if } $_ident2", "$_ident1 $if $_ident2", true) > 0 || replaceTokenSequence(tokens, "$_ident1 version(none) { $if } else { $else } $_ident2", "$_ident1 $else $_ident2", true) > 0 || replaceTokenSequence(tokens, "$_ident1 version(none) { $if } $_ident2", "$_ident1 $_ident2", true) > 0) {} // __stdcall version(none) { replaceTokenSequence(tokens, "$_identtype NTAPI", "extern(Windows) $_identtype", true); replaceTokenSequence(tokens, "$_identtype (NTAPI", "extern(Windows) $_identtype (", true); replaceTokenSequence(tokens, "$_identtype WINAPI", "extern(Windows) $_identtype", true); replaceTokenSequence(tokens, "$_identtype (WINAPI", "extern(Windows) $_identtype (", true); replaceTokenSequence(tokens, "$_identtype (/+$_ident+/ WINAPI", "extern(Windows) $_identtype (", true); replaceTokenSequence(tokens, "$_identtype APIENTRY", "extern(Windows) $_identtype", true); replaceTokenSequence(tokens, "$_identtype (APIENTRY", "extern(Windows) $_identtype (", true); replaceTokenSequence(tokens, "$_identtype (CALLBACK", "extern(Windows) $_identtype (", true); } else { replaceTokenSequence(tokens, "NTAPI", "extern(Windows)", true); replaceTokenSequence(tokens, "WINAPI", "extern(Windows)", true); replaceTokenSequence(tokens, "APIENTRY", "extern(Windows)", true); replaceTokenSequence(tokens, "CALLBACK", "extern(Windows)", true); } replaceTokenSequence(tokens, "$_identtype extern(Windows)", "extern(Windows) $_identtype", true); replaceTokenSequence(tokens, "$_identtype* extern(Windows)", "extern(Windows) $_identtype*", true); replaceTokenSequence(tokens, "$_identtype (extern(Windows)", "extern(Windows) $_identtype (", true); replaceTokenSequence(tokens, "$_identtype* (extern(Windows)", "extern(Windows) $_identtype* (", true); replaceTokenSequence(tokens, "$_identtype (/+$_ident+/ extern(Windows)", "extern(Windows) $_identtype (", true); replaceTokenSequence(tokens, "DECLARE_HANDLE($_ident);", "typedef HANDLE $_ident;", true); replaceTokenSequence(tokens, "__inline $_identFun(", "inline int $_identFun(", true); replaceTokenSequence(tokens, "HRESULT($_ident)($_args);", "HRESULT $_ident($_args);", true); replaceTokenSequence(tokens, "$_identType (*$_identFunc)($_args)", "$_identType function($_args) $_identFunc", true); replaceTokenSequence(tokens, "void* (*$_identFunc)($_args)", "void* function($_args) $_identFunc", true); replaceTokenSequence(tokens, "$_identType (__stdcall *$_identFunc)($_args)", "$_identType __stdcall function($_args) $_identFunc", true); replaceTokenSequence(tokens, "$_identType (__cdecl *$_identFunc)($_args)", "$_identType __cdecl function($_args) $_identFunc", true); replaceTokenSequence(tokens, "$_identType (/+__cdecl+/ *$_identFunc)($_args)", "$_identType __cdecl function($_args) $_identFunc", true); } version(targetD2) { replaceTokenSequence(tokens, "$_ident const volatile*", "volatile dconst($_ident)*", true); replaceTokenSequence(tokens, "CONST FAR*", "CONST*", true); replaceTokenSequence(tokens, "$_ident const*", "dconst($_ident)*", true); replaceTokenSequence(tokens, "const $_ident*", "dconst($_ident)*", true); replaceTokenSequence(tokens, "CONST $_ident*", "dconst($_ident)*", true); } else { replaceTokenSequence(tokens, "const $_ident*", "/+const+/ $_ident*", true); } replaceTokenSequence(tokens, "in const $_not(", "in $_not", false); if(currentModule == "vsshelluuids") { replaceTokenSequence(tokens, "denum GUID uuid_IVsDebugger3 = uuid($uid);$data denum GUID uuid_IVsDebugger3", "$data\ndenum GUID uuid_IVsDebugger3",true); replaceTokenSequence(tokens, "denum GUID uuid_IVsDebugLaunchHook = uuid($uid);$data denum GUID uuid_IVsDebugLaunchHook", "$data\ndenum GUID uuid_IVsDebugLaunchHook",true); } if(currentModule == "mnuhelpids") { replaceTokenSequence(tokens, "denum icmdHelpManager = $data; denum icmdHelpManager", "denum icmdHelpManager", true); } if(currentModule == "prsht") { replaceTokenSequence(tokens, "alias _PROPSHEETPAGEA $_ident;", "alias $_ident _PROPSHEETPAGEA;", true); replaceTokenSequence(tokens, "alias _PROPSHEETPAGEW $_ident;", "alias $_ident _PROPSHEETPAGEW;", true); } if(currentModule == "vsscceng") { replaceTokenSequence(tokens, "extern(C++) { $data }", "/+ $* +/", true); } if(currentModule) { replaceTokenSequence(tokens, "alias MUI_CALLBACK_FLAG_UPGRADED_INSTALLATION $_ident;", "// $*", true); } //replaceTokenSequence(tokens, "[$args]", "\n\t\t/+[$args]+/", true); TokenIterator inAlias = tokens.end(); for(TokenIterator tokIt = tokens.begin(); !tokIt.atEnd(); ++tokIt) { Token tok = *tokIt; //tok.pretext = tok.pretext.replace("//D", ""); tok.text = translateToken(tok.text); if(tok.text == "[" && tokIt[1].text == "]") { if(tokIt[2].text == ";") tokIt[1].pretext ~= "0"; // in struct else if(tokIt[2].text == "," || tokIt[2].text == ")" && tokIt[-1].type == Token.Identifier) { tok.text = ""; tokIt[1].text = ""; tokIt[-1].pretext ~= "*"; // in function argument } } else if(tok.text == "[" && tokIt[1].text != "]") { if((tokIt.atBegin() || tokIt[-1].text != "{" || tokIt[-2].text != "=") && (tokIt[1].type != Token.Number || tokIt[2].text != "]") && (tokIt[2].text != "]" || tokIt[3].text != ";")) { TokenIterator bit = tokIt; //if(advanceToClosingBracket(bit) && bit.text != ";") { if(tokIt.atBegin || (tokIt[-1].text != "(" && tokIt[-1].text != "alias")) if (tok.pretext.indexOf('\n') < 0) tok.pretext ~= "\n\t\t"; tok.text = "/+["; } } } else if(tok.text == "]" && tokIt[-1].text != "[") { TokenIterator openit = tokIt; if(retreatToOpeningBracket(openit) && (openit.atBegin || (openit-1).atBegin || openit[-1].text != "{" || openit[-2].text != "=")) if((tokIt[-1].type != Token.Number || tokIt[-2].text != "[") && (tokIt[-2].text != "[" || tokIt[1].text != ";")) tok.text = "]+/"; } else if(tok.text == "struct" && tokIt[1].type == Token.Identifier && tokIt[2].text != "{") { if(tokIt[1].text != "__" && tokIt[1].text != "_") { // forward reference to struct type tok.text = ""; if(tokIt[1].text.startsWith("tag")) tokIt[1].text = tokIt[1].text[3..$]; } } else if((tok.text == "GUID" || tok.text == "IID" || tok.text == "CLSID") && tokIt[1].type == Token.Identifier && tokIt[2].text == "=" && tokIt[3].text == "{") { convertGUID(tokIt + 4); } else if(tok.text == "__quote") { tok.pretext = ""; tok.text = "\""; tokIt[1].pretext = ""; } else if(tok.text == "*" && !tokIt.atBegin() && isClassIdentifier(tokIt[-1].text)) { tok.text = ""; if(tok.pretext.empty && tokIt[1].pretext.empty) tok.pretext = " "; } else if(tok.type == Token.String && tok.text.length > 4 && tok.text[0] == '\'') tok.text = "\"" ~ tok.text[1 .. $-1] ~ "\""; else if(tok.text == "in" && (tokIt[1].text in classes)) tok.text = "/+[in]+/"; else if(tok.text == "alias") inAlias = tokIt; else if(tok.text == ";" && !inAlias.atEnd()) { if(tokIt[-1].type == Token.Identifier) { if (string* s = tokIt[-1].text in aliases) { if(*s != currentFullModule) { inAlias.pretext ~= "/+"; tok.text ~= "+/"; if(!currentImports.contains(*s)) addedImports.addunique(*s); } } else aliases[tokIt[-1].text] = currentFullModule; } inAlias = tokens.end(); } } // vsshell.idl: replaceTokenSequence(tokens, "DEFINE_GUID($_ident,$_num1,$_num2,$_num3,$_num4,$_num5,$_num6,$_num7,$_num8,$_num9,$_numA,$_numB)", "const GUID $_ident = { $_num1,$_num2,$_num3, [ $_num4,$_num5,$_num6,$_num7,$_num8,$_num9,$_numA,$_numB ] }", true); replaceTokenSequence(tokens, "EXTERN_GUID($_ident,$_num1,$_num2,$_num3,$_num4,$_num5,$_num6,$_num7,$_num8,$_num9,$_numA,$_numB)", "const GUID $_ident = { $_num1,$_num2,$_num3, [ $_num4,$_num5,$_num6,$_num7,$_num8,$_num9,$_numA,$_numB ] }", true); // combaseapi.h: replaceTokenSequence(tokens, "alias int $_ident = $_num;", "enum int $_ident = $_num;", true); // C style array declarations to S style replaceTokenSequence(tokens, "$_identtype $_identvar[$dim]", "$_identtype[$dim] $_identvar", true); replaceTokenSequence(tokens, "$_identtype[$dim1] $_identvar[$dim2]", "$_identtype[$dim1][$dim2] $_identvar", true); // handle some pointer array explicitely to avoid ambiguities with expressions replaceTokenSequence(tokens, "void* $_identvar[$dim]", "void*[$dim] $_identvar", true); replaceTokenSequence(tokens, "ubyte* $_identvar[$dim]", "ubyte*[$dim] $_identvar", true); replaceTokenSequence(tokens, "ushort* $_identvar[$dim]", "ushort*[$dim] $_identvar", true); replaceTokenSequence(tokens, "UUID* $_identvar[$dim]", "UUID*[$dim] $_identvar", true); replaceTokenSequence(tokens, "RPC_IF_ID* $_identvar[$dim]", "RPC_IF_ID*[$dim] $_identvar", true); string txt = tokenListToString(tokens, true); return txt; } string translateToken(string text) { switch(text) { case "denum": return "enum"; case "dconst": return "const"; case "_stdcall": return "/*_stdcall*/"; case "_fastcall": return "/*_fastcall*/"; case "__stdcall": return "/*__stdcall*/"; case "__cdecl": return "/*__cdecl*/"; case "__gdi_entry": return "/*__gdi_entry*/"; //case "const": return "/*const*/"; case "inline": return "/*inline*/"; case "__int64": return "long"; case "__int32": return "int"; case "__int3264": return "int"; case "long": return "int"; case "typedef": return "alias"; case "bool": return "idl_bool"; case "GUID_NULL": return "const_GUID_NULL"; case "NULL": return "null"; case "scope": return "idl_scope"; // winbase annotations case "__in": case "__in_opt": case "__in_z_opt": case "__in_bound": case "__allocator": case "__out": case "__out_opt": case "__out_z": case "__inout": case "__inout_z": case "__deref": case "__deref_inout_opt": case "__deref_out_opt": case "__deref_inout": case "__inout_opt": case "__deref_out": case "__deref_opt_out": case "__deref_opt_out_opt": case "__deref_opt_inout_opt": case "__callback": case "__format_string": case "__reserved": case "__notnull": case "__nullterminated": case "__nullnullterminated": case "__possibly_notnullterminated": case "__drv_interlocked": case "__drv_sameIRQL": case "__drv_inTry": case "__drv_aliasesMem": case "__post": case "__notvalid": case "__analysis_noreturn": // Windows SDK 8.0 case "_Outptr_": case "_Outptr_opt_": case "_COM_Outptr_": case "_In_z_": case "_In_opt_z_": case "_Pre_": case "_Pre_valid_": case "_Pre_z_": case "_Pre_opt_valid_": case "_Pre_maybenull_": case "_Post_valid_": case "_Post_invalid_": case "_Post_": case "_Post_z_": case "_Deref_opt_out_opt_": case "_Post_equals_last_error_": case "_Outptr_opt_result_maybenull_": case "_Check_return_": case "_Must_inspect_result_": case "_Frees_ptr_opt_": case "_Reserved_": case "_Ret_maybenull_": case "_Ret_opt_": case "_Printf_format_string_": // Windows SDK 8.1 case "_Field_z_": case "_Pre_notnull_": case "_Frees_ptr_": return "/*" ~ text ~ "*/"; case "__checkReturn": return "/*__checkReturn*/"; case "volatile": return "/*volatile*/"; case "__inline": return "/*__inline*/"; case "__forceinline": return "/*__forceinline*/"; case "IN": return "/*IN*/"; case "OUT": return "/*OUT*/"; case "NEAR": return "/*NEAR*/"; case "FAR": return "/*FAR*/"; case "HUGEP": return "/*HUGEP*/"; case "OPTIONAL": return "/*OPTIONAL*/"; case "DECLSPEC_NORETURN": return "/*DECLSPEC_NORETURN*/"; case "CONST": return "/*CONST*/"; case "VOID": return "void"; case "wchar_t": return "wchar"; case "->": return "."; // vslangproj.d case "prjBuildActionCustom": return "prjBuildActionEmbeddedResource"; // wingdi.d: wrong octal number in SDK v6.0A case "02500": return "2500"; default: if(string* ps = text in tokImports) text = *ps ~ "." ~ text; break; } return text; } void addSource(string file) { string base = baseName(file); if(excludefiles.contains(base)) return; if(!srcfiles.contains(file)) srcfiles ~= file; } void addSourceByPattern(string file) { SpanMode mode = SpanMode.shallow; if (file[0] == '+') { mode = SpanMode.depth; file = file[1..$]; } string path = dirName(file); string pattern = baseName(file); foreach (string name; dirEntries(path, mode)) if (globMatch(baseName(name), pattern)) addSource(name); } void addSources(string file) { if (indexOf(file, '*') >= 0 || indexOf(file, '?') >= 0) addSourceByPattern("+" ~ file); else { if(!exists(file)) file = dirName(file) ~ "\\shared\\" ~ baseName(file); if(!exists(file)) file = replace(file, "\\shared\\", "\\um\\"); addSource(file); } } string fileToModule(string file) { auto len = file.startsWith(win_d_path) ? win_d_path.length : vsi_d_path.length; file = file[len .. $]; if (_endsWith(file,".d")) file = file[0 .. $-2]; file = replace(file, "/", "."); file = replace(file, "\\", "."); return file; } string makehdr(string file, string d_file) { string pkg = d_file.startsWith(win_d_path) ? packageWin : packageVSI; string name = fileToModule(d_file); string hdr; hdr ~= "// File generated by idl2d from\n"; hdr ~= "// " ~ file ~ "\n"; hdr ~= "module " ~ pkg ~ name ~ ";\n\n"; //hdr ~= "import std.c.windows.windows;\n"; //hdr ~= "import std.c.windows.com;\n"; //hdr ~= "import idl.pp_util;\n"; if(pkg == packageVSI) hdr ~= "import " ~ packageNF ~ "vsi;\n"; else hdr ~= "import " ~ packageNF ~ "base;\n"; hdr ~= "\n"; foreach(imp; addedImports) hdr ~= "import " ~ imp ~ ";\n"; if(currentModule == "vsshell") hdr ~= "import " ~ packageWin ~ "commctrl;\n"; if(currentModule == "vsshlids") hdr ~= "import " ~ packageVSI ~ "oleipc;\n"; else if(currentModule == "debugger80") hdr ~= "import " ~ packageWin ~ "oaidl;\n" ~ "import " ~ packageVSI ~ "dte80a;\n"; else if(currentModule == "xmldomdid") hdr ~= "import " ~ packageWin ~ "idispids;\n"; else if(currentModule == "xmldso") hdr ~= "import " ~ packageWin ~ "xmldom;\n"; else if(currentModule == "commctrl") hdr ~= "import " ~ packageWin ~ "objidl;\n"; else if(currentModule == "shellapi") hdr ~= "import " ~ packageWin ~ "iphlpapi;\n"; else if(currentModule == "ifmib") hdr ~= "import " ~ packageWin ~ "iprtrmib;\n"; else if(currentModule == "ipmib") hdr ~= "import " ~ packageWin ~ "iprtrmib;\n"; else if(currentModule == "tcpmib") hdr ~= "import " ~ packageWin ~ "iprtrmib;\n"; else if(currentModule == "udpmib") hdr ~= "import " ~ packageWin ~ "iprtrmib;\n"; else if(currentModule == "vssolutn") hdr ~= "import " ~ packageWin ~ "winnls;\n"; hdr ~= "\n"; version(static_if_to_version) { version(remove_pp) {} else hdr ~= "version = pp_ifndef;\n\n"; } return hdr; } void rewrite_vsiproject(string sources) { string projfile = sdk_d_path ~ "vsi.visualdproj"; if(!exists(projfile)) return; string txt = cast(string)(std.file.read(projfile)); auto pos = indexOf(txt, "<Folder"); if(pos < 0) return; auto pos2 = indexOf(txt[pos .. $], '\n'); if(pos < 0) return; string ins = " <Folder name=\"port\">\n"; string portdir = sdk_d_path ~ "port"; foreach (string name; dirEntries(portdir, SpanMode.shallow)) if (globMatch(baseName(name), "*.d")) ins ~= " <File path=\"port\\" ~ baseName(name) ~ "\" />\n"; string folder = "port"; string[] files = split(sources); foreach(file; files) { if(file == "\\" || file == "SRC" || file == "=") continue; string dir = dirName(file); if(dir != folder) { ins ~= " </Folder>\n"; ins ~= " <Folder name=\"" ~ dir ~ "\">\n"; folder = dir; } ins ~= " <File path=\"" ~ file ~ "\" />\n"; } ins ~= " </Folder>\n"; ins ~= " </Folder>\n"; ins ~= "</DProject>\n"; std.file.write(projfile, txt[0 .. pos + pos2 + 1] ~ ins); } void setCurrentFile(string file) { currentFile = file; currentFullModule = fixImport(file); auto p = lastIndexOf(currentFullModule, '.'); if(p >= 0) currentModule = currentFullModule[p+1 .. $]; else currentModule = currentFullModule; addedImports = addedImports.init; currentImports = currentImports.init; string[string] reinit; tokImports = reinit; // tokImports.init; dmd bugzilla #3491 } int main(string[] argv) { if(argv.length <= 1) { writeln("usage: ", baseName(argv[0]), " {-vsi|-dte|-win|-sdk|-prefix|-verbose|-define} [files...]"); writeln(); writeln(" -vsi=DIR specify path to Visual Studio Integration SDK"); writeln(" -dte=DIR specify path to additional IDL files from VSI SDK"); writeln(" -win=DIR specify path to Windows SDK include folder"); writeln(" -sdk=DIR output base directory for Windows/VSI SDK files"); writeln(" -prefix=P prefix used for identifiers that are D keywords"); writeln(" -verbose report undefined definitions in preprocessor conditions"); writeln(); writeln("Example: ", baseName(argv[0]), ` test.idl`); writeln(" ", baseName(argv[0]), ` -win="%WindowsSdkDir%\Include" -vsi="%VSSDK110Install%" -sdk=sdk`); return -1; } getopt(argv, "vsi", &vsi_base_path, "dte", &dte_path, "win", &win_path, "sdk", &sdk_d_path, "prefix", &keywordPrefix, "verbose", &verbose); if(!dte_path.empty && !_endsWith(dte_path, "\\")) dte_path ~= "\\"; if(!win_path.empty && !_endsWith(win_path, "\\")) win_path ~= "\\"; if(!sdk_d_path.empty && !_endsWith(sdk_d_path, "\\")) sdk_d_path ~= "\\"; if(!vsi_base_path.empty) { vsi_path = vsi_base_path ~ r"\VisualStudioIntegration\Common\IDL\"; vsi_hpath = vsi_base_path ~ r"\VisualStudioIntegration\Common\Inc\"; } if(!sdk_d_path.empty) { vsi_d_path = sdk_d_path ~ dirVSI ~ r"\"; win_d_path = sdk_d_path ~ dirWin ~ r"\"; } initFiles(); // GC.disable(); disabled_defines["__VARIANT_NAME_1"] = 1; disabled_defines["__VARIANT_NAME_2"] = 1; disabled_defines["__VARIANT_NAME_3"] = 1; disabled_defines["__VARIANT_NAME_4"] = 1; disabled_defines["uuid_constant"] = 1; // declared twice disabled_defines["VBProjectProperties2"] = 1; disabled_defines["VBProjectConfigProperties2"] = 1; // declared twice disabled_defines["IID_ProjectProperties2"] = 1; disabled_defines["IID_ProjectConfigurationProperties2"] = 1; // bad init disabled_defines["DOCDATAEXISTING_UNKNOWN"] = 1; disabled_defines["HIERARCHY_DONTCHANGE"] = 1; disabled_defines["SELCONTAINER_DONTCHANGE"] = 1; disabled_defines["HIERARCHY_DONTPROPAGATE"] = 1; disabled_defines["SELCONTAINER_DONTPROPAGATE"] = 1; disabled_defines["ME_UNKNOWN_MENU_ITEM"] = 1; disabled_defines["ME_FIRST_MENU_ITEM"] = 1; // win sdk disabled_defines["pascal"] = 1; disabled_defines["WINBASEAPI"] = 1; disabled_defines["WINADVAPI"] = 1; disabled_defines["FORCEINLINE"] = 1; //disabled_defines["POINTER_64"] = 1; disabled_defines["UNALIGNED"] = 1; disabled_defines["RESTRICTED_POINTER"] = 1; disabled_defines["RTL_CONST_CAST"] = 1; disabled_defines["RTL_RUN_ONCE_INIT"] = 1; disabled_defines["RTL_SRWLOCK_INIT"] = 1; disabled_defines["RTL_CONDITION_VARIABLE_INIT"] = 1; // commctrl.h disabled_defines["HDM_TRANSLATEACCELERATOR"] = 1; foreach(string file; argv[1..$]) addSources(file); writeln("Searching files..."); if(!win_path.empty) foreach(pat; win_idl_files) addSources(win_path ~ pat); if(!vsi_path.empty) foreach(pat; vsi_idl_files) addSources(vsi_path ~ pat); if(!vsi_hpath.empty) foreach(pat; vsi_h_files) addSources(vsi_hpath ~ pat); if(!dte_path.empty) foreach(pat; dte_idl_files) addSources(dte_path ~ pat); writeln("Scanning files..."); Source[] srcs; foreach(string file; srcfiles) { Source src = new Source; src.filename = file; src.text = fromMBSz (cast(immutable(char)*)(cast(char[]) read(file) ~ "\0").ptr); src.tokens = scanText(src.text, 1, true); collectClasses(src.tokens); srcs ~= src; } classes["IUnknown"] = true; classes["IServiceProvider"] = true; writeln("Converting files..."); string sources = "SRC = \\\n"; foreach(Source src; srcs) { writeln(src.filename); string d_file; d_file = replace(src.filename, win_path, win_d_path); d_file = replace(d_file, vsi_path, vsi_d_path); d_file = replace(d_file, vsi_hpath, vsi_d_path); d_file = replace(d_file, dte_path, vsi_d_path); d_file = toLower(d_file); if(d_file._endsWith(".idl") || d_file._endsWith(".idh")) d_file = d_file[0 .. $-3] ~ "d"; if(d_file.endsWith(".h")) d_file = d_file[0 .. $-1] ~ "d"; d_file = translateFilename(d_file); setCurrentFile(d_file); string text = convertText(src.tokens); text = removeDuplicateEmptyLines(text); string hdr = makehdr(src.filename, d_file); std.file.write(d_file, toUTF8(hdr ~ text)); sources ~= "\t" ~ d_file[sdk_d_path.length .. $] ~ " \\\n"; } sources ~= "\n"; if(!sdk_d_path.empty) { version(vsi) string srcfile = sdk_d_path ~ "\\vsi_sources"; else string srcfile = sdk_d_path ~ "\\sources"; std.file.write(srcfile, sources); rewrite_vsiproject(sources); } return 0; } bool verbose; bool simple = true; string[] srcfiles; string[] excludefiles; string currentFile; string currentModule; string currentFullModule; } /////////////////////////////////////////////////////////////////////// void testConvert(string txt, string exptxt, string mod = "") { txt = replace(txt, "\r", ""); exptxt = replace(exptxt, "\r", ""); idl2d inst = new idl2d; inst.currentModule = mod; TokenList tokens = scanText(txt, 1, true); string ntxt = inst.convertText(tokens); assert(ntxt == exptxt); } unittest { string txt = q{ typedef struct tag { } TAG; }; string exptxt = q{ struct tag { } alias tag TAG; }; testConvert(txt, exptxt); } unittest { string txt = q{ cpp_quote("//;end_internal") cpp_quote("typedef struct tagELEMDESC {") cpp_quote(" TYPEDESC tdesc; /* the type of the element */") cpp_quote(" union {") cpp_quote(" IDLDESC idldesc; /* info for remoting the element */") cpp_quote(" PARAMDESC paramdesc; /* info about the parameter */") cpp_quote(" };") cpp_quote("} ELEMDESC, * LPELEMDESC;") }; string exptxt = q{ //;end_internal struct tagELEMDESC { TYPEDESC tdesc; /* the type of the element */ union { IDLDESC idldesc; /* info for remoting the element */ PARAMDESC paramdesc; /* info about the parameter */ }; } alias tagELEMDESC ELEMDESC; alias tagELEMDESC * LPELEMDESC; }; testConvert(txt, exptxt); } /////////////////////////////////////////////////////////////////////// unittest { string txt = q{ int x; cpp_quote("#ifndef WIN16") typedef struct tagSIZE { LONG cx; LONG cy; } SIZE, *PSIZE, *LPSIZE; cpp_quote("#else // WIN16") cpp_quote("typedef struct tagSIZE") cpp_quote("{") cpp_quote(" INT cx;") cpp_quote(" INT cy;") cpp_quote("} SIZE, *PSIZE, *LPSIZE;") cpp_quote("#endif // WIN16") }; version(remove_pp) string exptxt = q{ int x; struct tagSIZE { LONG cx; LONG cy; } alias tagSIZE SIZE; alias tagSIZE *PSIZE; alias tagSIZE *LPSIZE; }q{ // WIN16 }; else // !remove_pp string exptxt = q{ int x; version(all) /* #ifndef WIN16 */ { struct tagSIZE { LONG cx; LONG cy; } alias tagSIZE SIZE; alias tagSIZE *PSIZE; alias tagSIZE *LPSIZE; } else { // #else // WIN16 struct tagSIZE { INT cx; INT cy; } alias tagSIZE SIZE; alias tagSIZE *PSIZE; alias tagSIZE *LPSIZE; } // #endif // WIN16 }; testConvert(txt, exptxt); } /////////////////////////////////////////////////////////////////////// unittest { string txt = " int x; #if defined(MIDL_PASS) typedef struct _LARGE_INTEGER { #else // MIDL_PASS typedef union _LARGE_INTEGER { struct { }; #endif //MIDL_PASS LONGLONG QuadPart; } LARGE_INTEGER; "; string exptxt = " int x; union _LARGE_INTEGER { struct { }; LONGLONG QuadPart; } alias _LARGE_INTEGER LARGE_INTEGER; "; testConvert(txt, exptxt, "winnt"); } /////////////////////////////////////////////////////////////////////// unittest { string txt = " #define convert() \\ hello #define noconvert(n,m) \\ hallo1 |\\ hallo2 "; string exptxt = " int convert() { return " " hello; } // #define noconvert(n,m) \\ // hallo1 |\\ // hallo2 "; version(macro2template) exptxt = replace(exptxt, "int", "auto"); testConvert(txt, exptxt); } unittest { string txt = " #define CONTEXT_i386 0x00010000L // this assumes that i386 and #define CONTEXT_CONTROL (CONTEXT_i386 | 0x00000001L) // SS:SP, CS:IP, FLAGS, BP "; string exptxt = " enum CONTEXT_i386 = 0x00010000; // this assumes that i386 and enum CONTEXT_CONTROL = (CONTEXT_i386 | 0x00000001); // SS:SP, CS:IP, FLAGS, BP "; testConvert(txt, exptxt); } unittest { string txt = " #define NtCurrentTeb() ((struct _TEB *)_rdtebex()) "; string exptxt = " _TEB* NtCurrentTeb() { return ( cast( _TEB*)_rdtebex()); } "; version(macro2template) exptxt = replace(exptxt, "_TEB* ", "auto "); testConvert(txt, exptxt); } unittest { string txt = " enum { prjBuildActionNone } cpp_quote(\"#define prjBuildActionMin prjBuildActionNone\") cpp_quote(\"#define prjBuildActionMax prjBuildActionCustom\") "; string exptxt = " enum { prjBuildActionNone } enum prjBuildActionMin = prjBuildActionNone; alias prjBuildActionEmbeddedResource prjBuildActionMax; "; testConvert(txt, exptxt); } unittest { string txt = " #define _INTEGRAL_MAX_BITS 64 #if (!defined (_MAC) && (!defined(MIDL_PASS) || defined(__midl)) && (!defined(_M_IX86) || (defined(_INTEGRAL_MAX_BITS) && _INTEGRAL_MAX_BITS >= 64))) typedef __int64 LONGLONG; #endif "; string exptxt = " alias long LONGLONG; "; // testConvert(txt, exptxt); } unittest { string txt = " #define KEY_READ ((STANDARD_RIGHTS_READ |\\ KEY_QUERY_VALUE)\\ & (~SYNCHRONIZE)) "; string exptxt = " enum KEY_READ = ((STANDARD_RIGHTS_READ | KEY_QUERY_VALUE) & (~SYNCHRONIZE)); "; testConvert(txt, exptxt); } unittest { string txt = " #if _WIN32_WINNT >= 0x0600 #define _PROPSHEETPAGEA_V3 _PROPSHEETPAGEA #elif (_WIN32_IE >= 0x0400) #define _PROPSHEETPAGEA_V2 _PROPSHEETPAGEA #else #define _PROPSHEETPAGEA_V1 _PROPSHEETPAGEA #endif "; string exptxt = " version(all) /* #if _WIN32_WINNT >= 0x0600 */ { alias _PROPSHEETPAGEA_V3 _PROPSHEETPAGEA; } else version(all) /* #elif (_WIN32_IE >= 0x0400) */ { alias _PROPSHEETPAGEA_V2 _PROPSHEETPAGEA; } else { alias _PROPSHEETPAGEA_V1 _PROPSHEETPAGEA; } " " "; testConvert(txt, exptxt, "prsht"); } unittest { string txt = " #define PtrToPtr64( p ) ((void * POINTER_64) p) __inline void * POINTER_64 PtrToPtr64(const void *p) { return((void * POINTER_64) (unsigned __int64) (ULONG_PTR)p ); } "; string exptxt = " // #define PtrToPtr64( p ) ((void * POINTER_64) p) /*__inline*/ void * PtrToPtr64(const( void)*p) { return( cast(void*) cast(ulong)cast(ULONG_PTR)p ); } "; testConvert(txt, exptxt, "prsht"); } unittest { string txt = "int x[3];"; string exptxt = "int[3] x;"; testConvert(txt, exptxt); }
D
/Users/techmaster/Downloads/animationWithQueue-master/Build/Intermediates/DemoAnimation.build/Debug-iphonesimulator/DemoAnimation.build/Objects-normal/x86_64/Utils.o : /Users/techmaster/Downloads/animationWithQueue-master/Queue.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/Dynamic.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/AniView.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/Miller.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/ViewController.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/AnimateItem.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/AppDelegate.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/Utils.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/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/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Users/techmaster/Downloads/animationWithQueue-master/Build/Intermediates/DemoAnimation.build/Debug-iphonesimulator/DemoAnimation.build/Objects-normal/x86_64/Utils~partial.swiftmodule : /Users/techmaster/Downloads/animationWithQueue-master/Queue.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/Dynamic.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/AniView.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/Miller.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/ViewController.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/AnimateItem.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/AppDelegate.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/Utils.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/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/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Users/techmaster/Downloads/animationWithQueue-master/Build/Intermediates/DemoAnimation.build/Debug-iphonesimulator/DemoAnimation.build/Objects-normal/x86_64/Utils~partial.swiftdoc : /Users/techmaster/Downloads/animationWithQueue-master/Queue.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/Dynamic.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/AniView.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/Miller.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/ViewController.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/AnimateItem.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/AppDelegate.swift /Users/techmaster/Downloads/animationWithQueue-master/DemoAnimation/Utils.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/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/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule
D
/******************************************************************************* * Copyright (c) 2000, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Port to the D programming language: * Frank Benoit <benoit@tionex.de> *******************************************************************************/ module dwt.internal.image.PngIhdrChunk; import dwt.dwthelper.utils; import dwt.DWT; import dwt.graphics.PaletteData; import dwt.graphics.RGB; import dwt.internal.image.PngFileReadState; import dwt.internal.image.PngIhdrChunk; import dwt.internal.image.PngChunk; import tango.text.convert.Format; class PngIhdrChunk : PngChunk { static const int IHDR_DATA_LENGTH = 13; static const int WIDTH_DATA_OFFSET = DATA_OFFSET + 0; static const int HEIGHT_DATA_OFFSET = DATA_OFFSET + 4; static const int BIT_DEPTH_OFFSET = DATA_OFFSET + 8; static const int COLOR_TYPE_OFFSET = DATA_OFFSET + 9; static const int COMPRESSION_METHOD_OFFSET = DATA_OFFSET + 10; static const int FILTER_METHOD_OFFSET = DATA_OFFSET + 11; static const int INTERLACE_METHOD_OFFSET = DATA_OFFSET + 12; static const byte COLOR_TYPE_GRAYSCALE = 0; static const byte COLOR_TYPE_RGB = 2; static const byte COLOR_TYPE_PALETTE = 3; static const byte COLOR_TYPE_GRAYSCALE_WITH_ALPHA = 4; static const byte COLOR_TYPE_RGB_WITH_ALPHA = 6; static const int INTERLACE_METHOD_NONE = 0; static const int INTERLACE_METHOD_ADAM7 = 1; static const int FILTER_NONE = 0; static const int FILTER_SUB = 1; static const int FILTER_UP = 2; static const int FILTER_AVERAGE = 3; static const int FILTER_PAETH = 4; static const byte[] ValidBitDepths = [ cast(byte)1, 2, 4, 8, 16]; static const byte[] ValidColorTypes = [ cast(byte)0, 2, 3, 4, 6]; int width, height; byte bitDepth, colorType, compressionMethod, filterMethod, interlaceMethod; this(int width, int height, byte bitDepth, byte colorType, byte compressionMethod, byte filterMethod, byte interlaceMethod) { super(IHDR_DATA_LENGTH); setType(TYPE_IHDR); setWidth(width); setHeight(height); setBitDepth(bitDepth); setColorType(colorType); setCompressionMethod(compressionMethod); setFilterMethod(filterMethod); setInterlaceMethod(interlaceMethod); setCRC(computeCRC()); } /** * Construct a PNGChunk using the reference bytes * given. */ this(byte[] reference) { super(reference); if (reference.length <= IHDR_DATA_LENGTH) DWT.error(DWT.ERROR_INVALID_IMAGE); width = getInt32(WIDTH_DATA_OFFSET); height = getInt32(HEIGHT_DATA_OFFSET); bitDepth = reference[BIT_DEPTH_OFFSET]; colorType = reference[COLOR_TYPE_OFFSET]; compressionMethod = reference[COMPRESSION_METHOD_OFFSET]; filterMethod = reference[FILTER_METHOD_OFFSET]; interlaceMethod = reference[INTERLACE_METHOD_OFFSET]; } override int getChunkType() { return CHUNK_IHDR; } /** * Get the image's width in pixels. */ int getWidth() { return width; } /** * Set the image's width in pixels. */ void setWidth(int value) { setInt32(WIDTH_DATA_OFFSET, value); width = value; } /** * Get the image's height in pixels. */ int getHeight() { return height; } /** * Set the image's height in pixels. */ void setHeight(int value) { setInt32(HEIGHT_DATA_OFFSET, value); height = value; } /** * Get the image's bit depth. * This is limited to the values 1, 2, 4, 8, or 16. */ byte getBitDepth() { return bitDepth; } /** * Set the image's bit depth. * This is limited to the values 1, 2, 4, 8, or 16. */ void setBitDepth(byte value) { reference[BIT_DEPTH_OFFSET] = value; bitDepth = value; } /** * Get the image's color type. * This is limited to the values: * 0 - Grayscale image. * 2 - RGB triple. * 3 - Palette. * 4 - Grayscale with Alpha channel. * 6 - RGB with Alpha channel. */ byte getColorType() { return colorType; } /** * Set the image's color type. * This is limited to the values: * 0 - Grayscale image. * 2 - RGB triple. * 3 - Palette. * 4 - Grayscale with Alpha channel. * 6 - RGB with Alpha channel. */ void setColorType(byte value) { reference[COLOR_TYPE_OFFSET] = value; colorType = value; } /** * Get the image's compression method. * This value must be 0. */ byte getCompressionMethod() { return compressionMethod; } /** * Set the image's compression method. * This value must be 0. */ void setCompressionMethod(byte value) { reference[COMPRESSION_METHOD_OFFSET] = value; compressionMethod = value; } /** * Get the image's filter method. * This value must be 0. */ byte getFilterMethod() { return filterMethod; } /** * Set the image's filter method. * This value must be 0. */ void setFilterMethod(byte value) { reference[FILTER_METHOD_OFFSET] = value; filterMethod = value; } /** * Get the image's interlace method. * This value is limited to: * 0 - No interlacing used. * 1 - Adam7 interlacing used. */ byte getInterlaceMethod() { return interlaceMethod; } /** * Set the image's interlace method. * This value is limited to: * 0 - No interlacing used. * 1 - Adam7 interlacing used. */ void setInterlaceMethod(byte value) { reference[INTERLACE_METHOD_OFFSET] = value; interlaceMethod = value; } /** * Answer whether the chunk is a valid IHDR chunk. */ override void validate(PngFileReadState readState, PngIhdrChunk headerChunk) { // An IHDR chunk is invalid if any other chunk has // been read. if (readState.readIHDR || readState.readPLTE || readState.readIDAT || readState.readIEND) { DWT.error(DWT.ERROR_INVALID_IMAGE); } else { readState.readIHDR = true; } super.validate(readState, headerChunk); if (length !is IHDR_DATA_LENGTH) DWT.error(DWT.ERROR_INVALID_IMAGE); if (compressionMethod !is 0) DWT.error(DWT.ERROR_INVALID_IMAGE); if (interlaceMethod !is INTERLACE_METHOD_NONE && interlaceMethod !is INTERLACE_METHOD_ADAM7) { DWT.error(DWT.ERROR_INVALID_IMAGE); } bool colorTypeIsValid = false; for (int i = 0; i < ValidColorTypes.length; i++) { if (ValidColorTypes[i] is colorType) { colorTypeIsValid = true; break; } } if (!colorTypeIsValid) DWT.error(DWT.ERROR_INVALID_IMAGE); bool bitDepthIsValid = false; for (int i = 0; i < ValidBitDepths.length; i++) { if (ValidBitDepths[i] is bitDepth) { bitDepthIsValid = true; break; } } if (!bitDepthIsValid) DWT.error(DWT.ERROR_INVALID_IMAGE); if ((colorType is COLOR_TYPE_RGB || colorType is COLOR_TYPE_RGB_WITH_ALPHA || colorType is COLOR_TYPE_GRAYSCALE_WITH_ALPHA) && bitDepth < 8) { DWT.error(DWT.ERROR_INVALID_IMAGE); } if (colorType is COLOR_TYPE_PALETTE && bitDepth > 8) { DWT.error(DWT.ERROR_INVALID_IMAGE); } } String getColorTypeString() { switch (colorType) { case COLOR_TYPE_GRAYSCALE: return "Grayscale"; case COLOR_TYPE_RGB: return "RGB"; case COLOR_TYPE_PALETTE: return "Palette"; case COLOR_TYPE_GRAYSCALE_WITH_ALPHA: return "Grayscale with Alpha"; case COLOR_TYPE_RGB_WITH_ALPHA: return "RGB with Alpha"; default: return "Unknown - " ~ cast(char)colorType; } } String getFilterMethodString() { switch (filterMethod) { case FILTER_NONE: return "None"; case FILTER_SUB: return "Sub"; case FILTER_UP: return "Up"; case FILTER_AVERAGE: return "Average"; case FILTER_PAETH: return "Paeth"; default: return "Unknown"; } } String getInterlaceMethodString() { switch (interlaceMethod) { case INTERLACE_METHOD_NONE: return "Not Interlaced"; case INTERLACE_METHOD_ADAM7: return "Interlaced - ADAM7"; default: return "Unknown"; } } override String contributeToString() { return Format( "\n\tWidth: {}\n\tHeight: {}\n\tBit Depth: {}\n\tColor Type: {}\n\tCompression Method: {}\n\tFilter Method: {}\n\tInterlace Method: {}", width, height, bitDepth, getColorTypeString(), compressionMethod, getFilterMethodString(), getInterlaceMethodString() ); } bool getMustHavePalette() { return colorType is COLOR_TYPE_PALETTE; } bool getCanHavePalette() { return colorType !is COLOR_TYPE_GRAYSCALE && colorType !is COLOR_TYPE_GRAYSCALE_WITH_ALPHA; } /** * Answer the pixel size in bits based on the color type * and bit depth. */ int getBitsPerPixel() { switch (colorType) { case COLOR_TYPE_RGB_WITH_ALPHA: return 4 * bitDepth; case COLOR_TYPE_RGB: return 3 * bitDepth; case COLOR_TYPE_GRAYSCALE_WITH_ALPHA: return 2 * bitDepth; case COLOR_TYPE_GRAYSCALE: case COLOR_TYPE_PALETTE: return bitDepth; default: DWT.error(DWT.ERROR_INVALID_IMAGE); return 0; } } /** * Answer the pixel size in bits based on the color type * and bit depth. */ int getSwtBitsPerPixel() { switch (colorType) { case COLOR_TYPE_RGB_WITH_ALPHA: case COLOR_TYPE_RGB: case COLOR_TYPE_GRAYSCALE_WITH_ALPHA: return 24; case COLOR_TYPE_GRAYSCALE: case COLOR_TYPE_PALETTE: return Math.min(bitDepth, 8); default: DWT.error(DWT.ERROR_INVALID_IMAGE); return 0; } } int getFilterByteOffset() { if (bitDepth < 8) return 1; return getBitsPerPixel() / 8; } bool usesDirectColor() { switch (colorType) { case COLOR_TYPE_GRAYSCALE: case COLOR_TYPE_GRAYSCALE_WITH_ALPHA: case COLOR_TYPE_RGB: case COLOR_TYPE_RGB_WITH_ALPHA: return true; default: return false; } } PaletteData createGrayscalePalette() { int depth = Math.min(bitDepth, 8); int max = (1 << depth) - 1; int delta = 255 / max; int gray = 0; RGB[] rgbs = new RGB[max + 1]; for (int i = 0; i <= max; i++) { rgbs[i] = new RGB(gray, gray, gray); gray += delta; } return new PaletteData(rgbs); } PaletteData getPaletteData() { switch (colorType) { case COLOR_TYPE_GRAYSCALE: return createGrayscalePalette(); case COLOR_TYPE_GRAYSCALE_WITH_ALPHA: case COLOR_TYPE_RGB: case COLOR_TYPE_RGB_WITH_ALPHA: return new PaletteData(0xFF0000, 0xFF00, 0xFF); default: return null; } } }
D
/Users/taharahiroki/Documents/GitHub/Enigma_Bitcoin_proto/bip32_proto/target/debug/build/proc-macro2-78620e4567a52b77/build_script_build-78620e4567a52b77: /Users/taharahiroki/.cargo/registry/src/github.com-1ecc6299db9ec823/proc-macro2-1.0.6/build.rs /Users/taharahiroki/Documents/GitHub/Enigma_Bitcoin_proto/bip32_proto/target/debug/build/proc-macro2-78620e4567a52b77/build_script_build-78620e4567a52b77.d: /Users/taharahiroki/.cargo/registry/src/github.com-1ecc6299db9ec823/proc-macro2-1.0.6/build.rs /Users/taharahiroki/.cargo/registry/src/github.com-1ecc6299db9ec823/proc-macro2-1.0.6/build.rs:
D
/****************************************************************************** This module contains internal implementation of the instance object. License: Copyright (c) 2008 Jarrett Billingsley This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ******************************************************************************/ module amigos.minid.instance; import tango.math.Math; import amigos.minid.alloc; import amigos.minid.classobj; import amigos.minid.namespace; import amigos.minid.string; import amigos.minid.types; struct instance { static: // ================================================================================================================================================ // Package // ================================================================================================================================================ package MDInstance* create(ref Allocator alloc, MDClass* parent, uword numValues = 0, uword extraBytes = 0) { auto i = alloc.allocate!(MDInstance)(InstanceSize(numValues, extraBytes)); i.parent = parent; i.numValues = numValues; i.extraBytes = extraBytes; i.finalizer = parent.finalizer; i.extraValues()[] = MDValue.nullValue; return i; } package void free(ref Allocator alloc, MDInstance* i) { alloc.free(i, InstanceSize(i.numValues, i.extraBytes)); } package MDValue* getField(MDInstance* i, MDString* name) { MDValue dummy; return getField(i, name, dummy); } package MDValue* getField(MDInstance* i, MDString* name, out MDValue owner) { if(i.fields !is null) { if(auto ret = namespace.get(i.fields, name)) { owner = i; return ret; } } MDClass* dummy; auto ret = classobj.getField(i.parent, name, dummy); if(dummy !is null) owner = dummy; return ret; } package void setField(ref Allocator alloc, MDInstance* i, MDString* name, MDValue* value) { if(i.fields is null) i.fields = namespace.create(alloc, i.parent.name); namespace.set(alloc, i.fields, name, value); } package bool derivesFrom(MDInstance* i, MDClass* c) { for(auto o = i.parent; o !is null; o = o.parent) if(o is c) return true; return false; } package MDNamespace* fieldsOf(ref Allocator alloc, MDInstance* i) { if(i.fields is null) i.fields = namespace.create(alloc, i.parent.name); return i.fields; } package bool next(MDInstance* i, ref uword idx, ref MDString** key, ref MDValue* val) { if(i.fields is null) return false; return i.fields.data.next(idx, key, val); } package uword InstanceSize(uword numValues, uword extraBytes) { return MDInstance.sizeof + (numValues * MDValue.sizeof) + extraBytes; } }
D
/Users/macosx/Desktop/TestNetWorkLayer/build/TestNetWorkLayer.build/Debug-iphonesimulator/TestNetWorkLayerTests.build/Objects-normal/x86_64/TestNetWorkLayerTests.o : /Users/macosx/Desktop/TestNetWorkLayer/TestNetWorkLayerTests/TestNetWorkLayerTests.swift /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreImage.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/QuartzCore.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Metal.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Swift.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/UIKit.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/SwiftyJSON/SwiftyJSON.framework/Modules/SwiftyJSON.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Modules/Nimble.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Alamofire/Alamofire.framework/Modules/Alamofire.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/URITemplate/URITemplate.framework/Modules/URITemplate.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Modules/Quick.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/TestNetWorkLayer.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/lib/XCTest.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Mockingjay/Mockingjay.framework/Modules/Mockingjay.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/DSL.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/QCKDSL.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/SwiftyJSON/SwiftyJSON.framework/Headers/SwiftyJSON-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/Nimble-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/URITemplate/URITemplate.framework/Headers/URITemplate-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/Quick-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Mockingjay/Mockingjay.framework/Headers/Mockingjay-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/QuickSpec.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/Nimble.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/NMBExceptionCapture.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/CwlPreconditionTesting.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/Quick.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/QuickConfiguration.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/CwlCatchException.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/CwlMachBadInstructionHandler.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/mach_excServer.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/SwiftyJSON/SwiftyJSON.framework/Headers/SwiftyJSON-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/Nimble-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/URITemplate/URITemplate.framework/Headers/URITemplate-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/Quick-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Mockingjay/Mockingjay.framework/Headers/Mockingjay-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Mockingjay/Mockingjay.framework/Headers/Mockingjay.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/NMBStringify.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/SwiftyJSON/SwiftyJSON.framework/Modules/module.modulemap /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Modules/module.modulemap /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Alamofire/Alamofire.framework/Modules/module.modulemap /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/URITemplate/URITemplate.framework/Modules/module.modulemap /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Modules/module.modulemap /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Mockingjay/Mockingjay.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTest.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/macosx/Desktop/TestNetWorkLayer/build/TestNetWorkLayer.build/Debug-iphonesimulator/TestNetWorkLayerTests.build/Objects-normal/x86_64/TestNetWorkLayerTests~partial.swiftmodule : /Users/macosx/Desktop/TestNetWorkLayer/TestNetWorkLayerTests/TestNetWorkLayerTests.swift /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreImage.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/QuartzCore.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Metal.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Swift.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/UIKit.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/SwiftyJSON/SwiftyJSON.framework/Modules/SwiftyJSON.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Modules/Nimble.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Alamofire/Alamofire.framework/Modules/Alamofire.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/URITemplate/URITemplate.framework/Modules/URITemplate.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Modules/Quick.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/TestNetWorkLayer.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/lib/XCTest.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Mockingjay/Mockingjay.framework/Modules/Mockingjay.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/DSL.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/QCKDSL.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/SwiftyJSON/SwiftyJSON.framework/Headers/SwiftyJSON-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/Nimble-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/URITemplate/URITemplate.framework/Headers/URITemplate-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/Quick-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Mockingjay/Mockingjay.framework/Headers/Mockingjay-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/QuickSpec.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/Nimble.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/NMBExceptionCapture.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/CwlPreconditionTesting.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/Quick.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/QuickConfiguration.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/CwlCatchException.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/CwlMachBadInstructionHandler.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/mach_excServer.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/SwiftyJSON/SwiftyJSON.framework/Headers/SwiftyJSON-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/Nimble-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/URITemplate/URITemplate.framework/Headers/URITemplate-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/Quick-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Mockingjay/Mockingjay.framework/Headers/Mockingjay-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Mockingjay/Mockingjay.framework/Headers/Mockingjay.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/NMBStringify.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/SwiftyJSON/SwiftyJSON.framework/Modules/module.modulemap /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Modules/module.modulemap /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Alamofire/Alamofire.framework/Modules/module.modulemap /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/URITemplate/URITemplate.framework/Modules/module.modulemap /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Modules/module.modulemap /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Mockingjay/Mockingjay.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTest.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/macosx/Desktop/TestNetWorkLayer/build/TestNetWorkLayer.build/Debug-iphonesimulator/TestNetWorkLayerTests.build/Objects-normal/x86_64/TestNetWorkLayerTests~partial.swiftdoc : /Users/macosx/Desktop/TestNetWorkLayer/TestNetWorkLayerTests/TestNetWorkLayerTests.swift /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreImage.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/QuartzCore.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Metal.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/Swift.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/UIKit.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftinterface /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/SwiftyJSON/SwiftyJSON.framework/Modules/SwiftyJSON.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Modules/Nimble.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Alamofire/Alamofire.framework/Modules/Alamofire.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/URITemplate/URITemplate.framework/Modules/URITemplate.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Modules/Quick.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/TestNetWorkLayer.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/lib/XCTest.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Mockingjay/Mockingjay.framework/Modules/Mockingjay.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/DSL.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/QCKDSL.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/SwiftyJSON/SwiftyJSON.framework/Headers/SwiftyJSON-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/Nimble-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/URITemplate/URITemplate.framework/Headers/URITemplate-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/Quick-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Mockingjay/Mockingjay.framework/Headers/Mockingjay-umbrella.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/QuickSpec.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/Nimble.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/NMBExceptionCapture.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/CwlPreconditionTesting.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/Quick.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/QuickConfiguration.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/CwlCatchException.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/CwlMachBadInstructionHandler.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/mach_excServer.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/SwiftyJSON/SwiftyJSON.framework/Headers/SwiftyJSON-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/Nimble-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/URITemplate/URITemplate.framework/Headers/URITemplate-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Headers/Quick-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Mockingjay/Mockingjay.framework/Headers/Mockingjay-Swift.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Mockingjay/Mockingjay.framework/Headers/Mockingjay.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Headers/NMBStringify.h /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/SwiftyJSON/SwiftyJSON.framework/Modules/module.modulemap /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Nimble/Nimble.framework/Modules/module.modulemap /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Alamofire/Alamofire.framework/Modules/module.modulemap /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/URITemplate/URITemplate.framework/Modules/module.modulemap /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Quick/Quick.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Modules/module.modulemap /Users/macosx/Desktop/TestNetWorkLayer/build/Debug-iphonesimulator/Mockingjay/Mockingjay.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework/Headers/XCTest.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.2.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
D
/Users/in2macbookpro/Documents/Ivan/WebServiceTest/build/WebServiceTest.build/Release-iphoneos/WebServiceTest.build/Objects-normal/arm64/UIDataCell.o : /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/DPTableData.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/UICommentsTableViewCell.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/UIBeginScreenViewController.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/UIDataCell.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/AppDelegate.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/UIDataTableViewController.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/UICommentViewController.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/WebServiceHandler.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/Security.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/CoreImage.swiftmodule /Users/in2macbookpro/Documents/Ivan/WebServiceTest/build/WebServiceTest.build/Release-iphoneos/WebServiceTest.build/Objects-normal/arm64/UIDataCell~partial.swiftmodule : /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/DPTableData.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/UICommentsTableViewCell.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/UIBeginScreenViewController.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/UIDataCell.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/AppDelegate.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/UIDataTableViewController.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/UICommentViewController.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/WebServiceHandler.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/Security.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/CoreImage.swiftmodule /Users/in2macbookpro/Documents/Ivan/WebServiceTest/build/WebServiceTest.build/Release-iphoneos/WebServiceTest.build/Objects-normal/arm64/UIDataCell~partial.swiftdoc : /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/DPTableData.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/UICommentsTableViewCell.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/UIBeginScreenViewController.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/UIDataCell.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/AppDelegate.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/UIDataTableViewController.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/UICommentViewController.swift /Users/in2macbookpro/Documents/Ivan/WebServiceTest/WebServiceTest/WebServiceHandler.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/Security.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/CoreImage.swiftmodule
D
/* Copyright 2016 HaCk3D, substanceof https://github.com/HaCk3Dq https://github.com/substanceof 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 utils; import std.stdio, std.array, std.range, std.string, std.file, std.random; import core.thread, core.sync.mutex, core.exception; import core.sys.posix.signal; import std.datetime, std.conv, std.algorithm, std.utf, std.typecons; import localization, app, vkversion, musicplayer; const bool debugMessagesEnabled = false, dbmfe = true, showTokenInLog = false; __gshared { File dbgff; File dbglat; string dbmlog = ""; string vkcliTmpDir = "/tmp/vkcli-tmp"; string vkcliLogDir = "/tmp/vkcli-log"; string dbgfname = "vklog"; string dbglatest = "-latest"; string mpvsck = "vkmpv-socket-"; string mpvsocketName; string logName; string logPath; string logLatPath; Mutex dbgmutex; } private void appendDbg(string app) { synchronized(dbgmutex) { append(logPath, app); append(logLatPath, app); } } string toTmpDateString(SysTime t) { return t.day().to!string ~ t.month().to!string ~ t.year().to!string ~ "-" ~ t.hour().tzr ~ ":" ~ t.minute().tzr ~ ":" ~ t.second().tzr ~ "-" ~ t.timezone().stdName(); } string getPlayerSocketName() { if(mpvsocketName == "") throw new Exception("bad player socket name"); return vkcliTmpDir ~ "/" ~ mpvsocketName; } void initdbm() { auto ctime = Clock.currTime(); dbgmutex = new Mutex(); logName = dbgfname ~ "_" ~ ctime.toTmpDateString(); logPath = vkcliLogDir ~ "/" ~ logName; logLatPath = vkcliLogDir ~ "/" ~ dbgfname ~ dbglatest; mpvsocketName = mpvsck ~ genStr(8); if(!exists(vkcliTmpDir)) mkdir(vkcliTmpDir); if(!exists(vkcliLogDir)) mkdir(vkcliLogDir); if(dbmfe) { string logIntro = "vk-cli " ~ currentVersion ~ " log\n" ~ ctime.toSimpleString() ~ "\n"; dbgff = File(logPath, "w"); dbgff.write(logIntro); dbgff.close(); dbglat = File(logLatPath, "w"); dbglat.write(logIntro); dbglat.close(); } } void dbm(string msg) { if(debugMessagesEnabled) writeln("[debug]" ~ msg); if(dbmfe) appendDbg(msg ~ "\n"); } void dropClient(string msg) { Exit(msg); } string tzr(int inpt) { auto r = inpt.to!string; if(inpt > -1 && inpt < 10) return ("0" ~ r); else return r; } string vktime(SysTime ct, long ut) { auto t = SysTime(unixTimeToStdTime(ut)); return (t.dayOfGregorianCal == ct.dayOfGregorianCal) ? (tzr(t.hour) ~ ":" ~ tzr(t.minute)) : (tzr(t.day) ~ "." ~ tzr(t.month) ~ ( t.year != ct.year ? "." ~ t.year.to!string[$-2..$] : "" ) ); } string agotime (SysTime ct, long ut) { //not used auto pt = SysTime(ut.unixTimeToStdTime); auto ctm = ct.hour*60 + ct.minute; auto ptm = pt.hour*60 + pt.minute; auto tmdelta = ctm - ptm; const threshld = 240; if( pt.dayOfGregorianCal == ct.dayOfGregorianCal && tmdelta < threshld ) { string rt; if(tmdelta > 60) { auto m = tmdelta % 60; auto h = (tmdelta-m) / 60; rt ~= h.to!string ~ ( h == 1 ? getLocal("time_hour") : ( h > 0 && h < 5 ? getLocal("time_hours_l5") : getLocal("time_hours") ) ); if(m != 0) rt ~= " " ~ m.to!string ~ ( m == 1 ? getLocal("time_minute") : ( m > 0 && m < 5 ? getLocal("time_minutes_l5") : getLocal("time_minutes") ) ); } else if(tmdelta == 1) rt = tmdelta.to!string ~ getLocal("time_minute"); else rt = tmdelta.to!string ~ getLocal("time_minutes"); return rt ~ getLocal("time_ago"); } else return vktime(ct, ut); } /* local["time_minutes"] = lang(" minutes ago", " минут назад"); local["time_minutes_l5"] = lang(" minutes ago", " минуты назад"); local["time_minute"] = lang(" minute", " минуту"); local["time_hours"] = lang(" hours", " часов"); local["time_hours_l5"] = lang(" hours", " часа"); local["time_hour"] = lang(" hour", " час"); local["time_ago"] = lang(" ago" , " назад"); local["lastseen"] = lang("last seen at ", "был в сети в "); */ string longpollReplaces(string inp) { return inp .replace("<br>", "\n") .replace("&quot;", "\"") .replace("&lt;", "<") .replace("&gt;", ">") .replace("&amp;", "&"); } T[] slice(T)(ref T[] src, int count, int offset) { try { return src[offset..(offset+count)]; //.map!(d => &d).array; } catch (RangeError e) { dbm("utils slice count: " ~ count.to!string ~ ", offset: " ~ offset.to!string); dbm("catched slice ex: " ~ e.msg); return []; } } S[] wordwrap(S)(S s, size_t mln) { auto wrplines = s.wrap(mln).split("\n"); S[] lines; foreach(ln; wrplines) { S[] crp = ["", ln]; while(crp.length > 1) { crp = cropstr(crp[1] ,mln); lines ~= crp[0]; } } return lines[0..$-1]; } private S[] cropstr(S)(S s, size_t mln) { if(s.length > mln) return [ s[0..mln], s[mln..$] ]; else return [s]; } class JoinerBidirectionalResult(RoR) if (isBidirectionalRange!RoR && isBidirectionalRange!(ElementType!RoR)) { alias rortype = ElementType!RoR; private { RoR range; rortype rfront = null, rback = null; } this(RoR r) { range = r; } private void prepareFront() { if(range.empty) return; while(range.front.empty) { range.popFront(); if(range.empty) return; } rfront = range.front; } private void prepareBack() { if(range.empty) return; while(range.back.empty) { range.popBack(); if(range.empty) return; } rback = range.back; } @property bool empty() { return range.empty; } @property auto front() { if(rfront is null) prepareFront(); assert(!empty); assert(!rfront.empty); return rfront.front; } @property auto back() { if(rback is null) prepareBack(); assert(!empty); assert(!rback.empty); return rback.back; } void popFront() { if(rfront is null) prepareFront(); else { rfront.popFront(); if(rfront.empty) { range.popFront(); prepareFront(); } } } void popBack() { if(rback is null) prepareBack(); else { rback.popBack(); if(rback.empty) { range.popBack(); prepareBack(); } } } auto moveBack() { return back; } auto save() { return this; } } auto joinerBidirectional(RoR)(RoR range) { return new JoinerBidirectionalResult!RoR(range); } auto takeBackArray(R)(R range, size_t hm) { ElementType!R[] outr; size_t iter; while(iter < hm && !range.empty) { outr ~= range.back(); range.popBack(); ++iter; } reverse(outr); return outr; } class InputRetroResult(R) if (isInputRange!R) { private R rng; this(R range) { rng = range; } void popFront() { rng.popFront(); } void popBack() { rng.popFront(); } auto front() { return rng.front; } auto back() { return rng.front; } auto empty() { return rng.empty; } auto moveBack() { return back; } auto save() { return this; } } auto inputRetro(R)(R range) { return new InputRetroResult!R(range); } void logThread(string thrname = "") { if(thrname != "") dbm("thread started for: " ~ thrname); } void unwantedExit(int sig) { Exit("killed by signal " ~ sig.to!string, 2); } void writeCurrentTrack(int sig) { auto file = File(vkcliTmpDir ~ "/current-track", "w"); auto track = mplayer.currentTrack; file.write("[" ~ track.playtime ~ "/" ~ track.duration ~ "] " ~ track.artist ~ " - " ~ track.title); } void setPosixSignals() { sigset(SIGSEGV, a => unwantedExit(a)); sigset(SIGUSR1, a => writeCurrentTrack(a)); } int gcSuspendSignal; int gcResumeSignal; void updateGcSignals() { gcSuspendSignal = SIGRTMIN; gcResumeSignal = SIGRTMIN+1; thread_term(); thread_setGCSignals(gcSuspendSignal, gcResumeSignal); thread_init(); } void usedSignalsNotify() { dbm("GC signals: " ~ gcSuspendSignal.to!string ~ " " ~ gcResumeSignal.to!string); } const uint maxuint = 4_294_967_295; const uint maxint = 2_147_483_647; const uint ridstart = 1; int genId() { long rnd = uniform(ridstart, maxuint); if(rnd > maxint) { rnd = -(rnd-maxint); } dbm("rid: " ~ rnd.to!string); return rnd.to!int; } string genStrDict = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890"; string genStr(uint strln) { string output; for(uint i; i < strln; ++i) { size_t rnd = uniform!"[)"(0, genStrDict.length); output ~= genStrDict[rnd]; } return output; } alias Repldchar = std.typecons.Flag!"useReplacementDchar"; const Repldchar repl = Repldchar.yes; wstring toUTF16wrepl(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!repl(s, i); encode(r, c); } } return cast(wstring)r; } string toUTF8wrepl(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; while (i < slen) encode(r, decode!repl(s, i)); break; } } return cast(string)r; } struct utf { ulong start, end; int spaces; } const utfranges = [ utf(19968, 40959, 1), utf(12288, 12351, 1), utf(11904, 12031, 1), utf(13312, 19903, 1), utf(63744, 64255, 1), utf(12800, 13055, 1), utf(13056, 13311, 1), utf(12736, 12783, 1), utf(12448, 12543, 1), utf(12352, 12447, 1), utf(110592, 110847, 1), utf(65280, 65519, 1) ]; uint utfLength(string inp) { uint s = 0; size_t inplen = inp.length; for (size_t i = 0; i < inplen; ) { auto ic = inp[i]; ulong c; ++s; if(ic <= 0x7F) { c = cast(ulong)ic; ++i; } else { c = cast(ulong)(decode!repl(inp, i)); } foreach (r; utfranges) { if (c >= r.start && c <= r.end) { s += r.spaces; break; } } } return s; } S replicatestr(S)(S str, ulong n) { S outstr = ""; for(ulong i = 0; i < n; ++i) { outstr ~= str; } return outstr; }
D
/** * Compiler implementation of the * $(LINK2 http://www.dlang.org, D programming language). * * Copyright: Copyright (C) 1984-1998 by Symantec * Copyright (C) 2000-2018 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: https://github.com/dlang/dmd/blob/master/src/dmd/backend/symbol.d */ module dmd.backend.symbol; version (SCPP) { version = COMPILE; version = SCPP_HTOD; } version (HTOD) { version = COMPILE; version = SCPP_HTOD; } version (MARS) { version = COMPILE; enum HYDRATE = false; enum DEHYDRATE = false; } version (COMPILE) { import core.stdc.stdio; import core.stdc.stdlib; import core.stdc.string; import dmd.backend.cdef; import dmd.backend.cc; import dmd.backend.cgcv; import dmd.backend.dlist; import dmd.backend.dt; import dmd.backend.dvec; import dmd.backend.el; import dmd.backend.global; import dmd.backend.memh; import dmd.backend.oper; import dmd.backend.ty; import dmd.backend.type; version (SCPP_HTOD) { import cpp; import dtoken; import scopeh; import msgs2; import parser; import precomp; extern (C++) void baseclass_free(baseclass_t *b); } extern (C++): alias MEM_PH_MALLOC = mem_malloc; alias MEM_PH_CALLOC = mem_calloc; alias MEM_PH_FREE = mem_free; alias MEM_PH_FREEFP = mem_freefp; alias MEM_PH_STRDUP = mem_strdup; alias MEM_PH_REALLOC = mem_realloc; alias MEM_PARF_MALLOC = mem_malloc; alias MEM_PARF_CALLOC = mem_calloc; alias MEM_PARF_REALLOC = mem_realloc; alias MEM_PARF_FREE = mem_free; alias MEM_PARF_STRDUP = mem_strdup; version (SCPP_HTOD) enum mBP = 0x20; else import dmd.backend.code_x86; void struct_free(struct_t *st) { } func_t* func_calloc() { return cast(func_t *) calloc(1, func_t.sizeof); } void func_free(func_t* f) { free(f); } /********************************* * Allocate/free symbol table. */ extern (C) Symbol **symtab_realloc(Symbol **tab, size_t symmax) { Symbol **newtab; if (config.flags2 & (CFG2phgen | CFG2phuse | CFG2phauto | CFG2phautoy)) { newtab = cast(Symbol **) MEM_PH_REALLOC(tab, symmax * (Symbol *).sizeof); } else { newtab = cast(Symbol **) realloc(tab, symmax * (Symbol *).sizeof); if (!newtab) err_nomem(); } return newtab; } Symbol **symtab_malloc(size_t symmax) { Symbol **newtab; if (config.flags2 & (CFG2phgen | CFG2phuse | CFG2phauto | CFG2phautoy)) { newtab = cast(Symbol **) MEM_PH_MALLOC(symmax * (Symbol *).sizeof); } else { newtab = cast(Symbol **) malloc(symmax * (Symbol *).sizeof); if (!newtab) err_nomem(); } return newtab; } Symbol **symtab_calloc(size_t symmax) { Symbol **newtab; if (config.flags2 & (CFG2phgen | CFG2phuse | CFG2phauto | CFG2phautoy)) { newtab = cast(Symbol **) MEM_PH_CALLOC(symmax * (Symbol *).sizeof); } else { newtab = cast(Symbol **) calloc(symmax, (Symbol *).sizeof); if (!newtab) err_nomem(); } return newtab; } void symtab_free(Symbol **tab) { if (config.flags2 & (CFG2phgen | CFG2phuse | CFG2phauto | CFG2phautoy)) MEM_PH_FREE(tab); else if (tab) free(tab); } /******************************* * Type out symbol information. */ void symbol_print(Symbol *s) { debug { version (COMPILE) { if (!s) return; printf("symbol %p '%s'\n ",s,s.Sident.ptr); printf(" Sclass = "); WRclass(cast(SC) s.Sclass); printf(" Ssymnum = %d",s.Ssymnum); printf(" Sfl = "); WRFL(cast(FL) s.Sfl); printf(" Sseg = %d\n",s.Sseg); // printf(" Ssize = x%02x\n",s.Ssize); printf(" Soffset = x%04llx",cast(ulong)s.Soffset); printf(" Sweight = %d",s.Sweight); printf(" Sflags = x%04x",cast(uint)s.Sflags); printf(" Sxtrnnum = %d\n",s.Sxtrnnum); printf(" Stype = %p",s.Stype); version (SCPP_HTOD) { printf(" Ssequence = %x", s.Ssequence); printf(" Scover = %p", s.Scover); } printf(" Sl = %p",s.Sl); printf(" Sr = %p\n",s.Sr); if (s.Sscope) printf(" Sscope = '%s'\n",s.Sscope.Sident.ptr); if (s.Stype) type_print(s.Stype); if (s.Sclass == SCmember || s.Sclass == SCfield) { printf(" Smemoff =%5lld", cast(long)s.Smemoff); printf(" Sbit =%3d",s.Sbit); printf(" Swidth =%3d\n",s.Swidth); } version (SCPP_HTOD) { if (s.Sclass == SCstruct) { printf(" Svbptr = %p, Svptr = %p\n",s.Sstruct.Svbptr,s.Sstruct.Svptr); } } } } } /********************************* * Terminate use of symbol table. */ private __gshared Symbol *keep; void symbol_term() { symbol_free(keep); } /**************************************** * Keep symbol around until symbol_term(). */ static if (TERMCODE) { void symbol_keep(Symbol *s) { symbol_debug(s); s.Sr = keep; // use Sr so symbol_free() doesn't nest keep = s; } } /**************************************** * Return alignment of symbol. */ int Symbol_Salignsize(Symbol* s) { if (s.Salignment > 0) return s.Salignment; int alignsize = type_alignsize(s.Stype); /* Reduce alignment faults when SIMD vectors * are reinterpreted cast to other types with less alignment. */ if (config.fpxmmregs && alignsize < 16 && s.Sclass == SCauto && type_size(s.Stype) == 16) { alignsize = 16; } return alignsize; } /**************************************** * Aver if Symbol is not only merely dead, but really most sincerely dead. * Params: * anyInlineAsm = true if there's any inline assembler code * Returns: * true if symbol is dead. */ bool Symbol_Sisdead(Symbol* s, bool anyInlineAsm) { version (MARS) enum vol = false; else enum vol = true; return s.Sflags & SFLdead || /* SFLdead means the optimizer found no references to it. * The rest deals with variables that the compiler never needed * to read from memory because they were cached in registers, * and so no memory needs to be allocated for them. * Code that does write those variables to memory gets NOPed out * during address assignment. */ (!anyInlineAsm && !(s.Sflags & SFLread) && s.Sflags & SFLunambig && // mTYvolatile means this variable has been reference by a nested function (vol || !(s.Stype.Tty & mTYvolatile)) && (config.flags4 & CFG4optimized || !config.fulltypes)); } /**************************************** * Determine if symbol needs a 'this' pointer. */ int Symbol_needThis(Symbol* s) { //printf("needThis() '%s'\n", Sident.ptr); debug assert(isclassmember(s)); if (s.Sclass == SCmember || s.Sclass == SCfield) return 1; if (tyfunc(s.Stype.Tty) && !(s.Sfunc.Fflags & Fstatic)) return 1; return 0; } /*********************************** * Get user name of symbol. */ char *symbol_ident(Symbol *s) { version (SCPP_HTOD) { __gshared char* noname = cast(char*)"__unnamed".ptr; switch (s.Sclass) { case SCstruct: if (s.Sstruct.Salias) s = s.Sstruct.Salias; else if (s.Sstruct.Sflags & STRnotagname) return noname; break; case SCenum: if (CPP) { if (s.Senum.SEalias) s = s.Senum.SEalias; else if (s.Senum.SEflags & SENnotagname) return noname; } break; case SCnamespace: if (s.Sident[0] == '?' && s.Sident.ptr[1] == '%') return cast(char*)"unique".ptr; // an unnamed namespace break; default: break; } } return s.Sident.ptr; } /**************************************** * Create a new symbol. */ Symbol * symbol_calloc(const(char)* id) { return symbol_calloc(id, cast(uint)strlen(id)); } Symbol * symbol_calloc(const(char)* id, uint len) { Symbol *s; //printf("sizeof(symbol)=%d, sizeof(s.Sident)=%d, len=%d\n",sizeof(symbol),sizeof(s.Sident),(int)len); s = cast(Symbol *) mem_fmalloc(Symbol.sizeof - s.Sident.length + len + 1 + 5); memset(s,0,Symbol.sizeof - s.Sident.length); version (SCPP_HTOD) { s.Ssequence = pstate.STsequence; pstate.STsequence += 1; //if (s.Ssequence == 0x21) *cast(char*)0=0; } debug { if (debugy) printf("symbol_calloc('%s') = %p\n",id,s); s.id = Symbol.IDsymbol; } memcpy(s.Sident.ptr,id,len + 1); s.Ssymnum = -1; return s; } /**************************************** * Create a symbol, given a name and type. */ Symbol * symbol_name(const(char)* name,int sclass,type *t) { return symbol_name(name, cast(uint)strlen(name), sclass, t); } Symbol * symbol_name(const(char)* name, uint len, int sclass, type *t) { type_debug(t); Symbol *s = symbol_calloc(name, len); s.Sclass = cast(char) sclass; s.Stype = t; s.Stype.Tcount++; if (tyfunc(t.Tty)) symbol_func(s); return s; } /**************************************** * Create a symbol that is an alias to another function symbol. */ Funcsym *symbol_funcalias(Funcsym *sf) { Funcsym *s; symbol_debug(sf); assert(tyfunc(sf.Stype.Tty)); if (sf.Sclass == SCfuncalias) sf = sf.Sfunc.Falias; s = cast(Funcsym *)symbol_name(sf.Sident.ptr,SCfuncalias,sf.Stype); s.Sfunc.Falias = sf; version (SCPP_HTOD) s.Scover = sf.Scover; return s; } /**************************************** * Create a symbol, give it a name, storage class and type. */ Symbol * symbol_generate(int sclass,type *t) { __gshared int tmpnum; char[4 + tmpnum.sizeof * 3 + 1] name; //printf("symbol_generate(_TMP%d)\n", tmpnum); sprintf(name.ptr,"_TMP%d",tmpnum++); Symbol *s = symbol_name(name.ptr,sclass,t); //symbol_print(s); version (MARS) s.Sflags |= SFLnodebug | SFLartifical; return s; } /**************************************** * Generate an auto symbol, and add it to the symbol table. */ Symbol * symbol_genauto(type *t) { Symbol *s; s = symbol_generate(SCauto,t); version (SCPP_HTOD) { //printf("symbol_genauto(t) '%s'\n", s.Sident.ptr); if (pstate.STdefertemps) { symbol_keep(s); s.Ssymnum = -1; } else { s.Sflags |= SFLfree; if (init_staticctor) { // variable goes into _STI_xxxx s.Ssymnum = -1; // deferred allocation //printf("test2\n"); //if (s.Sident[4] == '2') *(char*)0=0; } else { symbol_add(s); } } } else { s.Sflags |= SFLfree; symbol_add(s); } return s; } /****************************************** * Generate symbol into which we can copy the contents of expression e. */ Symbol *symbol_genauto(elem *e) { return symbol_genauto(type_fake(e.Ety)); } /****************************************** * Generate symbol into which we can copy the contents of expression e. */ Symbol *symbol_genauto(tym_t ty) { return symbol_genauto(type_fake(ty)); } /**************************************** * Add in the variants for a function symbol. */ void symbol_func(Symbol *s) { //printf("symbol_func(%s, x%x)\n", s.Sident.ptr, fregsaved); symbol_debug(s); s.Sfl = FLfunc; // Interrupt functions modify all registers // BUG: do interrupt functions really save BP? // Note that fregsaved may not be set yet s.Sregsaved = (s.Stype && tybasic(s.Stype.Tty) == TYifunc) ? cast(regm_t) mBP : fregsaved; s.Sseg = UNKNOWN; // don't know what segment it is in if (!s.Sfunc) s.Sfunc = func_calloc(); } /*************************************** * Add a field to a struct s. * Input: * s the struct symbol * name field name * t the type of the field * offset offset of the field */ void symbol_struct_addField(Symbol *s, const(char)* name, type *t, uint offset) { Symbol *s2 = symbol_name(name, SCmember, t); s2.Smemoff = offset; list_append(&s.Sstruct.Sfldlst, s2); } /******************************** * Define symbol in specified symbol table. * Returns: * pointer to symbol */ version (SCPP_HTOD) { Symbol * defsy(const(char)* p,Symbol **parent) { Symbol *s = symbol_calloc(p); symbol_addtotree(parent,s); return s; } } /******************************** * Check integrity of symbol data structure. */ debug { void symbol_check(Symbol *s) { //printf("symbol_check('%s',%p)\n",s.Sident.ptr,s); symbol_debug(s); if (s.Stype) type_debug(s.Stype); assert(cast(uint)s.Sclass < cast(uint)SCMAX); version (SCPP_HTOD) { if (s.Sscope) symbol_check(s.Sscope); if (s.Scover) symbol_check(s.Scover); } } void symbol_tree_check(Symbol *s) { while (s) { symbol_check(s); symbol_tree_check(s.Sl); s = s.Sr; } } } /******************************** * Insert symbol in specified symbol table. */ version (SCPP_HTOD) { void symbol_addtotree(Symbol **parent,Symbol *s) { Symbol *rover; byte cmp; size_t len; const(char)* p; char c; //printf("symbol_addtotree('%s',%p)\n",s.Sident.ptr,*parent); debug { symbol_tree_check(*parent); assert(!s.Sl && !s.Sr); } symbol_debug(s); p = s.Sident.ptr; c = *p; len = strlen(p); p++; rover = *parent; while (rover != null) // while we haven't run out of tree { symbol_debug(rover); if ((cmp = cast(byte)(c - rover.Sident[0])) == 0) { cmp = cast(byte)memcmp(p,rover.Sident.ptr + 1,len); // compare identifier strings if (cmp == 0) // found it if strings match { if (CPP) { Symbol *s2; switch (rover.Sclass) { case SCstruct: s2 = rover; goto case_struct; case_struct: if (s2.Sstruct.Sctor && !(s2.Sstruct.Sctor.Sfunc.Fflags & Fgen)) cpperr(EM_ctor_disallowed,p); // no ctor allowed for class rover s2.Sstruct.Sflags |= STRnoctor; goto case_cover; case_cover: // Replace rover with the new symbol s, and // have s 'cover' the tag symbol s2. // BUG: memory leak on rover if s2!=rover assert(!s2.Scover); s.Sl = rover.Sl; s.Sr = rover.Sr; s.Scover = s2; *parent = s; rover.Sl = rover.Sr = null; return; case SCenum: s2 = rover; goto case_cover; case SCtemplate: s2 = rover; s2.Stemplate.TMflags |= STRnoctor; goto case_cover; case SCalias: s2 = rover.Smemalias; if (s2.Sclass == SCstruct) goto case_struct; if (s2.Sclass == SCenum) goto case_cover; break; default: break; } } synerr(EM_multiple_def,p - 1); // symbol is already defined //symbol_undef(s); // undefine the symbol return; } } parent = (cmp < 0) ? /* if we go down left side */ &(rover.Sl) : /* then get left child */ &(rover.Sr); /* else get right child */ rover = *parent; /* get child */ } /* not in table, so insert into table */ *parent = s; /* link new symbol into tree */ L1: ; } } /************************************* * Search for symbol in multiple symbol tables, * starting with most recently nested one. * Input: * p . identifier string * Returns: * pointer to symbol * null if couldn't find it */ static if (0) { Symbol * lookupsym(const(char)* p) { return scope_search(p,SCTglobal | SCTlocal); } } /************************************* * Search for symbol in symbol table. * Input: * p . identifier string * rover . where to start looking * Returns: * pointer to symbol (null if not found) */ version (SCPP_HTOD) { Symbol * findsy(const(char)* p,Symbol *rover) { /+ #if TX86 && __DMC__ volatile int len; __asm { #if !_WIN32 push DS pop ES #endif mov EDI,p xor AL,AL mov BL,[EDI] mov ECX,-1 repne scasb not ECX mov EDX,p dec ECX inc EDX mov len,ECX mov AL,BL mov EBX,rover mov ESI,EDX test EBX,EBX je L6 cmp AL,symbol.Sident[EBX] js L2 lea EDI,symbol.Sident+1[EBX] je L5 mov EBX,symbol.Sr[EBX] jmp L3 L1: mov ECX,len L2: mov EBX,symbol.Sl[EBX] L3: test EBX,EBX je L6 L4: cmp AL,symbol.Sident[EBX] js L2 lea EDI,symbol.Sident+1[EBX] je L5 mov EBX,symbol.Sr[EBX] jmp L3 L5: rep cmpsb mov ESI,EDX js L1 je L6 mov EBX,symbol.Sr[EBX] mov ECX,len test EBX,EBX jne L4 L6: mov EAX,EBX } #else +/ size_t len; byte cmp; /* set to value of strcmp */ char c = *p; len = strlen(p); p++; // will pick up 0 on memcmp while (rover != null) // while we haven't run out of tree { symbol_debug(rover); if ((cmp = cast(byte)(c - rover.Sident[0])) == 0) { cmp = cast(byte)memcmp(p,rover.Sident.ptr + 1,len); /* compare identifier strings */ if (cmp == 0) return rover; /* found it if strings match */ } rover = (cmp < 0) ? rover.Sl : rover.Sr; } return rover; // failed to find it //#endif } } /*********************************** * Create a new symbol table. */ version (SCPP_HTOD) { void createglobalsymtab() { assert(!scope_end); if (CPP) scope_push(null,cast(scope_fp)&findsy, SCTcglobal); else scope_push(null,cast(scope_fp)&findsy, SCTglobaltag); scope_push(null,cast(scope_fp)&findsy, SCTglobal); } void createlocalsymtab() { assert(scope_end); if (!CPP) scope_push(null,cast(scope_fp)&findsy, SCTtag); scope_push(null,cast(scope_fp)&findsy, SCTlocal); } /*********************************** * Delete current symbol table and back up one. */ void deletesymtab() { Symbol *root; root = cast(Symbol *)scope_pop(); if (root) { if (funcsym_p) list_prepend(&funcsym_p.Sfunc.Fsymtree,root); else symbol_free(root); // free symbol table } if (!CPP) { root = cast(Symbol *)scope_pop(); if (root) { if (funcsym_p) list_prepend(&funcsym_p.Sfunc.Fsymtree,root); else symbol_free(root); // free symbol table } } } } /********************************* * Delete symbol from symbol table, taking care to delete * all children of a symbol. * Make sure there are no more forward references (labels, tags). * Input: * pointer to a symbol */ void meminit_free(meminit_t *m) /* helper for symbol_free() */ { list_free(&m.MIelemlist,cast(list_free_fp)&el_free); MEM_PARF_FREE(m); } void symbol_free(Symbol *s) { while (s) /* if symbol exists */ { Symbol *sr; debug { if (debugy) printf("symbol_free('%s',%p)\n",s.Sident.ptr,s); symbol_debug(s); assert(/*s.Sclass != SCunde &&*/ cast(int) s.Sclass < cast(int) SCMAX); } { type *t = s.Stype; if (t) type_debug(t); if (t && tyfunc(t.Tty) && s.Sfunc) { func_t *f = s.Sfunc; debug assert(f); blocklist_free(&f.Fstartblock); freesymtab(f.Flocsym.tab,0,f.Flocsym.top); symtab_free(f.Flocsym.tab); if (CPP) { if (f.Fflags & Fnotparent) { debug if (debugy) printf("not parent, returning\n"); return; } /* We could be freeing the symbol before it's class is */ /* freed, so remove it from the class's field list */ if (f.Fclass) { list_t tl; symbol_debug(f.Fclass); tl = list_inlist(f.Fclass.Sstruct.Sfldlst,s); if (tl) list_setsymbol(tl, null); } if (f.Foversym && f.Foversym.Sfunc) { f.Foversym.Sfunc.Fflags &= ~Fnotparent; f.Foversym.Sfunc.Fclass = null; symbol_free(f.Foversym); } if (f.Fexplicitspec) symbol_free(f.Fexplicitspec); /* If operator function, remove from list of such functions */ if (f.Fflags & Foperator) { assert(f.Foper && f.Foper < OPMAX); //if (list_inlist(cpp_operfuncs[f.Foper],s)) // list_subtract(&cpp_operfuncs[f.Foper],s); } list_free(&f.Fclassfriends,FPNULL); list_free(&f.Ffwdrefinstances,FPNULL); param_free(&f.Farglist); param_free(&f.Fptal); list_free(&f.Fexcspec,cast(list_free_fp)&type_free); version (SCPP_HTOD) token_free(f.Fbody); el_free(f.Fbaseinit); if (f.Fthunk && !(f.Fflags & Finstance)) MEM_PH_FREE(f.Fthunk); list_free(&f.Fthunks,cast(list_free_fp)&symbol_free); } list_free(&f.Fsymtree,cast(list_free_fp)&symbol_free); free(f.typesTable); func_free(f); } switch (s.Sclass) { version (SCPP_HTOD) { case SClabel: if (!s.Slabel) synerr(EM_unknown_label,s.Sident.ptr); break; } case SCstruct: version (SCPP_HTOD) { if (CPP) { struct_t *st = s.Sstruct; assert(st); list_free(&st.Sclassfriends,FPNULL); list_free(&st.Sfriendclass,FPNULL); list_free(&st.Sfriendfuncs,FPNULL); list_free(&st.Scastoverload,FPNULL); list_free(&st.Sopoverload,FPNULL); list_free(&st.Svirtual,&MEM_PH_FREEFP); list_free(&st.Sfldlst,FPNULL); symbol_free(st.Sroot); baseclass_t* b,bn; for (b = st.Sbase; b; b = bn) { bn = b.BCnext; list_free(&b.BCpublics,FPNULL); baseclass_free(b); } for (b = st.Svirtbase; b; b = bn) { bn = b.BCnext; baseclass_free(b); } for (b = st.Smptrbase; b; b = bn) { bn = b.BCnext; list_free(&b.BCmptrlist,&MEM_PH_FREEFP); baseclass_free(b); } for (b = st.Svbptrbase; b; b = bn) { bn = b.BCnext; baseclass_free(b); } param_free(&st.Sarglist); param_free(&st.Spr_arglist); struct_free(st); } } if (!CPP) { debug if (debugy) printf("freeing members %p\n",s.Sstruct.Sfldlst); list_free(&s.Sstruct.Sfldlst,FPNULL); symbol_free(s.Sstruct.Sroot); struct_free(s.Sstruct); } static if (0) /* Don't complain anymore about these, ANSI C says */ { /* it's ok */ if (t && t.Tflags & TFsizeunknown) synerr(EM_unknown_tag,s.Sident.ptr); } break; case SCenum: /* The actual member symbols are either in a local */ /* table or on the member list of a class, so we */ /* don't free them here. */ assert(s.Senum); list_free(&s.Senum.SEenumlist,FPNULL); MEM_PH_FREE(s.Senum); s.Senum = null; break; version (SCPP_HTOD) { case SCtemplate: { template_t *tm = s.Stemplate; list_free(&tm.TMinstances,FPNULL); list_free(&tm.TMmemberfuncs,cast(list_free_fp)&tmf_free); list_free(&tm.TMexplicit,cast(list_free_fp)&tme_free); list_free(&tm.TMnestedexplicit,cast(list_free_fp)&tmne_free); list_free(&tm.TMnestedfriends,cast(list_free_fp)&tmnf_free); param_free(&tm.TMptpl); param_free(&tm.TMptal); token_free(tm.TMbody); symbol_free(tm.TMpartial); list_free(&tm.TMfriends,FPNULL); MEM_PH_FREE(tm); break; } case SCnamespace: symbol_free(s.Snameroot); list_free(&s.Susing,FPNULL); break; case SCmemalias: case SCfuncalias: case SCadl: list_free(&s.Spath,FPNULL); break; } case SCparameter: case SCregpar: case SCfastpar: case SCshadowreg: case SCregister: case SCauto: vec_free(s.Srange); static if (0) { goto case SCconst; case SCconst: if (s.Sflags & (SFLvalue | SFLdtorexp)) el_free(s.Svalue); } break; default: break; } if (s.Sflags & (SFLvalue | SFLdtorexp)) el_free(s.Svalue); if (s.Sdt) dt_free(s.Sdt); type_free(t); symbol_free(s.Sl); version (SCPP_HTOD) { if (s.Scover) symbol_free(s.Scover); } sr = s.Sr; debug { s.id = 0; } mem_ffree(s); } s = sr; } } /******************************** * Undefine a symbol. * Assume error msg was already printed. */ static if (0) { private void symbol_undef(Symbol *s) { s.Sclass = SCunde; s.Ssymnum = -1; type_free(s.Stype); /* free type data */ s.Stype = null; } } /***************************** * Add symbol to current symbol array. */ SYMIDX symbol_add(Symbol *s) { SYMIDX sitop; //printf("symbol_add('%s')\n", s.Sident.ptr); debug { if (!s || !s.Sident[0]) { printf("bad symbol\n"); assert(0); } } symbol_debug(s); if (pstate.STinsizeof) { symbol_keep(s); return -1; } debug assert(cstate.CSpsymtab); sitop = cstate.CSpsymtab.top; assert(sitop <= cstate.CSpsymtab.symmax); if (sitop == cstate.CSpsymtab.symmax) { debug enum SYMINC = 1; /* flush out reallocation bugs */ else enum SYMINC = 99; cstate.CSpsymtab.symmax += (cstate.CSpsymtab == &globsym) ? SYMINC : 1; //assert(cstate.CSpsymtab.symmax * (Symbol *).sizeof < 4096 * 4); cstate.CSpsymtab.tab = symtab_realloc(cstate.CSpsymtab.tab, cstate.CSpsymtab.symmax); } cstate.CSpsymtab.tab[sitop] = s; debug if (debugy) printf("symbol_add(%p '%s') = %d\n",s,s.Sident.ptr,cstate.CSpsymtab.top); assert(s.Ssymnum == -1); return s.Ssymnum = cstate.CSpsymtab.top++; } /**************************** * Free up the symbol table, from symbols n1 through n2, not * including n2. */ void freesymtab(Symbol **stab,SYMIDX n1,SYMIDX n2) { SYMIDX si; if (!stab) return; debug if (debugy) printf("freesymtab(from %d to %d)\n",n1,n2); assert(stab != globsym.tab || (n1 <= n2 && n2 <= globsym.top)); for (si = n1; si < n2; si++) { Symbol *s; s = stab[si]; if (s && s.Sflags & SFLfree) { stab[si] = null; debug { if (debugy) printf("Freeing %p '%s' (%d)\n",s,s.Sident.ptr,si); symbol_debug(s); } s.Sl = s.Sr = null; s.Ssymnum = -1; symbol_free(s); } } } /**************************** * Create a copy of a symbol. */ Symbol * symbol_copy(Symbol *s) { Symbol *scopy; type *t; symbol_debug(s); /*printf("symbol_copy(%s)\n",s.Sident.ptr);*/ scopy = symbol_calloc(s.Sident.ptr); memcpy(scopy,s,Symbol.sizeof - s.Sident.sizeof); scopy.Sl = scopy.Sr = scopy.Snext = null; scopy.Ssymnum = -1; if (scopy.Sdt) { scope dtb = new DtBuilder(); dtb.nzeros(cast(uint)type_size(scopy.Stype)); scopy.Sdt = dtb.finish(); } if (scopy.Sflags & (SFLvalue | SFLdtorexp)) scopy.Svalue = el_copytree(s.Svalue); t = scopy.Stype; if (t) { t.Tcount++; /* one more parent of the type */ type_debug(t); } return scopy; } /******************************* * Search list for a symbol with an identifier that matches. * Returns: * pointer to matching symbol * null if not found */ version (SCPP_HTOD) { Symbol * symbol_searchlist(symlist_t sl,const(char)* vident) { Symbol *s; debug int count = 0; //printf("searchlist(%s)\n",vident); for (; sl; sl = list_next(sl)) { s = list_symbol(sl); symbol_debug(s); /*printf("\tcomparing with %s\n",s.Sident.ptr);*/ if (strcmp(vident,s.Sident.ptr) == 0) return s; debug assert(++count < 300); /* prevent infinite loops */ } return null; } /*************************************** * Search for symbol in sequence of symbol tables. * Input: * glbl !=0 if global symbol table only */ Symbol *symbol_search(const(char)* id) { Scope *sc; if (CPP) { uint sct; sct = pstate.STclasssym ? SCTclass : 0; sct |= SCTmfunc | SCTlocal | SCTwith | SCTglobal | SCTnspace | SCTtemparg | SCTtempsym; return scope_searchx(id,sct,&sc); } else return scope_searchx(id,SCTglobal | SCTlocal,&sc); } } /******************************************* * Hydrate a symbol tree. */ static if (HYDRATE) { void symbol_tree_hydrate(Symbol **ps) { Symbol *s; while (isdehydrated(*ps)) /* if symbol is dehydrated */ { s = symbol_hydrate(ps); symbol_debug(s); if (s.Scover) symbol_hydrate(&s.Scover); symbol_tree_hydrate(&s.Sl); ps = &s.Sr; } } } /******************************************* * Dehydrate a symbol tree. */ static if (DEHYDRATE) { void symbol_tree_dehydrate(Symbol **ps) { Symbol *s; while ((s = *ps) != null && !isdehydrated(s)) /* if symbol exists */ { symbol_debug(s); symbol_dehydrate(ps); version (DEBUG_XSYMGEN) { if (xsym_gen && ph_in_head(s)) return; } symbol_dehydrate(&s.Scover); symbol_tree_dehydrate(&s.Sl); ps = &s.Sr; } } } /******************************************* * Hydrate a symbol. */ static if (HYDRATE) { Symbol *symbol_hydrate(Symbol **ps) { Symbol *s; s = *ps; if (isdehydrated(s)) /* if symbol is dehydrated */ { type *t; struct_t *st; s = cast(Symbol *) ph_hydrate(cast(void**)ps); debug debugy && printf("symbol_hydrate('%s')\n",s.Sident.ptr); symbol_debug(s); if (!isdehydrated(s.Stype)) // if this symbol is already dehydrated return s; // no need to do it again if (pstate.SThflag != FLAG_INPLACE && s.Sfl != FLreg) s.Sxtrnnum = 0; // not written to .OBJ file yet type_hydrate(&s.Stype); //printf("symbol_hydrate(%p, '%s', t = %p)\n",s,s.Sident.ptr,s.Stype); t = s.Stype; if (t) type_debug(t); if (t && tyfunc(t.Tty) && ph_hydrate(cast(void**)&s.Sfunc)) { func_t *f = s.Sfunc; SYMIDX si; debug assert(f); list_hydrate(&f.Fsymtree,cast(list_free_fp)&symbol_tree_hydrate); blocklist_hydrate(&f.Fstartblock); ph_hydrate(cast(void**)&f.Flocsym.tab); for (si = 0; si < f.Flocsym.top; si++) symbol_hydrate(&f.Flocsym.tab[si]); srcpos_hydrate(&f.Fstartline); srcpos_hydrate(&f.Fendline); symbol_hydrate(&f.F__func__); if (CPP) { symbol_hydrate(&f.Fparsescope); Classsym_hydrate(&f.Fclass); symbol_hydrate(&f.Foversym); symbol_hydrate(&f.Fexplicitspec); symbol_hydrate(&f.Fsurrogatesym); list_hydrate(&f.Fclassfriends,cast(list_free_fp)&symbol_hydrate); el_hydrate(&f.Fbaseinit); token_hydrate(&f.Fbody); symbol_hydrate(&f.Falias); list_hydrate(&f.Fthunks,cast(list_free_fp)&symbol_hydrate); if (f.Fflags & Finstance) symbol_hydrate(&f.Ftempl); else thunk_hydrate(&f.Fthunk); param_hydrate(&f.Farglist); param_hydrate(&f.Fptal); list_hydrate(&f.Ffwdrefinstances,cast(list_free_fp)&symbol_hydrate); list_hydrate(&f.Fexcspec,cast(list_free_fp)&type_hydrate); } } if (CPP) symbol_hydrate(&s.Sscope); switch (s.Sclass) { case SCstruct: if (CPP) { st = cast(struct_t *) ph_hydrate(cast(void**)&s.Sstruct); assert(st); symbol_tree_hydrate(&st.Sroot); ph_hydrate(cast(void**)&st.Spvirtder); list_hydrate(&st.Sfldlst,cast(list_free_fp)&symbol_hydrate); list_hydrate(&st.Svirtual,cast(list_free_fp)&mptr_hydrate); list_hydrate(&st.Sopoverload,cast(list_free_fp)&symbol_hydrate); list_hydrate(&st.Scastoverload,cast(list_free_fp)&symbol_hydrate); list_hydrate(&st.Sclassfriends,cast(list_free_fp)&symbol_hydrate); list_hydrate(&st.Sfriendclass,cast(list_free_fp)&symbol_hydrate); list_hydrate(&st.Sfriendfuncs,cast(list_free_fp)&symbol_hydrate); assert(!st.Sinlinefuncs); baseclass_hydrate(&st.Sbase); baseclass_hydrate(&st.Svirtbase); baseclass_hydrate(&st.Smptrbase); baseclass_hydrate(&st.Sprimary); baseclass_hydrate(&st.Svbptrbase); ph_hydrate(cast(void**)&st.Svecctor); ph_hydrate(cast(void**)&st.Sctor); ph_hydrate(cast(void**)&st.Sdtor); ph_hydrate(cast(void**)&st.Sprimdtor); ph_hydrate(cast(void**)&st.Spriminv); ph_hydrate(cast(void**)&st.Sscaldeldtor); ph_hydrate(cast(void**)&st.Sinvariant); ph_hydrate(cast(void**)&st.Svptr); ph_hydrate(cast(void**)&st.Svtbl); ph_hydrate(cast(void**)&st.Sopeq); ph_hydrate(cast(void**)&st.Sopeq2); ph_hydrate(cast(void**)&st.Scpct); ph_hydrate(cast(void**)&st.Sveccpct); ph_hydrate(cast(void**)&st.Salias); ph_hydrate(cast(void**)&st.Stempsym); param_hydrate(&st.Sarglist); param_hydrate(&st.Spr_arglist); ph_hydrate(cast(void**)&st.Svbptr); ph_hydrate(cast(void**)&st.Svbptr_parent); ph_hydrate(cast(void**)&st.Svbtbl); } else { ph_hydrate(cast(void**)&s.Sstruct); symbol_tree_hydrate(&s.Sstruct.Sroot); list_hydrate(&s.Sstruct.Sfldlst,cast(list_free_fp)&symbol_hydrate); } break; case SCenum: assert(s.Senum); ph_hydrate(cast(void**)&s.Senum); if (CPP) { ph_hydrate(cast(void**)&s.Senum.SEalias); list_hydrate(&s.Senum.SEenumlist,cast(list_free_fp)&symbol_hydrate); } break; case SCtemplate: { template_t *tm; tm = cast(template_t *) ph_hydrate(cast(void**)&s.Stemplate); list_hydrate(&tm.TMinstances,cast(list_free_fp)&symbol_hydrate); list_hydrate(&tm.TMfriends,cast(list_free_fp)&symbol_hydrate); param_hydrate(&tm.TMptpl); param_hydrate(&tm.TMptal); token_hydrate(&tm.TMbody); list_hydrate(&tm.TMmemberfuncs,cast(list_free_fp)&tmf_hydrate); list_hydrate(&tm.TMexplicit,cast(list_free_fp)&tme_hydrate); list_hydrate(&tm.TMnestedexplicit,cast(list_free_fp)&tmne_hydrate); list_hydrate(&tm.TMnestedfriends,cast(list_free_fp)&tmnf_hydrate); ph_hydrate(cast(void**)&tm.TMnext); symbol_hydrate(&tm.TMpartial); symbol_hydrate(&tm.TMprimary); break; } case SCnamespace: symbol_tree_hydrate(&s.Snameroot); list_hydrate(&s.Susing,cast(list_free_fp)&symbol_hydrate); break; case SCmemalias: case SCfuncalias: case SCadl: list_hydrate(&s.Spath,cast(list_free_fp)&symbol_hydrate); goto case SCalias; case SCalias: ph_hydrate(cast(void**)&s.Smemalias); break; default: if (s.Sflags & (SFLvalue | SFLdtorexp)) el_hydrate(&s.Svalue); break; } { dt_t **pdt; dt_t *dt; for (pdt = &s.Sdt; isdehydrated(*pdt); pdt = &dt.DTnext) { dt = cast(dt_t *) ph_hydrate(cast(void**)pdt); switch (dt.dt) { case DT_abytes: case DT_nbytes: ph_hydrate(cast(void**)&dt.DTpbytes); break; case DT_xoff: symbol_hydrate(&dt.DTsym); break; default: break; } } } if (s.Scover) symbol_hydrate(&s.Scover); } return s; } } /******************************************* * Dehydrate a symbol. */ static if (DEHYDRATE) { void symbol_dehydrate(Symbol **ps) { Symbol *s; if ((s = *ps) != null && !isdehydrated(s)) /* if symbol exists */ { type *t; struct_t *st; debug if (debugy) printf("symbol_dehydrate('%s')\n",s.Sident.ptr); ph_dehydrate(ps); version (DEBUG_XSYMGEN) { if (xsym_gen && ph_in_head(s)) return; } symbol_debug(s); t = s.Stype; if (isdehydrated(t)) return; type_dehydrate(&s.Stype); if (tyfunc(t.Tty) && !isdehydrated(s.Sfunc)) { func_t *f = s.Sfunc; SYMIDX si; debug assert(f); ph_dehydrate(&s.Sfunc); list_dehydrate(&f.Fsymtree,cast(list_free_fp)&symbol_tree_dehydrate); blocklist_dehydrate(&f.Fstartblock); assert(!isdehydrated(&f.Flocsym.tab)); version (DEBUG_XSYMGEN) { if (!xsym_gen || !ph_in_head(f.Flocsym.tab)) for (si = 0; si < f.Flocsym.top; si++) symbol_dehydrate(&f.Flocsym.tab[si]); } else { for (si = 0; si < f.Flocsym.top; si++) symbol_dehydrate(&f.Flocsym.tab[si]); } ph_dehydrate(&f.Flocsym.tab); srcpos_dehydrate(&f.Fstartline); srcpos_dehydrate(&f.Fendline); symbol_dehydrate(&f.F__func__); if (CPP) { symbol_dehydrate(&f.Fparsescope); ph_dehydrate(&f.Fclass); symbol_dehydrate(&f.Foversym); symbol_dehydrate(&f.Fexplicitspec); symbol_dehydrate(&f.Fsurrogatesym); list_dehydrate(&f.Fclassfriends,FPNULL); el_dehydrate(&f.Fbaseinit); version (DEBUG_XSYMGEN) { if (xsym_gen && s.Sclass == SCfunctempl) ph_dehydrate(&f.Fbody); else token_dehydrate(&f.Fbody); } else token_dehydrate(&f.Fbody); symbol_dehydrate(&f.Falias); list_dehydrate(&f.Fthunks,cast(list_free_fp)&symbol_dehydrate); if (f.Fflags & Finstance) symbol_dehydrate(&f.Ftempl); else thunk_dehydrate(&f.Fthunk); //#if !TX86 && DEBUG_XSYMGEN // if (xsym_gen && s.Sclass == SCfunctempl) // ph_dehydrate(&f.Farglist); // else //#endif param_dehydrate(&f.Farglist); param_dehydrate(&f.Fptal); list_dehydrate(&f.Ffwdrefinstances,cast(list_free_fp)&symbol_dehydrate); list_dehydrate(&f.Fexcspec,cast(list_free_fp)&type_dehydrate); } } if (CPP) ph_dehydrate(&s.Sscope); switch (s.Sclass) { case SCstruct: if (CPP) { st = s.Sstruct; if (isdehydrated(st)) break; ph_dehydrate(&s.Sstruct); assert(st); symbol_tree_dehydrate(&st.Sroot); ph_dehydrate(&st.Spvirtder); list_dehydrate(&st.Sfldlst,cast(list_free_fp)&symbol_dehydrate); list_dehydrate(&st.Svirtual,cast(list_free_fp)&mptr_dehydrate); list_dehydrate(&st.Sopoverload,cast(list_free_fp)&symbol_dehydrate); list_dehydrate(&st.Scastoverload,cast(list_free_fp)&symbol_dehydrate); list_dehydrate(&st.Sclassfriends,cast(list_free_fp)&symbol_dehydrate); list_dehydrate(&st.Sfriendclass,cast(list_free_fp)&ph_dehydrate); list_dehydrate(&st.Sfriendfuncs,cast(list_free_fp)&ph_dehydrate); assert(!st.Sinlinefuncs); baseclass_dehydrate(&st.Sbase); baseclass_dehydrate(&st.Svirtbase); baseclass_dehydrate(&st.Smptrbase); baseclass_dehydrate(&st.Sprimary); baseclass_dehydrate(&st.Svbptrbase); ph_dehydrate(&st.Svecctor); ph_dehydrate(&st.Sctor); ph_dehydrate(&st.Sdtor); ph_dehydrate(&st.Sprimdtor); ph_dehydrate(&st.Spriminv); ph_dehydrate(&st.Sscaldeldtor); ph_dehydrate(&st.Sinvariant); ph_dehydrate(&st.Svptr); ph_dehydrate(&st.Svtbl); ph_dehydrate(&st.Sopeq); ph_dehydrate(&st.Sopeq2); ph_dehydrate(&st.Scpct); ph_dehydrate(&st.Sveccpct); ph_dehydrate(&st.Salias); ph_dehydrate(&st.Stempsym); param_dehydrate(&st.Sarglist); param_dehydrate(&st.Spr_arglist); ph_dehydrate(&st.Svbptr); ph_dehydrate(&st.Svbptr_parent); ph_dehydrate(&st.Svbtbl); } else { symbol_tree_dehydrate(&s.Sstruct.Sroot); list_dehydrate(&s.Sstruct.Sfldlst,cast(list_free_fp)&symbol_dehydrate); ph_dehydrate(&s.Sstruct); } break; case SCenum: assert(s.Senum); if (!isdehydrated(s.Senum)) { if (CPP) { ph_dehydrate(&s.Senum.SEalias); list_dehydrate(&s.Senumlist,cast(list_free_fp)&ph_dehydrate); } ph_dehydrate(&s.Senum); } break; case SCtemplate: { template_t *tm; tm = s.Stemplate; if (!isdehydrated(tm)) { ph_dehydrate(&s.Stemplate); list_dehydrate(&tm.TMinstances,cast(list_free_fp)&symbol_dehydrate); list_dehydrate(&tm.TMfriends,cast(list_free_fp)&symbol_dehydrate); list_dehydrate(&tm.TMnestedfriends,cast(list_free_fp)&tmnf_dehydrate); param_dehydrate(&tm.TMptpl); param_dehydrate(&tm.TMptal); token_dehydrate(&tm.TMbody); list_dehydrate(&tm.TMmemberfuncs,cast(list_free_fp)&tmf_dehydrate); list_dehydrate(&tm.TMexplicit,cast(list_free_fp)&tme_dehydrate); list_dehydrate(&tm.TMnestedexplicit,cast(list_free_fp)&tmne_dehydrate); ph_dehydrate(&tm.TMnext); symbol_dehydrate(&tm.TMpartial); symbol_dehydrate(&tm.TMprimary); } break; } case SCnamespace: symbol_tree_dehydrate(&s.Snameroot); list_dehydrate(&s.Susing,cast(list_free_fp)&symbol_dehydrate); break; case SCmemalias: case SCfuncalias: case SCadl: list_dehydrate(&s.Spath,cast(list_free_fp)&symbol_dehydrate); case SCalias: ph_dehydrate(&s.Smemalias); break; default: if (s.Sflags & (SFLvalue | SFLdtorexp)) el_dehydrate(&s.Svalue); break; } { dt_t **pdt; dt_t *dt; for (pdt = &s.Sdt; (dt = *pdt) != null && !isdehydrated(dt); pdt = &dt.DTnext) { ph_dehydrate(pdt); switch (dt.dt) { case DT_abytes: case DT_nbytes: ph_dehydrate(&dt.DTpbytes); break; case DT_xoff: symbol_dehydrate(&dt.DTsym); break; } } } if (s.Scover) symbol_dehydrate(&s.Scover); } } } /*************************** * Dehydrate threaded list of symbols. */ static if (DEHYDRATE) { void symbol_symdefs_dehydrate(Symbol **ps) { Symbol *s; for (; *ps; ps = &s.Snext) { s = *ps; symbol_debug(s); //printf("symbol_symdefs_dehydrate(%p, '%s')\n",s,s.Sident.ptr); symbol_dehydrate(ps); } } } /*************************** * Hydrate threaded list of symbols. * Input: * *psx start of threaded list * *parent root of symbol table to add symbol into * flag !=0 means add onto existing stuff * 0 means hydrate in place */ version (SCPP_HTOD) { void symbol_symdefs_hydrate(Symbol **psx,Symbol **parent,int flag) { Symbol *s; //printf("symbol_symdefs_hydrate(flag = %d)\n",flag); debug { int count = 0; if (flag) symbol_tree_check(*parent); } for (; *psx; psx = &s.Snext) { //printf("%p ",*psx); debug count++; s = dohydrate ? symbol_hydrate(psx) : *psx; //if (s.Sclass == SCstruct) //printf("symbol_symdefs_hydrate(%p, '%s')\n",s,s.Sident.ptr); symbol_debug(s); static if (0) { if (tyfunc(s.Stype.Tty)) { Outbuffer buf; char *p1; p1 = param_tostring(&buf,s.Stype); printf("'%s%s'\n",cpp_prettyident(s),p1); } } type_debug(s.Stype); if (flag) { char *p; Symbol **ps; Symbol *rover; char c; size_t len; p = s.Sident.ptr; c = *p; // Put symbol s into symbol table static if (MMFIO) { if (s.Sl || s.Sr) // avoid writing to page if possible s.Sl = s.Sr = null; } else s.Sl = s.Sr = null; len = strlen(p); p++; ps = parent; while ((rover = *ps) != null) { byte cmp; if ((cmp = cast(byte)(c - rover.Sident[0])) == 0) { cmp = cast(byte)memcmp(p,rover.Sident.ptr + 1,len); // compare identifier strings if (cmp == 0) { if (CPP && tyfunc(s.Stype.Tty) && tyfunc(rover.Stype.Tty)) { Symbol **psym; Symbol *sn; Symbol *so; so = s; do { // Tack onto end of overloaded function list for (psym = &rover; *psym; psym = &(*psym).Sfunc.Foversym) { if (cpp_funccmp(so, *psym)) { //printf("function '%s' already in list\n",so.Sident.ptr); goto L2; } } //printf("appending '%s' to rover\n",so.Sident.ptr); *psym = so; L2: sn = so.Sfunc.Foversym; so.Sfunc.Foversym = null; so = sn; } while (so); //printf("overloading...\n"); } else if (s.Sclass == SCstruct) { if (CPP && rover.Scover) { ps = &rover.Scover; rover = *ps; } else if (rover.Sclass == SCstruct) { if (!(s.Stype.Tflags & TFforward)) { // Replace rover with s in symbol table //printf("Replacing '%s'\n",s.Sident.ptr); *ps = s; s.Sl = rover.Sl; s.Sr = rover.Sr; rover.Sl = rover.Sr = null; rover.Stype.Ttag = cast(Classsym *)s; symbol_keep(rover); } else s.Stype.Ttag = cast(Classsym *)rover; } } goto L1; } } ps = (cmp < 0) ? /* if we go down left side */ &rover.Sl : &rover.Sr; } *ps = s; if (s.Sclass == SCcomdef) { s.Sclass = SCglobal; outcommon(s,type_size(s.Stype)); } } L1: ; } // for debug { if (flag) symbol_tree_check(*parent); printf("%d symbols hydrated\n",count); } } } static if (0) { /************************************* * Put symbol table s into parent symbol table. */ void symboltable_hydrate(Symbol *s,Symbol **parent) { while (s) { Symbol* sl,sr; char *p; symbol_debug(s); sl = s.Sl; sr = s.Sr; p = s.Sident.ptr; //printf("symboltable_hydrate('%s')\n",p); /* Put symbol s into symbol table */ { Symbol **ps; Symbol *rover; int c = *p; ps = parent; while ((rover = *ps) != null) { int cmp; if ((cmp = c - rover.Sident[0]) == 0) { cmp = strcmp(p,rover.Sident.ptr); /* compare identifier strings */ if (cmp == 0) { if (CPP && tyfunc(s.Stype.Tty) && tyfunc(rover.Stype.Tty)) { Symbol **ps; Symbol *sn; do { // Tack onto end of overloaded function list for (ps = &rover; *ps; ps = &(*ps).Sfunc.Foversym) { if (cpp_funccmp(s, *ps)) goto L2; } s.Sl = s.Sr = null; *ps = s; L2: sn = s.Sfunc.Foversym; s.Sfunc.Foversym = null; s = sn; } while (s); } else { if (!typematch(s.Stype,rover.Stype,0)) { // cpp_predefine() will define this again if (type_struct(rover.Stype) && rover.Sstruct.Sflags & STRpredef) { s.Sl = s.Sr = null; symbol_keep(s); } else synerr(EM_multiple_def,p); // already defined } } goto L1; } } ps = (cmp < 0) ? /* if we go down left side */ &rover.Sl : &rover.Sr; } { s.Sl = s.Sr = null; *ps = s; } } L1: symboltable_hydrate(sl,parent); s = sr; } } } /************************************ * Hydrate/dehydrate an mptr_t. */ static if (HYDRATE) { private void mptr_hydrate(mptr_t **pm) { mptr_t *m; m = cast(mptr_t *) ph_hydrate(cast(void**)pm); symbol_hydrate(&m.MPf); symbol_hydrate(&m.MPparent); } } static if (DEHYDRATE) { private void mptr_dehydrate(mptr_t **pm) { mptr_t *m; m = *pm; if (m && !isdehydrated(m)) { ph_dehydrate(pm); version (DEBUG_XSYMGEN) { if (xsym_gen && ph_in_head(m.MPf)) ph_dehydrate(&m.MPf); else symbol_dehydrate(&m.MPf); } else symbol_dehydrate(&m.MPf); symbol_dehydrate(&m.MPparent); } } } /************************************ * Hydrate/dehydrate a baseclass_t. */ static if (HYDRATE) { private void baseclass_hydrate(baseclass_t **pb) { baseclass_t *b; assert(pb); while (isdehydrated(*pb)) { b = cast(baseclass_t *) ph_hydrate(cast(void**)pb); ph_hydrate(cast(void**)&b.BCbase); ph_hydrate(cast(void**)&b.BCpbase); list_hydrate(&b.BCpublics,cast(list_free_fp)&symbol_hydrate); list_hydrate(&b.BCmptrlist,cast(list_free_fp)&mptr_hydrate); symbol_hydrate(&b.BCvtbl); Classsym_hydrate(&b.BCparent); pb = &b.BCnext; } } } /********************************** * Dehydrate a baseclass_t. */ static if (DEHYDRATE) { private void baseclass_dehydrate(baseclass_t **pb) { baseclass_t *b; while ((b = *pb) != null && !isdehydrated(b)) { ph_dehydrate(pb); version (DEBUG_XSYMGEN) { if (xsym_gen && ph_in_head(b)) return; } ph_dehydrate(&b.BCbase); ph_dehydrate(&b.BCpbase); list_dehydrate(&b.BCpublics,cast(list_free_fp)&symbol_dehydrate); list_dehydrate(&b.BCmptrlist,cast(list_free_fp)&mptr_dehydrate); symbol_dehydrate(&b.BCvtbl); Classsym_dehydrate(&b.BCparent); pb = &b.BCnext; } } } /*************************** * Look down baseclass list to find sbase. * Returns: * null not found * pointer to baseclass */ baseclass_t *baseclass_find(baseclass_t *bm,Classsym *sbase) { symbol_debug(sbase); for (; bm; bm = bm.BCnext) if (bm.BCbase == sbase) break; return bm; } baseclass_t *baseclass_find_nest(baseclass_t *bm,Classsym *sbase) { symbol_debug(sbase); for (; bm; bm = bm.BCnext) { if (bm.BCbase == sbase || baseclass_find_nest(bm.BCbase.Sstruct.Sbase, sbase)) break; } return bm; } /****************************** * Calculate number of baseclasses in list. */ int baseclass_nitems(baseclass_t *b) { int i; for (i = 0; b; b = b.BCnext) i++; return i; } /***************************** * Go through symbol table preparing it to be written to a precompiled * header. That means removing references to things in the .OBJ file. */ version (SCPP_HTOD) { void symboltable_clean(Symbol *s) { while (s) { struct_t *st; //printf("clean('%s')\n",s.Sident.ptr); if (config.fulltypes != CVTDB && s.Sxtrnnum && s.Sfl != FLreg) s.Sxtrnnum = 0; // eliminate debug info type index switch (s.Sclass) { case SCstruct: s.Stypidx = 0; st = s.Sstruct; assert(st); symboltable_clean(st.Sroot); //list_apply(&st.Sfldlst,cast(list_free_fp)&symboltable_clean); break; case SCtypedef: case SCenum: s.Stypidx = 0; break; case SCtemplate: { template_t *tm = s.Stemplate; list_apply(&tm.TMinstances,cast(list_free_fp)&symboltable_clean); break; } case SCnamespace: symboltable_clean(s.Snameroot); break; default: if (s.Sxtrnnum && s.Sfl != FLreg) s.Sxtrnnum = 0; // eliminate external symbol index if (tyfunc(s.Stype.Tty)) { func_t *f = s.Sfunc; SYMIDX si; debug assert(f); list_apply(&f.Fsymtree,cast(list_free_fp)&symboltable_clean); for (si = 0; si < f.Flocsym.top; si++) symboltable_clean(f.Flocsym.tab[si]); if (f.Foversym) symboltable_clean(f.Foversym); if (f.Fexplicitspec) symboltable_clean(f.Fexplicitspec); } break; } if (s.Sl) symboltable_clean(s.Sl); if (s.Scover) symboltable_clean(s.Scover); s = s.Sr; } } } version (SCPP_HTOD) { /* * Balance our symbol tree in place. This is nice for precompiled headers, since they * will typically be written out once, but read in many times. We balance the tree in * place by traversing the tree inorder and writing the pointers out to an ordered * list. Once we have a list of symbol pointers, we can create a tree by recursively * dividing the list, using the midpoint of each division as the new root for that * subtree. */ struct Balance { uint nsyms; Symbol **array; uint index; } private __gshared Balance balance; private void count_symbols(Symbol *s) { while (s) { balance.nsyms++; switch (s.Sclass) { case SCnamespace: symboltable_balance(&s.Snameroot); break; case SCstruct: symboltable_balance(&s.Sstruct.Sroot); break; default: break; } count_symbols(s.Sl); s = s.Sr; } } private void place_in_array(Symbol *s) { while (s) { place_in_array(s.Sl); balance.array[balance.index++] = s; s = s.Sr; } } /* * Create a tree in place by subdividing between lo and hi inclusive, using i * as the root for the tree. When the lo-hi interval is one, we've either * reached a leaf or an empty node. We subdivide below i by halving the interval * between i and lo, and using i-1 as our new hi point. A similar subdivision * is created above i. */ private Symbol * create_tree(int i, int lo, int hi) { Symbol *s = balance.array[i]; if (i < lo || i > hi) /* empty node ? */ return null; assert(cast(uint) i < balance.nsyms); if (i == lo && i == hi) { /* leaf node ? */ s.Sl = null; s.Sr = null; return s; } s.Sl = create_tree((i + lo) / 2, lo, i - 1); s.Sr = create_tree((i + hi + 1) / 2, i + 1, hi); return s; } enum METRICS = false; void symboltable_balance(Symbol **ps) { Balance balancesave; static if (METRICS) { clock_t ticks; printf("symbol table before balance:\n"); symbol_table_metrics(); ticks = clock(); } balancesave = balance; // so we can nest balance.nsyms = 0; count_symbols(*ps); //printf("Number of global symbols = %d\n",balance.nsyms); // Use malloc instead of mem because of pagesize limits balance.array = cast(Symbol **) malloc(balance.nsyms * (Symbol *).sizeof); if (!balance.array) goto Lret; // no error, just don't balance balance.index = 0; place_in_array(*ps); *ps = create_tree(balance.nsyms / 2, 0, balance.nsyms - 1); free(balance.array); static if (METRICS) { printf("time to balance: %ld\n", clock() - ticks); printf("symbol table after balance:\n"); symbol_table_metrics(); } Lret: balance = balancesave; } } /***************************************** * Symbol table search routine for members of structs, given that * we don't know which struct it is in. * Give error message if it appears more than once. * Returns: * null member not found * symbol* symbol matching member */ version (SCPP_HTOD) { struct Paramblock // to minimize stack usage in helper function { const(char)* id; // identifier we are looking for Symbol *sm; // where to put result Symbol *s; } private void membersearchx(Paramblock *p,Symbol *s) { Symbol *sm; list_t sl; while (s) { symbol_debug(s); switch (s.Sclass) { case SCstruct: for (sl = s.Sstruct.Sfldlst; sl; sl = list_next(sl)) { sm = list_symbol(sl); symbol_debug(sm); if ((sm.Sclass == SCmember || sm.Sclass == SCfield) && strcmp(p.id,sm.Sident.ptr) == 0) { if (p.sm && p.sm.Smemoff != sm.Smemoff) synerr(EM_ambig_member,p.id,s.Sident.ptr,p.s.Sident.ptr); // ambiguous reference to id p.s = s; p.sm = sm; break; } } break; default: break; } if (s.Sl) membersearchx(p,s.Sl); s = s.Sr; } } Symbol *symbol_membersearch(const(char)* id) { list_t sl; Paramblock pb; Scope *sc; pb.id = id; pb.sm = null; for (sc = scope_end; sc; sc = sc.next) { if (sc.sctype & (CPP ? (SCTglobal | SCTlocal) : (SCTglobaltag | SCTtag))) membersearchx(cast(Paramblock *)&pb,cast(Symbol *)sc.root); } return pb.sm; } /******************************************* * Generate debug info for global struct tag symbols. */ private void symbol_gendebuginfox(Symbol *s) { for (; s; s = s.Sr) { if (s.Sl) symbol_gendebuginfox(s.Sl); if (s.Scover) symbol_gendebuginfox(s.Scover); switch (s.Sclass) { case SCenum: if (CPP && s.Senum.SEflags & SENnotagname) break; goto Lout; case SCstruct: if (s.Sstruct.Sflags & STRanonymous) break; goto Lout; case SCtypedef: Lout: if (!s.Stypidx) cv_outsym(s); break; default: break; } } } void symbol_gendebuginfo() { Scope *sc; for (sc = scope_end; sc; sc = sc.next) { if (sc.sctype & (SCTglobaltag | SCTglobal)) symbol_gendebuginfox(cast(Symbol *)sc.root); } } } /************************************* * Reset Symbol so that it's now an "extern" to the next obj file being created. */ void symbol_reset(Symbol *s) { s.Soffset = 0; s.Sxtrnnum = 0; s.Stypidx = 0; s.Sflags &= ~(STRoutdef | SFLweak); s.Sdw_ref_idx = 0; if (s.Sclass == SCglobal || s.Sclass == SCcomdat || s.Sfl == FLudata || s.Sclass == SCstatic) { s.Sclass = SCextern; s.Sfl = FLextern; } } }
D
module hunt.wechat.bean.media.MediaGetResult; import hunt.wechat.bean.BaseResult; class MediaGetResult : BaseResult{ private string filename; private string contentType; private byte[] bytes; private string video_url; //如果返回的是视频消息素材 public string getFilename() { return filename; } public void setFilename(string filename) { this.filename = filename; } public string getContentType() { return contentType; } public void setContentType(string contentType) { this.contentType = contentType; } public byte[] getBytes() { return bytes; } public void setBytes(byte[] bytes) { this.bytes = bytes; } public string getVideo_url() { return video_url; } public void setVideo_url(string video_url) { this.video_url = video_url; } }
D
module jobs.executor;
D
/Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Heady.build/Debug-iphonesimulator/Heady.build/Objects-normal/x86_64/Heady+CoreDataModel.o : /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Wireframe/CategoryListWireFrame.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Common/CoreDataStore.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/AppDelegate.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Heady.build/Debug-iphonesimulator/Heady.build/DerivedSources/CoreDataGenerated/Heady/Heady+CoreDataModel.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Common/Util.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/View/CategoryTableViewCell.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Protocols/CategoryListProtocol.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Remote/CategoryListRemoteDataManager.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Local/CategoriesLocalDataManager.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/ViewController.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Presenter/CategoryListPresenter.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Common/PersistanceError.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Interactor/CategoryListInteractor.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Heady.build/Debug-iphonesimulator/Heady.build/DerivedSources/CoreDataGenerated/Heady/ProductCategory+CoreDataProperties.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Heady.build/Debug-iphonesimulator/Heady.build/DerivedSources/CoreDataGenerated/Heady/ProductCategory+CoreDataClass.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Common/Constants.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Entities/Product.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Entities/Variant.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/View/CategoryListView.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Entities/ProductCategory.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Debug-iphonesimulator/PKHUD/PKHUD.framework/Modules/PKHUD.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/CoreData.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/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Debug-iphonesimulator/PKHUD/PKHUD.framework/Headers/PKHUD.h /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Debug-iphonesimulator/PKHUD/PKHUD.framework/Headers/PKHUD-umbrella.h /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Debug-iphonesimulator/PKHUD/PKHUD.framework/Headers/PKHUD-Swift.h /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Debug-iphonesimulator/PKHUD/PKHUD.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/CoreData.framework/Headers/CoreData.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/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Heady.build/Debug-iphonesimulator/Heady.build/Objects-normal/x86_64/Heady+CoreDataModel~partial.swiftmodule : /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Wireframe/CategoryListWireFrame.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Common/CoreDataStore.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/AppDelegate.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Heady.build/Debug-iphonesimulator/Heady.build/DerivedSources/CoreDataGenerated/Heady/Heady+CoreDataModel.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Common/Util.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/View/CategoryTableViewCell.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Protocols/CategoryListProtocol.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Remote/CategoryListRemoteDataManager.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Local/CategoriesLocalDataManager.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/ViewController.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Presenter/CategoryListPresenter.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Common/PersistanceError.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Interactor/CategoryListInteractor.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Heady.build/Debug-iphonesimulator/Heady.build/DerivedSources/CoreDataGenerated/Heady/ProductCategory+CoreDataProperties.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Heady.build/Debug-iphonesimulator/Heady.build/DerivedSources/CoreDataGenerated/Heady/ProductCategory+CoreDataClass.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Common/Constants.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Entities/Product.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Entities/Variant.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/View/CategoryListView.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Entities/ProductCategory.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Debug-iphonesimulator/PKHUD/PKHUD.framework/Modules/PKHUD.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/CoreData.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/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Debug-iphonesimulator/PKHUD/PKHUD.framework/Headers/PKHUD.h /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Debug-iphonesimulator/PKHUD/PKHUD.framework/Headers/PKHUD-umbrella.h /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Debug-iphonesimulator/PKHUD/PKHUD.framework/Headers/PKHUD-Swift.h /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Debug-iphonesimulator/PKHUD/PKHUD.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/CoreData.framework/Headers/CoreData.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/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Heady.build/Debug-iphonesimulator/Heady.build/Objects-normal/x86_64/Heady+CoreDataModel~partial.swiftdoc : /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Wireframe/CategoryListWireFrame.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Common/CoreDataStore.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/AppDelegate.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Heady.build/Debug-iphonesimulator/Heady.build/DerivedSources/CoreDataGenerated/Heady/Heady+CoreDataModel.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Common/Util.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/View/CategoryTableViewCell.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Protocols/CategoryListProtocol.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Remote/CategoryListRemoteDataManager.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Local/CategoriesLocalDataManager.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/ViewController.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Presenter/CategoryListPresenter.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Common/PersistanceError.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/Interactor/CategoryListInteractor.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Heady.build/Debug-iphonesimulator/Heady.build/DerivedSources/CoreDataGenerated/Heady/ProductCategory+CoreDataProperties.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Heady.build/Debug-iphonesimulator/Heady.build/DerivedSources/CoreDataGenerated/Heady/ProductCategory+CoreDataClass.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Common/Constants.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Entities/Product.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Entities/Variant.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Categories/View/CategoryListView.swift /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/Heady/Entities/ProductCategory.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Debug-iphonesimulator/PKHUD/PKHUD.framework/Modules/PKHUD.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/CoreData.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/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Debug-iphonesimulator/PKHUD/PKHUD.framework/Headers/PKHUD.h /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Debug-iphonesimulator/PKHUD/PKHUD.framework/Headers/PKHUD-umbrella.h /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Debug-iphonesimulator/PKHUD/PKHUD.framework/Headers/PKHUD-Swift.h /Users/deepapatil/Desktop/Heady_Assignment/iOS/Heady/build/Debug-iphonesimulator/PKHUD/PKHUD.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/CoreData.framework/Headers/CoreData.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
/* TODO: * * - Minimap / info window * - Configurable keys * - File packing / image loading (load all images) * - About * - Window decorations * - I18N * - city earth * - save city on exit * - initial screen, region * - documentation * - save current configurations */ module gui.defaultgui; import std.stdio, std.xml, std.string; import derelict.sdl.sdl; import derelict.sdl.ttf; import derelict.sdl.image; import derelict.util.compat; import gui.gui; import gui.button; import gui.cityview; import gui.dialog; import gui.lateralpanel; import gui.minimap; import util.sdl; import city.city; import city.tile; class DefaultGUI : GUI { const uint FPS = 60; SDL_Surface*[string] images; SDL_Surface* screen; Buttons buttons; TTF_Font* monoBig, monoSmall, titleFont, titleSmall, pico, athens; this(City city) { version(test) initializeSDL(400, 500); else initializeSDL(800, 600); buttons = new Buttons(); super(city); } override void initialize() { Button.initialize(); loadConfig("etc/defaultgui.xml"); dialog = new Dialog(this); lateralPanel = new LateralPanel(desktopH, this, new MiniMap(city)); cityview = new CityView(city, images, lateralPanel.widthOpen); } override void run() { SDL_Event e; while(running) { uint next = SDL_GetTicks() + (1000/FPS); lateralPanel.process(); updateScreen(); while(SDL_PollEvent(&e)) final switch(e.type) { case SDL_QUIT: running = quit(); break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: mouseButton(e.button); break; case SDL_MOUSEMOTION: mouseMotion(e.motion); break; case SDL_KEYDOWN: keyPress(e.key); break; case SDL_VIDEORESIZE: if(!fullscreen) { screen = SDL_SetVideoMode(e.resize.w, e.resize.h, 32, screen.flags); windowW = e.resize.w; windowH = e.resize.h; updateScreen(); } break; } while(SDL_GetTicks() < next) SDL_Delay(1); } } override void displayException(Exception e) { SDL_FillRect(screen, null, 0); SDL_Surface* s = TTF_RenderText_Solid(monoBig, e.msg.toStringz(), whiteColor); SDL_Rect r = { cast(short)((screen.w/2) - (s.w/2)), cast(short)((screen.h/2) - (s.h/2)) }; SDL_BlitSurface(s, null, screen, &r); SDL_Flip(screen); SDL_Event ev; bool done = false; while(!done) { SDL_WaitEvent(&ev); if(ev.type == SDL_KEYDOWN || ev.type == SDL_QUIT) done = true; } throw e; } SDL_Surface* loadImage(string file) { SDL_Surface* image2, image1 = IMG_Load(toStringz("data/art/" ~ file)); if(image1 !is null) { debug writefln("Loading image %s... ok!", file); image2 = SDL_ConvertSurface(image1, screen.format, SDL_SWSURFACE); SDL_FreeSurface(image1); SDL_SetColorKey(image2, SDL_SRCCOLORKEY|SDL_RLEACCEL, image2.format.colorkey); return image2; } else throw new Exception(format("Error loading image %s.", file)); } private { Dialog dialog; const SDL_Color whiteColor = { 255, 255, 255 }; uint white; bool running = true; CityView cityview; short rel_x = 0, rel_y = 0; int last_x, last_y; uint screenFlags; uint desktopW, desktopH; uint windowW, windowH; bool fullscreen = false; LateralPanel lateralPanel; void initializeSDL(uint w, uint h) { // initialize SDL DerelictSDL.load(); if(SDL_Init(SDL_INIT_VIDEO)) throw new Exception("Error initializing SDL."); else debug writefln("SDL initialized."); // initialize SDL_ttf DerelictSDLttf.load(); if(TTF_Init() < 0) throw new Exception("Could not initialize SDL_ttf."); else debug writefln("SDL_ttf initialized."); // load font if((monoBig = TTF_OpenFont("./data/font/04B_03__.TTF", 16)) is null) throw new Exception("Could not load font 04B_03__.TTF."); else debug writefln("Font 04B_03__.TTF loaded."); if((monoSmall = TTF_OpenFont("./data/font/04B_03__.TTF", 8)) is null) throw new Exception("Could not load font 04B_03__.TTF."); else debug writefln("Font 04B_03__.TTF loaded."); if((titleFont = TTF_OpenFont("./data/font/Hardpixel.OTF", 20)) is null) throw new Exception("Could not load font Hardpixel.OTF."); else debug writefln("Font Hardpixel.OTF loaded."); if((titleSmall = TTF_OpenFont("./data/font/Hardpixel.OTF", 10)) is null) throw new Exception("Could not load font Hardpixel.OTF."); else debug writefln("Font Hardpixel.OTF loaded."); if((pico = TTF_OpenFont("./data/font/Pic0.ttf", 16)) is null) throw new Exception("Could not load font pic0.ttf."); else debug writefln("Font pic0.ttf loaded."); if((athens = TTF_OpenFont("./data/font/AthensClassic.ttf", 22)) is null) throw new Exception("Could not load font AthensClassic.ttf."); else debug writefln("Font AthensClassic.ttf loaded."); // get desktop size const SDL_VideoInfo* info = SDL_GetVideoInfo(); desktopW = info.current_w; desktopH = info.current_h; // create window screenFlags = SDL_SWSURFACE|SDL_RESIZABLE; windowW = w; windowH = h; if((screen = SDL_SetVideoMode(w, h, 32, screenFlags)) == null) throw new Exception("Failed to set video mode: " ~ toDString(SDL_GetError())); else debug writefln("Window created."); // initialize SDL_image DerelictSDLImage.load(); if(!IMG_Init(IMG_INIT_PNG)) throw new Exception("Could not initialize SDL_image."); else debug writefln("SDL_image initialized."); // setup colors white = SDL_MapRGB(screen.format, 255, 255, 255); // get pointer position SDL_GetMouseState(&last_x, &last_y); } void loadConfig(string file) { auto s = cast(string)std.file.read(file); check(s); auto xml = new Document(s); assert(xml.tag.name == "gui"); foreach(Element e; xml.elements) if(e.tag.name == "images") { string[string] image_paths; foreach(Element ei; e.elements) { assert(ei.tag.name == "image"); image_paths[ei.tag.attr["id"]] = ei.tag.attr["image"]; } loadImages(image_paths); } foreach(Element e; xml.elements) switch(e.tag.name) { case "images": break; case "buttons": foreach(Element ei; e.elements) { if(ei.tag.name == "button") buttons ~= new Button(ei, this); else if(ei.tag.name == "separator") buttons.addSeparator(); else assert(false); } break; default: assert(false); } buttons.initialize(); } void loadImages(string[string] paths) { foreach(string key, string path; paths) images[key] = loadImage(path); } void updateScreen() { // draw cityview SDL_SetClipRect(screen, &SDL_Rect(0, 0, cast(ushort)(screen.w - lateralPanel.w), cast(ushort)screen.h)); SDL_BlitSurface(cityview, null, screen, &SDL_Rect(rel_x, rel_y)); SDL_SetClipRect(screen, null); // draw lateral panel lateralPanel.draw(screen); // draw buttons uint x = lateralPanel.w; SDL_Rect r2 = { cast(ushort)((screen.w-x)/2 - buttons.sf.w/2), 0 }; SDL_BlitSurface(buttons.sf, null, screen, &r2); // draw options buttons.drawOptions(screen, r2.x); SDL_Flip(screen); } bool quit() { version(test) return 0; else { string os; version(Windows) os = "Windows"; else version(linux) os = "Linux"; else os = "the Operating System"; return !dialog.yesNo("Are you sure you want to quit to " ~ os ~ "?", Dialog.Image.WARNING, true); } } Tile tileClicked(short x, short y) { return null; } void mouseButton(SDL_MouseButtonEvent e) { if(e.button == SDL_BUTTON_LEFT && e.state == SDL_PRESSED) { string command; if(e.x >= cast(short)((screen.w-lateralPanel.w)/2 - buttons.sf.w/2) && e.x <= cast(short)((screen.w-lateralPanel.w)/2 + buttons.sf.w/2) && e.y <= cast(short)buttons.sf.h) buttons.click(cast(short)(e.x - ((screen.w-lateralPanel.w)/2 - buttons.sf.w/2)), e.y); else if((command = buttons.optionClicked(e.x, e.y)) !is null) { buttons.unclickAll(); doCommand(command); } else if(lateralPanel.state == LateralPanel.State.OPEN && e.x >= screen.w - lateralPanel.w && e.x < screen.w - lateralPanel.w + 20 && e.y < 20) lateralPanel.close(); else if(lateralPanel.state == LateralPanel.State.CLOSED && e.x >= screen.w - 15) lateralPanel.open(); else { buttons.unclickAll(); Tile tile = tileClicked(e.x, e.y); if(tile !is null) writefln("%d x %d", tile.x, tile.y); } } } void mouseMotion(SDL_MouseMotionEvent e) { int xrel = e.x - last_x; int yrel = e.y - last_y; last_x = e.x; last_y = e.y; // right button pressed if(e.state & SDL_BUTTON(3)) { if(cityview.w < screen.w) rel_x = 0; else if(rel_x + xrel > 0) rel_x = 0; else if(rel_x + xrel < (screen.w - cityview.w)) rel_x = cast(short)(screen.w - cityview.w); else rel_x += xrel; if(cityview.h < screen.h) rel_y = 0; else if(rel_y + yrel > 0) rel_y = 0; else if(rel_y + yrel < (screen.h - cityview.h)) rel_y = cast(short)(screen.h - cityview.h); else rel_y += yrel; } } void keyPress(SDL_KeyboardEvent e) { final switch(e.keysym.sym) { case SDLK_g: doCommand("grid"); break; } } void doCommand(string command) { switch(command) { case "grid": cityview.displayGrid = !cityview.displayGrid; cityview.redraw(); break; case "fullscreen": if(!fullscreen) { writefln("%d x %d", desktopW, desktopH); screen = SDL_SetVideoMode(desktopW, desktopH, 32, screenFlags ^ SDL_FULLSCREEN); if(screen is null) screen = SDL_SetVideoMode(windowW, windowH, 32, screenFlags); else fullscreen = true; } else { screen = SDL_SetVideoMode(windowW, windowH, 32, screenFlags); fullscreen = false; } assert(screen); updateScreen(); break; case "quit": running = quit(); break; default: assert(false, format("Unknown command '%s'.", command)); } } } }
D
/home/yudjinn/Documents/Projects/rust-learning/guessing_game/target/debug/deps/rand_core-a082a0b66c2e366b.rmeta: /home/yudjinn/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_core-0.3.1/src/lib.rs /home/yudjinn/Documents/Projects/rust-learning/guessing_game/target/debug/deps/librand_core-a082a0b66c2e366b.rlib: /home/yudjinn/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_core-0.3.1/src/lib.rs /home/yudjinn/Documents/Projects/rust-learning/guessing_game/target/debug/deps/rand_core-a082a0b66c2e366b.d: /home/yudjinn/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_core-0.3.1/src/lib.rs /home/yudjinn/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_core-0.3.1/src/lib.rs:
D
module nuklear; public import core.stdc.stdarg, core.stdc.config; extern(C): /* int nk_strmatch_fuzzy_string(char const *str, char const *pattern, int *out_score); */ /* int nk_textedit_paste(struct nk_text_edit*, char const*, int len); */ static immutable NK_VERTEX_LAYOUT_END = nk_draw_vertex_layout_element(NK_VERTEX_ATTRIBUTE_COUNT, NK_FORMAT_COUNT, 0); enum NK_UTF_SIZE = 4; alias byte nk_char; alias ubyte nk_uchar; alias ubyte nk_byte; alias short nk_short; alias ushort nk_ushort; alias int nk_int; alias uint nk_uint; alias size_t nk_size; alias size_t nk_ptr; alias nk_uint nk_hash; alias nk_uint nk_flags; alias nk_uint nk_rune; alias char[4] nk_glyph; alias void* function(nk_handle, void* old, nk_size) nk_plugin_alloc; alias void function(nk_handle, void* old) nk_plugin_free; alias int function(const(nk_text_edit)*, nk_rune unicode) nk_plugin_filter; alias void function(nk_handle, nk_text_edit*) nk_plugin_paste; alias void function(nk_handle, const(char)*, int len) nk_plugin_copy; alias float function(nk_handle, float h, const(char)*, int len) nk_text_width_f; alias void function(nk_handle handle, float font_height, nk_user_font_glyph* glyph, nk_rune codepoint, nk_rune next_codepoint) nk_query_font_glyph_f; alias void function(void* canvas, short x, short y, ushort w, ushort h, nk_handle callback_data) nk_command_custom_callback; alias nk_uint nk_draw_index; alias nk_heading = int; alias nk_button_behavior = int; alias nk_modify = int; alias nk_orientation = int; alias nk_collapse_states = int; alias nk_show_states = int; alias nk_chart_type = int; alias nk_chart_event = int; alias nk_color_format = int; alias nk_popup_type = int; alias nk_layout_format = int; alias nk_tree_type = int; alias nk_symbol_type = int; alias nk_keys = int; alias nk_buttons = int; alias nk_anti_aliasing = int; alias nk_convert_result = int; alias nk_panel_flags = int; alias nk_widget_layout_states = int; alias nk_widget_states = int; alias nk_text_align = int; alias nk_text_alignment = int; alias nk_edit_flags = int; alias nk_edit_types = int; alias nk_edit_events = int; alias nk_style_colors = int; alias nk_style_cursor = int; alias nk_font_coord_type = int; alias nk_font_atlas_format = int; alias nk_allocation_type = int; alias nk_buffer_allocation_type = int; alias nk_text_edit_type = int; alias nk_text_edit_mode = int; alias nk_command_type = int; alias nk_command_clipping = int; alias nk_draw_list_stroke = int; alias nk_draw_vertex_layout_attribute = int; alias nk_draw_vertex_layout_format = int; alias nk_style_item_type = int; alias nk_style_header_align = int; alias nk_panel_type = int; alias nk_panel_set = int; alias nk_panel_row_layout_type = int; alias nk_window_flags = int; struct nk_style_slide; enum { nk_false, nk_true } enum { NK_UP, NK_RIGHT, NK_DOWN, NK_LEFT } enum { NK_BUTTON_DEFAULT, NK_BUTTON_REPEATER } enum { NK_FIXED = nk_false, NK_MODIFIABLE = nk_true } enum { NK_VERTICAL, NK_HORIZONTAL } enum { NK_MINIMIZED = nk_false, NK_MAXIMIZED = nk_true } enum { NK_HIDDEN = nk_false, NK_SHOWN = nk_true } enum { NK_CHART_LINES, NK_CHART_COLUMN, NK_CHART_MAX } enum { NK_CHART_HOVERING = 0x01, NK_CHART_CLICKED = 0x02 } enum { NK_RGB, NK_RGBA } enum { NK_POPUP_STATIC, NK_POPUP_DYNAMIC } enum { NK_DYNAMIC, NK_STATIC } enum { NK_TREE_NODE, NK_TREE_TAB } enum { NK_SYMBOL_NONE, NK_SYMBOL_X, NK_SYMBOL_UNDERSCORE, NK_SYMBOL_CIRCLE_SOLID, NK_SYMBOL_CIRCLE_OUTLINE, NK_SYMBOL_RECT_SOLID, NK_SYMBOL_RECT_OUTLINE, NK_SYMBOL_TRIANGLE_UP, NK_SYMBOL_TRIANGLE_DOWN, NK_SYMBOL_TRIANGLE_LEFT, NK_SYMBOL_TRIANGLE_RIGHT, NK_SYMBOL_PLUS, NK_SYMBOL_MINUS, NK_SYMBOL_MAX } enum { NK_KEY_NONE, NK_KEY_SHIFT, NK_KEY_CTRL, NK_KEY_DEL, NK_KEY_ENTER, NK_KEY_TAB, NK_KEY_BACKSPACE, NK_KEY_COPY, NK_KEY_CUT, NK_KEY_PASTE, NK_KEY_UP, NK_KEY_DOWN, NK_KEY_LEFT, NK_KEY_RIGHT, NK_KEY_TEXT_INSERT_MODE, NK_KEY_TEXT_REPLACE_MODE, NK_KEY_TEXT_RESET_MODE, NK_KEY_TEXT_LINE_START, NK_KEY_TEXT_LINE_END, NK_KEY_TEXT_START, NK_KEY_TEXT_END, NK_KEY_TEXT_UNDO, NK_KEY_TEXT_REDO, NK_KEY_TEXT_SELECT_ALL, NK_KEY_TEXT_WORD_LEFT, NK_KEY_TEXT_WORD_RIGHT, NK_KEY_SCROLL_START, NK_KEY_SCROLL_END, NK_KEY_SCROLL_DOWN, NK_KEY_SCROLL_UP, NK_KEY_MAX } enum { NK_BUTTON_LEFT, NK_BUTTON_MIDDLE, NK_BUTTON_RIGHT, NK_BUTTON_DOUBLE, NK_BUTTON_MAX } enum { NK_ANTI_ALIASING_OFF, NK_ANTI_ALIASING_ON } enum { NK_CONVERT_SUCCESS = 0, NK_CONVERT_INVALID_PARAM = 1, NK_CONVERT_COMMAND_BUFFER_FULL = (1<<(1)), NK_CONVERT_VERTEX_BUFFER_FULL = (1<<(2)), NK_CONVERT_ELEMENT_BUFFER_FULL = (1<<(3)) } enum { NK_WINDOW_BORDER = (1<<(0)), NK_WINDOW_MOVABLE = (1<<(1)), NK_WINDOW_SCALABLE = (1<<(2)), NK_WINDOW_CLOSABLE = (1<<(3)), NK_WINDOW_MINIMIZABLE = (1<<(4)), NK_WINDOW_NO_SCROLLBAR = (1<<(5)), NK_WINDOW_TITLE = (1<<(6)), NK_WINDOW_SCROLL_AUTO_HIDE = (1<<(7)), NK_WINDOW_BACKGROUND = (1<<(8)), NK_WINDOW_SCALE_LEFT = (1<<(9)), NK_WINDOW_NO_INPUT = (1<<(10)) } enum { NK_WIDGET_INVALID, NK_WIDGET_VALID, NK_WIDGET_ROM } enum { NK_WIDGET_STATE_MODIFIED = (1<<(1)), NK_WIDGET_STATE_INACTIVE = (1<<(2)), NK_WIDGET_STATE_ENTERED = (1<<(3)), NK_WIDGET_STATE_HOVER = (1<<(4)), NK_WIDGET_STATE_ACTIVED = (1<<(5)), NK_WIDGET_STATE_LEFT = (1<<(6)), NK_WIDGET_STATE_HOVERED = NK_WIDGET_STATE_HOVER|NK_WIDGET_STATE_MODIFIED, NK_WIDGET_STATE_ACTIVE = NK_WIDGET_STATE_ACTIVED|NK_WIDGET_STATE_MODIFIED } enum { NK_TEXT_ALIGN_LEFT = 0x01, NK_TEXT_ALIGN_CENTERED = 0x02, NK_TEXT_ALIGN_RIGHT = 0x04, NK_TEXT_ALIGN_TOP = 0x08, NK_TEXT_ALIGN_MIDDLE = 0x10, NK_TEXT_ALIGN_BOTTOM = 0x20 } enum { NK_TEXT_LEFT = NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_LEFT, NK_TEXT_CENTERED = NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_CENTERED, NK_TEXT_RIGHT = NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_RIGHT } enum { NK_EDIT_DEFAULT = 0, NK_EDIT_READ_ONLY = (1<<(0)), NK_EDIT_AUTO_SELECT = (1<<(1)), NK_EDIT_SIG_ENTER = (1<<(2)), NK_EDIT_ALLOW_TAB = (1<<(3)), NK_EDIT_NO_CURSOR = (1<<(4)), NK_EDIT_SELECTABLE = (1<<(5)), NK_EDIT_CLIPBOARD = (1<<(6)), NK_EDIT_CTRL_ENTER_NEWLINE = (1<<(7)), NK_EDIT_NO_HORIZONTAL_SCROLL = (1<<(8)), NK_EDIT_ALWAYS_INSERT_MODE = (1<<(9)), NK_EDIT_MULTILINE = (1<<(10)), NK_EDIT_GOTO_END_ON_ACTIVATE = (1<<(11)) } enum { NK_EDIT_SIMPLE = NK_EDIT_ALWAYS_INSERT_MODE, NK_EDIT_FIELD = NK_EDIT_SIMPLE|NK_EDIT_SELECTABLE|NK_EDIT_CLIPBOARD, NK_EDIT_BOX = NK_EDIT_ALWAYS_INSERT_MODE|NK_EDIT_SELECTABLE|NK_EDIT_MULTILINE|NK_EDIT_ALLOW_TAB|NK_EDIT_CLIPBOARD, NK_EDIT_EDITOR = NK_EDIT_SELECTABLE|NK_EDIT_MULTILINE|NK_EDIT_ALLOW_TAB|NK_EDIT_CLIPBOARD } enum { NK_EDIT_ACTIVE = (1<<(0)), NK_EDIT_INACTIVE = (1<<(1)), NK_EDIT_ACTIVATED = (1<<(2)), NK_EDIT_DEACTIVATED = (1<<(3)), NK_EDIT_COMMITED = (1<<(4)) } enum { NK_COLOR_TEXT, NK_COLOR_WINDOW, NK_COLOR_HEADER, NK_COLOR_BORDER, NK_COLOR_BUTTON, NK_COLOR_BUTTON_HOVER, NK_COLOR_BUTTON_ACTIVE, NK_COLOR_TOGGLE, NK_COLOR_TOGGLE_HOVER, NK_COLOR_TOGGLE_CURSOR, NK_COLOR_SELECT, NK_COLOR_SELECT_ACTIVE, NK_COLOR_SLIDER, NK_COLOR_SLIDER_CURSOR, NK_COLOR_SLIDER_CURSOR_HOVER, NK_COLOR_SLIDER_CURSOR_ACTIVE, NK_COLOR_PROPERTY, NK_COLOR_EDIT, NK_COLOR_EDIT_CURSOR, NK_COLOR_COMBO, NK_COLOR_CHART, NK_COLOR_CHART_COLOR, NK_COLOR_CHART_COLOR_HIGHLIGHT, NK_COLOR_SCROLLBAR, NK_COLOR_SCROLLBAR_CURSOR, NK_COLOR_SCROLLBAR_CURSOR_HOVER, NK_COLOR_SCROLLBAR_CURSOR_ACTIVE, NK_COLOR_TAB_HEADER, NK_COLOR_COUNT } enum { NK_CURSOR_ARROW, NK_CURSOR_TEXT, NK_CURSOR_MOVE, NK_CURSOR_RESIZE_VERTICAL, NK_CURSOR_RESIZE_HORIZONTAL, NK_CURSOR_RESIZE_TOP_LEFT_DOWN_RIGHT, NK_CURSOR_RESIZE_TOP_RIGHT_DOWN_LEFT, NK_CURSOR_COUNT } enum { NK_COORD_UV, NK_COORD_PIXEL } enum { NK_FONT_ATLAS_ALPHA8, NK_FONT_ATLAS_RGBA32 } enum { NK_BUFFER_FIXED, NK_BUFFER_DYNAMIC } enum { NK_BUFFER_FRONT, NK_BUFFER_BACK, NK_BUFFER_MAX } enum { NK_TEXT_EDIT_SINGLE_LINE, NK_TEXT_EDIT_MULTI_LINE } enum { NK_TEXT_EDIT_MODE_VIEW, NK_TEXT_EDIT_MODE_INSERT, NK_TEXT_EDIT_MODE_REPLACE } enum { NK_COMMAND_NOP, NK_COMMAND_SCISSOR, NK_COMMAND_LINE, NK_COMMAND_CURVE, NK_COMMAND_RECT, NK_COMMAND_RECT_FILLED, NK_COMMAND_RECT_MULTI_COLOR, NK_COMMAND_CIRCLE, NK_COMMAND_CIRCLE_FILLED, NK_COMMAND_ARC, NK_COMMAND_ARC_FILLED, NK_COMMAND_TRIANGLE, NK_COMMAND_TRIANGLE_FILLED, NK_COMMAND_POLYGON, NK_COMMAND_POLYGON_FILLED, NK_COMMAND_POLYLINE, NK_COMMAND_TEXT, NK_COMMAND_IMAGE, NK_COMMAND_CUSTOM } enum { NK_CLIPPING_OFF = nk_false, NK_CLIPPING_ON = nk_true } enum { NK_STROKE_OPEN = nk_false, NK_STROKE_CLOSED = nk_true } enum { NK_VERTEX_POSITION, NK_VERTEX_COLOR, NK_VERTEX_TEXCOORD, NK_VERTEX_ATTRIBUTE_COUNT } enum { NK_FORMAT_SCHAR, NK_FORMAT_SSHORT, NK_FORMAT_SINT, NK_FORMAT_UCHAR, NK_FORMAT_USHORT, NK_FORMAT_UINT, NK_FORMAT_FLOAT, NK_FORMAT_DOUBLE, NK_FORMAT_COLOR_BEGIN, NK_FORMAT_R8G8B8 = NK_FORMAT_COLOR_BEGIN, NK_FORMAT_R16G15B16, NK_FORMAT_R32G32B32, NK_FORMAT_R8G8B8A8, NK_FORMAT_B8G8R8A8, NK_FORMAT_R16G15B16A16, NK_FORMAT_R32G32B32A32, NK_FORMAT_R32G32B32A32_FLOAT, NK_FORMAT_R32G32B32A32_DOUBLE, NK_FORMAT_RGB32, NK_FORMAT_RGBA32, NK_FORMAT_COLOR_END = NK_FORMAT_RGBA32, NK_FORMAT_COUNT } enum { NK_STYLE_ITEM_COLOR, NK_STYLE_ITEM_IMAGE } enum { NK_HEADER_LEFT, NK_HEADER_RIGHT } enum { NK_PANEL_NONE = 0, NK_PANEL_WINDOW = (1<<(0)), NK_PANEL_GROUP = (1<<(1)), NK_PANEL_POPUP = (1<<(2)), NK_PANEL_CONTEXTUAL = (1<<(4)), NK_PANEL_COMBO = (1<<(5)), NK_PANEL_MENU = (1<<(6)), NK_PANEL_TOOLTIP = (1<<(7)) } enum { NK_PANEL_SET_NONBLOCK = NK_PANEL_CONTEXTUAL|NK_PANEL_COMBO|NK_PANEL_MENU|NK_PANEL_TOOLTIP, NK_PANEL_SET_POPUP = NK_PANEL_SET_NONBLOCK|NK_PANEL_POPUP, NK_PANEL_SET_SUB = NK_PANEL_SET_POPUP|NK_PANEL_GROUP } enum { NK_LAYOUT_DYNAMIC_FIXED = 0, NK_LAYOUT_DYNAMIC_ROW, NK_LAYOUT_DYNAMIC_FREE, NK_LAYOUT_DYNAMIC, NK_LAYOUT_STATIC_FIXED, NK_LAYOUT_STATIC_ROW, NK_LAYOUT_STATIC_FREE, NK_LAYOUT_STATIC, NK_LAYOUT_TEMPLATE, NK_LAYOUT_COUNT } enum { NK_WINDOW_PRIVATE = (1<<(11)), NK_WINDOW_DYNAMIC = NK_WINDOW_PRIVATE, NK_WINDOW_ROM = (1<<(12)), NK_WINDOW_NOT_INTERACTIVE = NK_WINDOW_ROM|NK_WINDOW_NO_INPUT, NK_WINDOW_HIDDEN = (1<<(13)), NK_WINDOW_CLOSED = (1<<(14)), NK_WINDOW_MINIMIZED = (1<<(15)), NK_WINDOW_REMOVE_ROM = (1<<(16)) } union nk_handle { void* ptr; int id; } union nk_style_item_data { nk_image image; nk_color color; } union nk_page_data { nk_table tbl; nk_panel pan; nk_window win; } struct nk_color { nk_byte r; nk_byte g; nk_byte b; nk_byte a; } struct nk_colorf { float r; float g; float b; float a; } struct nk_vec2 { float x; float y; } struct nk_vec2i { short x; short y; } struct nk_rect { float x; float y; float w; float h; } struct nk_recti { short x; short y; short w; short h; } struct nk_image { nk_handle handle; ushort w; ushort h; ushort[4] region; } struct nk_cursor { nk_image img; nk_vec2 size; nk_vec2 offset; } struct nk_scroll { nk_uint x; nk_uint y; } struct nk_allocator { nk_handle userdata; nk_plugin_alloc alloc; nk_plugin_free free; } struct nk_draw_null_texture { nk_handle texture; nk_vec2 uv; } struct nk_convert_config { float global_alpha; nk_anti_aliasing line_AA; nk_anti_aliasing shape_AA; uint circle_segment_count; uint arc_segment_count; uint curve_segment_count; nk_draw_null_texture null_; const(nk_draw_vertex_layout_element)* vertex_layout; nk_size vertex_size; nk_size vertex_alignment; } struct nk_list_view { int begin; int end; int count; int total_height; nk_context* ctx; nk_uint* scroll_pointer; nk_uint scroll_value; } struct nk_user_font_glyph { nk_vec2[2] uv; nk_vec2 offset; float width; float height; float xadvance; } struct nk_user_font { nk_handle userdata; float height; nk_text_width_f width; nk_query_font_glyph_f query; nk_handle texture; } struct nk_baked_font { float height; float ascent; float descent; nk_rune glyph_offset; nk_rune glyph_count; const(nk_rune)* ranges; } struct nk_font_config { nk_font_config* next; void* ttf_blob; nk_size ttf_size; ubyte ttf_data_owned_by_atlas; ubyte merge_mode; ubyte pixel_snap; ubyte oversample_v; ubyte oversample_h; ubyte[3] padding; float size; nk_font_coord_type coord_type; nk_vec2 spacing; const(nk_rune)* range; nk_baked_font* font; nk_rune fallback_glyph; nk_font_config* n; nk_font_config* p; } struct nk_font_glyph { nk_rune codepoint; float xadvance; float x0; float y0; float x1; float y1; float w; float h; float u0; float v0; float u1; float v1; } struct nk_font { nk_font* next; nk_user_font handle; nk_baked_font info; float scale; nk_font_glyph* glyphs; const(nk_font_glyph)* fallback; nk_rune fallback_codepoint; nk_handle texture; nk_font_config* config; } struct nk_font_atlas { void* pixel; int tex_width; int tex_height; nk_allocator permanent; nk_allocator temporary; nk_recti custom; nk_cursor[NK_CURSOR_COUNT] cursors; int glyph_count; nk_font_glyph* glyphs; nk_font* default_font; nk_font* fonts; nk_font_config* config; int font_num; } struct nk_memory_status { void* memory; uint type; nk_size size; nk_size allocated; nk_size needed; nk_size calls; } struct nk_buffer_marker { int active; nk_size offset; } struct nk_memory { void* ptr; nk_size size; } struct nk_buffer { nk_buffer_marker[NK_BUFFER_MAX] marker; nk_allocator pool; nk_allocation_type type; nk_memory memory; float grow_factor; nk_size allocated; nk_size needed; nk_size calls; nk_size size; } struct nk_str { nk_buffer buffer; int len; } struct nk_clipboard { nk_handle userdata; nk_plugin_paste paste; nk_plugin_copy copy; } struct nk_text_undo_record { int where; short insert_length; short delete_length; short char_storage; } struct nk_text_undo_state { nk_text_undo_record[99] undo_rec; nk_rune[999] undo_char; short undo_point; short redo_point; short undo_char_point; short redo_char_point; } struct nk_text_edit { nk_clipboard clip; nk_str string; nk_plugin_filter filter; nk_vec2 scrollbar; int cursor; int select_start; int select_end; ubyte mode; ubyte cursor_at_end_of_line; ubyte initialized; ubyte has_preferred_x; ubyte single_line; ubyte active; ubyte padding1; float preferred_x; nk_text_undo_state undo; } struct nk_command { nk_command_type type; nk_size next; } struct nk_command_scissor { nk_command header; short x; short y; ushort w; ushort h; } struct nk_command_line { nk_command header; ushort line_thickness; nk_vec2i begin; nk_vec2i end; nk_color color; } struct nk_command_curve { nk_command header; ushort line_thickness; nk_vec2i begin; nk_vec2i end; nk_vec2i[2] ctrl; nk_color color; } struct nk_command_rect { nk_command header; ushort rounding; ushort line_thickness; short x; short y; ushort w; ushort h; nk_color color; } struct nk_command_rect_filled { nk_command header; ushort rounding; short x; short y; ushort w; ushort h; nk_color color; } struct nk_command_rect_multi_color { nk_command header; short x; short y; ushort w; ushort h; nk_color left; nk_color top; nk_color bottom; nk_color right; } struct nk_command_triangle { nk_command header; ushort line_thickness; nk_vec2i a; nk_vec2i b; nk_vec2i c; nk_color color; } struct nk_command_triangle_filled { nk_command header; nk_vec2i a; nk_vec2i b; nk_vec2i c; nk_color color; } struct nk_command_circle { nk_command header; short x; short y; ushort line_thickness; ushort w; ushort h; nk_color color; } struct nk_command_circle_filled { nk_command header; short x; short y; ushort w; ushort h; nk_color color; } struct nk_command_arc { nk_command header; short cx; short cy; ushort r; ushort line_thickness; float[2] a; nk_color color; } struct nk_command_arc_filled { nk_command header; short cx; short cy; ushort r; float[2] a; nk_color color; } struct nk_command_polygon { nk_command header; nk_color color; ushort line_thickness; ushort point_count; nk_vec2i[1] points; } struct nk_command_polygon_filled { nk_command header; nk_color color; ushort point_count; nk_vec2i[1] points; } struct nk_command_polyline { nk_command header; nk_color color; ushort line_thickness; ushort point_count; nk_vec2i[1] points; } struct nk_command_image { nk_command header; short x; short y; ushort w; ushort h; nk_image img; nk_color col; } struct nk_command_custom { nk_command header; short x; short y; ushort w; ushort h; nk_handle callback_data; nk_command_custom_callback callback; } struct nk_command_text { nk_command header; const(nk_user_font)* font; nk_color background; nk_color foreground; short x; short y; ushort w; ushort h; float height; int length; char[1] string; } struct nk_command_buffer { nk_buffer* base; nk_rect clip; int use_clipping; nk_handle userdata; nk_size begin; nk_size end; nk_size last; } struct nk_mouse_button { int down; uint clicked; nk_vec2 clicked_pos; } struct nk_mouse { nk_mouse_button[NK_BUTTON_MAX] buttons; nk_vec2 pos; nk_vec2 prev; nk_vec2 delta; nk_vec2 scroll_delta; ubyte grab; ubyte grabbed; ubyte ungrab; } struct nk_key { int down; uint clicked; } struct nk_keyboard { nk_key[NK_KEY_MAX] keys; char[16] text; int text_len; } struct nk_input { nk_keyboard keyboard; nk_mouse mouse; } struct nk_draw_vertex_layout_element { nk_draw_vertex_layout_attribute attribute; nk_draw_vertex_layout_format format; nk_size offset; } struct nk_draw_command { uint elem_count; nk_rect clip_rect; nk_handle texture; } struct nk_draw_list { nk_rect clip_rect; nk_vec2[12] circle_vtx; nk_convert_config config; nk_buffer* buffer; nk_buffer* vertices; nk_buffer* elements; uint element_count; uint vertex_count; uint cmd_count; nk_size cmd_offset; uint path_count; uint path_offset; nk_anti_aliasing line_AA; nk_anti_aliasing shape_AA; } struct nk_style_item { nk_style_item_type type; nk_style_item_data data; } struct nk_style_text { nk_color color; nk_vec2 padding; } struct nk_style_button { nk_style_item normal; nk_style_item hover; nk_style_item active; nk_color border_color; nk_color text_background; nk_color text_normal; nk_color text_hover; nk_color text_active; nk_flags text_alignment; float border; float rounding; nk_vec2 padding; nk_vec2 image_padding; nk_vec2 touch_padding; nk_handle userdata; void function(nk_command_buffer*, nk_handle userdata) draw_begin; void function(nk_command_buffer*, nk_handle userdata) draw_end; } struct nk_style_toggle { nk_style_item normal; nk_style_item hover; nk_style_item active; nk_color border_color; nk_style_item cursor_normal; nk_style_item cursor_hover; nk_color text_normal; nk_color text_hover; nk_color text_active; nk_color text_background; nk_flags text_alignment; nk_vec2 padding; nk_vec2 touch_padding; float spacing; float border; nk_handle userdata; void function(nk_command_buffer*, nk_handle) draw_begin; void function(nk_command_buffer*, nk_handle) draw_end; } struct nk_style_selectable { nk_style_item normal; nk_style_item hover; nk_style_item pressed; nk_style_item normal_active; nk_style_item hover_active; nk_style_item pressed_active; nk_color text_normal; nk_color text_hover; nk_color text_pressed; nk_color text_normal_active; nk_color text_hover_active; nk_color text_pressed_active; nk_color text_background; nk_flags text_alignment; float rounding; nk_vec2 padding; nk_vec2 touch_padding; nk_vec2 image_padding; nk_handle userdata; void function(nk_command_buffer*, nk_handle) draw_begin; void function(nk_command_buffer*, nk_handle) draw_end; } struct nk_style_slider { nk_style_item normal; nk_style_item hover; nk_style_item active; nk_color border_color; nk_color bar_normal; nk_color bar_hover; nk_color bar_active; nk_color bar_filled; nk_style_item cursor_normal; nk_style_item cursor_hover; nk_style_item cursor_active; float border; float rounding; float bar_height; nk_vec2 padding; nk_vec2 spacing; nk_vec2 cursor_size; int show_buttons; nk_style_button inc_button; nk_style_button dec_button; nk_symbol_type inc_symbol; nk_symbol_type dec_symbol; nk_handle userdata; void function(nk_command_buffer*, nk_handle) draw_begin; void function(nk_command_buffer*, nk_handle) draw_end; } struct nk_style_progress { nk_style_item normal; nk_style_item hover; nk_style_item active; nk_color border_color; nk_style_item cursor_normal; nk_style_item cursor_hover; nk_style_item cursor_active; nk_color cursor_border_color; float rounding; float border; float cursor_border; float cursor_rounding; nk_vec2 padding; nk_handle userdata; void function(nk_command_buffer*, nk_handle) draw_begin; void function(nk_command_buffer*, nk_handle) draw_end; } struct nk_style_scrollbar { nk_style_item normal; nk_style_item hover; nk_style_item active; nk_color border_color; nk_style_item cursor_normal; nk_style_item cursor_hover; nk_style_item cursor_active; nk_color cursor_border_color; float border; float rounding; float border_cursor; float rounding_cursor; nk_vec2 padding; int show_buttons; nk_style_button inc_button; nk_style_button dec_button; nk_symbol_type inc_symbol; nk_symbol_type dec_symbol; nk_handle userdata; void function(nk_command_buffer*, nk_handle) draw_begin; void function(nk_command_buffer*, nk_handle) draw_end; } struct nk_style_edit { nk_style_item normal; nk_style_item hover; nk_style_item active; nk_color border_color; nk_style_scrollbar scrollbar; nk_color cursor_normal; nk_color cursor_hover; nk_color cursor_text_normal; nk_color cursor_text_hover; nk_color text_normal; nk_color text_hover; nk_color text_active; nk_color selected_normal; nk_color selected_hover; nk_color selected_text_normal; nk_color selected_text_hover; float border; float rounding; float cursor_size; nk_vec2 scrollbar_size; nk_vec2 padding; float row_padding; } struct nk_style_property { nk_style_item normal; nk_style_item hover; nk_style_item active; nk_color border_color; nk_color label_normal; nk_color label_hover; nk_color label_active; nk_symbol_type sym_left; nk_symbol_type sym_right; float border; float rounding; nk_vec2 padding; nk_style_edit edit; nk_style_button inc_button; nk_style_button dec_button; nk_handle userdata; void function(nk_command_buffer*, nk_handle) draw_begin; void function(nk_command_buffer*, nk_handle) draw_end; } struct nk_style_chart { nk_style_item background; nk_color border_color; nk_color selected_color; nk_color color; float border; float rounding; nk_vec2 padding; } struct nk_style_combo { nk_style_item normal; nk_style_item hover; nk_style_item active; nk_color border_color; nk_color label_normal; nk_color label_hover; nk_color label_active; nk_color symbol_normal; nk_color symbol_hover; nk_color symbol_active; nk_style_button button; nk_symbol_type sym_normal; nk_symbol_type sym_hover; nk_symbol_type sym_active; float border; float rounding; nk_vec2 content_padding; nk_vec2 button_padding; nk_vec2 spacing; } struct nk_style_tab { nk_style_item background; nk_color border_color; nk_color text; nk_style_button tab_maximize_button; nk_style_button tab_minimize_button; nk_style_button node_maximize_button; nk_style_button node_minimize_button; nk_symbol_type sym_minimize; nk_symbol_type sym_maximize; float border; float rounding; float indent; nk_vec2 padding; nk_vec2 spacing; } struct nk_style_window_header { nk_style_item normal; nk_style_item hover; nk_style_item active; nk_style_button close_button; nk_style_button minimize_button; nk_symbol_type close_symbol; nk_symbol_type minimize_symbol; nk_symbol_type maximize_symbol; nk_color label_normal; nk_color label_hover; nk_color label_active; nk_style_header_align align_; nk_vec2 padding; nk_vec2 label_padding; nk_vec2 spacing; } struct nk_style_window { nk_style_window_header header; nk_style_item fixed_background; nk_color background; nk_color border_color; nk_color popup_border_color; nk_color combo_border_color; nk_color contextual_border_color; nk_color menu_border_color; nk_color group_border_color; nk_color tooltip_border_color; nk_style_item scaler; float border; float combo_border; float contextual_border; float menu_border; float group_border; float tooltip_border; float popup_border; float min_row_height_padding; float rounding; nk_vec2 spacing; nk_vec2 scrollbar_size; nk_vec2 min_size; nk_vec2 padding; nk_vec2 group_padding; nk_vec2 popup_padding; nk_vec2 combo_padding; nk_vec2 contextual_padding; nk_vec2 menu_padding; nk_vec2 tooltip_padding; } struct nk_style { const(nk_user_font)* font; const(nk_cursor)*[NK_CURSOR_COUNT] cursors; const(nk_cursor)* cursor_active; nk_cursor* cursor_last; int cursor_visible; nk_style_text text; nk_style_button button; nk_style_button contextual_button; nk_style_button menu_button; nk_style_toggle option; nk_style_toggle checkbox; nk_style_selectable selectable; nk_style_slider slider; nk_style_progress progress; nk_style_property property; nk_style_edit edit; nk_style_chart chart; nk_style_scrollbar scrollh; nk_style_scrollbar scrollv; nk_style_tab tab; nk_style_combo combo; nk_style_window window; } struct nk_chart_slot { nk_chart_type type; nk_color color; nk_color highlight; float min; float max; float range; int count; nk_vec2 last; int index; } struct nk_chart { int slot; float x; float y; float w; float h; nk_chart_slot[4] slots; } struct nk_row_layout { nk_panel_row_layout_type type; int index; float height; float min_height; int columns; const(float)* ratio; float item_width; float item_height; float item_offset; float filled; nk_rect item; int tree_depth; float[16] templates; } struct nk_popup_buffer { nk_size begin; nk_size parent; nk_size last; nk_size end; int active; } struct nk_menu_state { float x; float y; float w; float h; nk_scroll offset; } struct nk_panel { nk_panel_type type; nk_flags flags; nk_rect bounds; nk_uint* offset_x; nk_uint* offset_y; float at_x; float at_y; float max_x; float footer_height; float header_height; float border; uint has_scrolling; nk_rect clip; nk_menu_state menu; nk_row_layout row; nk_chart chart; nk_command_buffer* buffer; nk_panel* parent; } struct nk_popup_state { nk_window* win; nk_panel_type type; nk_popup_buffer buf; nk_hash name; int active; uint combo_count; uint con_count; uint con_old; uint active_con; nk_rect header; } struct nk_edit_state { nk_hash name; uint seq; uint old; int active; int prev; int cursor; int sel_start; int sel_end; nk_scroll scrollbar; ubyte mode; ubyte single_line; } struct nk_property_state { int active; int prev; char[64] buffer; int length; int cursor; int select_start; int select_end; nk_hash name; uint seq; uint old; int state; } struct nk_window { uint seq; nk_hash name; char[64] name_string; nk_flags flags; nk_rect bounds; nk_scroll scrollbar; nk_command_buffer buffer; nk_panel* layout; float scrollbar_hiding_timer; nk_property_state property; nk_popup_state popup; nk_edit_state edit; uint scrolled; nk_table* tables; uint table_count; nk_window* next; nk_window* prev; nk_window* parent; } struct nk_config_stack_style_item_element { nk_style_item* address; nk_style_item old_value; } struct nk_config_stack_float_element { float* address; float old_value; } struct nk_config_stack_vec2_element { nk_vec2* address; nk_vec2 old_value; } struct nk_config_stack_flags_element { nk_flags* address; nk_flags old_value; } struct nk_config_stack_color_element { nk_color* address; nk_color old_value; } struct nk_config_stack_user_font_element { const(nk_user_font)** address; const(nk_user_font)* old_value; } struct nk_config_stack_button_behavior_element { nk_button_behavior* address; nk_button_behavior old_value; } struct nk_config_stack_style_item { int head; nk_config_stack_style_item_element[16] elements; } struct nk_config_stack_float { int head; nk_config_stack_float_element[32] elements; } struct nk_config_stack_vec2 { int head; nk_config_stack_vec2_element[16] elements; } struct nk_config_stack_flags { int head; nk_config_stack_flags_element[32] elements; } struct nk_config_stack_color { int head; nk_config_stack_color_element[32] elements; } struct nk_config_stack_user_font { int head; nk_config_stack_user_font_element[8] elements; } struct nk_config_stack_button_behavior { int head; nk_config_stack_button_behavior_element[8] elements; } struct nk_configuration_stacks { nk_config_stack_style_item style_items; nk_config_stack_float floats; nk_config_stack_vec2 vectors; nk_config_stack_flags flags; nk_config_stack_color colors; nk_config_stack_user_font fonts; nk_config_stack_button_behavior button_behaviors; } import std; enum NK_VALUE_PAGE_CAPACITY = (max(nk_window.sizeof, nk_panel.sizeof) / nk_uint.sizeof) / 2; struct nk_table { uint seq; uint size; nk_hash[NK_VALUE_PAGE_CAPACITY] keys; nk_uint[NK_VALUE_PAGE_CAPACITY] values; nk_table* next; nk_table* prev; } struct nk_page_element { nk_page_data data; nk_page_element* next; nk_page_element* prev; } struct nk_page { uint size; nk_page* next; nk_page_element[1] win; } struct nk_pool { nk_allocator alloc; nk_allocation_type type; uint page_count; nk_page* pages; nk_page_element* freelist; uint capacity; nk_size size; nk_size cap; } struct nk_context { nk_input input; nk_style style; nk_buffer memory; nk_clipboard clip; nk_flags last_widget_state; nk_button_behavior button_behavior; nk_configuration_stacks stacks; float delta_time_seconds; nk_draw_list draw_list; nk_text_edit text_edit; nk_command_buffer overlay; int build; int use_pool; nk_pool pool; nk_window* begin; nk_window* end; nk_window* active; nk_window* current; nk_page_element* freelist; uint count; uint seq; } int nk_init_default(nk_context*, const(nk_user_font)*); int nk_init_fixed(nk_context*, void* memory, nk_size size, const(nk_user_font)*); int nk_init(nk_context*, nk_allocator*, const(nk_user_font)*); int nk_init_custom(nk_context*, nk_buffer* cmds, nk_buffer* pool, const(nk_user_font)*); void nk_clear(nk_context*); void nk_free(nk_context*); void nk_input_begin(nk_context*); void nk_input_motion(nk_context*, int x, int y); void nk_input_key(nk_context*, nk_keys, int down); void nk_input_button(nk_context*, nk_buttons, int x, int y, int down); void nk_input_scroll(nk_context*, nk_vec2 val); void nk_input_char(nk_context*, char); void nk_input_glyph(nk_context*, const(char)*); void nk_input_unicode(nk_context*, nk_rune); void nk_input_end(nk_context*); const(nk_command)* nk__begin(nk_context*); const(nk_command)* nk__next(nk_context*, const(nk_command)*); nk_flags nk_convert(nk_context*, nk_buffer* cmds, nk_buffer* vertices, nk_buffer* elements, const(nk_convert_config)*); const(nk_draw_command)* nk__draw_begin(const(nk_context)*, const(nk_buffer)*); const(nk_draw_command)* nk__draw_end(const(nk_context)*, const(nk_buffer)*); const(nk_draw_command)* nk__draw_next(const(nk_draw_command)*, const(nk_buffer)*, const(nk_context)*); int nk_begin(nk_context* ctx, const(char)* title, nk_rect bounds, nk_flags flags); int nk_begin_titled(nk_context* ctx, const(char)* name, const(char)* title, nk_rect bounds, nk_flags flags); void nk_end(nk_context* ctx); nk_window* nk_window_find(nk_context* ctx, const(char)* name); nk_rect nk_window_get_bounds(const(nk_context)* ctx); nk_vec2 nk_window_get_position(const(nk_context)* ctx); nk_vec2 nk_window_get_size(const(nk_context)*); float nk_window_get_width(const(nk_context)*); float nk_window_get_height(const(nk_context)*); nk_panel* nk_window_get_panel(nk_context*); nk_rect nk_window_get_content_region(nk_context*); nk_vec2 nk_window_get_content_region_min(nk_context*); nk_vec2 nk_window_get_content_region_max(nk_context*); nk_vec2 nk_window_get_content_region_size(nk_context*); nk_command_buffer* nk_window_get_canvas(nk_context*); void nk_window_get_scroll(nk_context*, nk_uint* offset_x, nk_uint* offset_y); int nk_window_has_focus(const(nk_context)*); int nk_window_is_hovered(nk_context*); int nk_window_is_collapsed(nk_context* ctx, const(char)* name); int nk_window_is_closed(nk_context*, const(char)*); int nk_window_is_hidden(nk_context*, const(char)*); int nk_window_is_active(nk_context*, const(char)*); int nk_window_is_any_hovered(nk_context*); int nk_item_is_any_active(nk_context*); void nk_window_set_bounds(nk_context*, const(char)* name, nk_rect bounds); void nk_window_set_position(nk_context*, const(char)* name, nk_vec2 pos); void nk_window_set_size(nk_context*, const(char)* name, nk_vec2); void nk_window_set_focus(nk_context*, const(char)* name); void nk_window_set_scroll(nk_context*, nk_uint offset_x, nk_uint offset_y); void nk_window_close(nk_context* ctx, const(char)* name); void nk_window_collapse(nk_context*, const(char)* name, nk_collapse_states state); void nk_window_collapse_if(nk_context*, const(char)* name, nk_collapse_states, int cond); void nk_window_show(nk_context*, const(char)* name, nk_show_states); void nk_window_show_if(nk_context*, const(char)* name, nk_show_states, int cond); void nk_layout_set_min_row_height(nk_context*, float height); void nk_layout_reset_min_row_height(nk_context*); nk_rect nk_layout_widget_bounds(nk_context*); float nk_layout_ratio_from_pixel(nk_context*, float pixel_width); void nk_layout_row_dynamic(nk_context* ctx, float height, int cols); void nk_layout_row_static(nk_context* ctx, float height, int item_width, int cols); void nk_layout_row_begin(nk_context* ctx, nk_layout_format fmt, float row_height, int cols); void nk_layout_row_push(nk_context*, float value); void nk_layout_row_end(nk_context*); void nk_layout_row(nk_context*, nk_layout_format, float height, int cols, const(float)* ratio); void nk_layout_row_template_begin(nk_context*, float row_height); void nk_layout_row_template_push_dynamic(nk_context*); void nk_layout_row_template_push_variable(nk_context*, float min_width); void nk_layout_row_template_push_static(nk_context*, float width); void nk_layout_row_template_end(nk_context*); void nk_layout_space_begin(nk_context*, nk_layout_format, float height, int widget_count); void nk_layout_space_push(nk_context*, nk_rect bounds); void nk_layout_space_end(nk_context*); nk_rect nk_layout_space_bounds(nk_context*); nk_vec2 nk_layout_space_to_screen(nk_context*, nk_vec2); nk_vec2 nk_layout_space_to_local(nk_context*, nk_vec2); nk_rect nk_layout_space_rect_to_screen(nk_context*, nk_rect); nk_rect nk_layout_space_rect_to_local(nk_context*, nk_rect); int nk_group_begin(nk_context*, const(char)* title, nk_flags); int nk_group_begin_titled(nk_context*, const(char)* name, const(char)* title, nk_flags); void nk_group_end(nk_context*); int nk_group_scrolled_offset_begin(nk_context*, nk_uint* x_offset, nk_uint* y_offset, const(char)* title, nk_flags flags); int nk_group_scrolled_begin(nk_context*, nk_scroll* off, const(char)* title, nk_flags); void nk_group_scrolled_end(nk_context*); void nk_group_get_scroll(nk_context*, const(char)* id, nk_uint* x_offset, nk_uint* y_offset); void nk_group_set_scroll(nk_context*, const(char)* id, nk_uint x_offset, nk_uint y_offset); int nk_tree_push_hashed(nk_context*, nk_tree_type, const(char)* title, nk_collapse_states initial_state, const(char)* hash, int len, int seed); int nk_tree_image_push_hashed(nk_context*, nk_tree_type, nk_image, const(char)* title, nk_collapse_states initial_state, const(char)* hash, int len, int seed); void nk_tree_pop(nk_context*); int nk_tree_state_push(nk_context*, nk_tree_type, const(char)* title, nk_collapse_states* state); int nk_tree_state_image_push(nk_context*, nk_tree_type, nk_image, const(char)* title, nk_collapse_states* state); void nk_tree_state_pop(nk_context*); int nk_tree_element_push_hashed(nk_context*, nk_tree_type, const(char)* title, nk_collapse_states initial_state, int* selected, const(char)* hash, int len, int seed); int nk_tree_element_image_push_hashed(nk_context*, nk_tree_type, nk_image, const(char)* title, nk_collapse_states initial_state, int* selected, const(char)* hash, int len, int seed); void nk_tree_element_pop(nk_context*); int nk_list_view_begin(nk_context*, nk_list_view* out_, const(char)* id, nk_flags, int row_height, int row_count); void nk_list_view_end(nk_list_view*); nk_widget_layout_states nk_widget(nk_rect*, const(nk_context)*); nk_widget_layout_states nk_widget_fitting(nk_rect*, nk_context*, nk_vec2); nk_rect nk_widget_bounds(nk_context*); nk_vec2 nk_widget_position(nk_context*); nk_vec2 nk_widget_size(nk_context*); float nk_widget_width(nk_context*); float nk_widget_height(nk_context*); int nk_widget_is_hovered(nk_context*); int nk_widget_is_mouse_clicked(nk_context*, nk_buttons); int nk_widget_has_mouse_click_down(nk_context*, nk_buttons, int down); void nk_spacing(nk_context*, int cols); void nk_text(nk_context*, const(char)*, int, nk_flags); void nk_text_colored(nk_context*, const(char)*, int, nk_flags, nk_color); void nk_text_wrap(nk_context*, const(char)*, int); void nk_text_wrap_colored(nk_context*, const(char)*, int, nk_color); void nk_label(nk_context*, const(char)*, nk_flags align_); void nk_label_colored(nk_context*, const(char)*, nk_flags align_, nk_color); void nk_label_wrap(nk_context*, const(char)*); void nk_label_colored_wrap(nk_context*, const(char)*, nk_color); pragma(mangle, `nk_image`) void nk_image_(nk_context*, nk_image); void nk_image_color(nk_context*, nk_image, nk_color); void nk_labelf(nk_context*, nk_flags, const(char)*, ...); void nk_labelf_colored(nk_context*, nk_flags, nk_color, const(char)*, ...); void nk_labelf_wrap(nk_context*, const(char)*, ...); void nk_labelf_colored_wrap(nk_context*, nk_color, const(char)*, ...); void nk_labelfv(nk_context*, nk_flags, const(char)*, va_list); void nk_labelfv_colored(nk_context*, nk_flags, nk_color, const(char)*, va_list); void nk_labelfv_wrap(nk_context*, const(char)*, va_list); void nk_labelfv_colored_wrap(nk_context*, nk_color, const(char)*, va_list); void nk_value_bool(nk_context*, const(char)* prefix, int); void nk_value_int(nk_context*, const(char)* prefix, int); void nk_value_uint(nk_context*, const(char)* prefix, uint); void nk_value_float(nk_context*, const(char)* prefix, float); void nk_value_color_byte(nk_context*, const(char)* prefix, nk_color); void nk_value_color_float(nk_context*, const(char)* prefix, nk_color); void nk_value_color_hex(nk_context*, const(char)* prefix, nk_color); int nk_button_text(nk_context*, const(char)* title, int len); int nk_button_label(nk_context*, const(char)* title); int nk_button_color(nk_context*, nk_color); int nk_button_symbol(nk_context*, nk_symbol_type); int nk_button_image(nk_context*, nk_image img); int nk_button_symbol_label(nk_context*, nk_symbol_type, const(char)*, nk_flags text_alignment); int nk_button_symbol_text(nk_context*, nk_symbol_type, const(char)*, int, nk_flags alignment); int nk_button_image_label(nk_context*, nk_image img, const(char)*, nk_flags text_alignment); int nk_button_image_text(nk_context*, nk_image img, const(char)*, int, nk_flags alignment); int nk_button_text_styled(nk_context*, const(nk_style_button)*, const(char)* title, int len); int nk_button_label_styled(nk_context*, const(nk_style_button)*, const(char)* title); int nk_button_symbol_styled(nk_context*, const(nk_style_button)*, nk_symbol_type); int nk_button_image_styled(nk_context*, const(nk_style_button)*, nk_image img); int nk_button_symbol_text_styled(nk_context*, const(nk_style_button)*, nk_symbol_type, const(char)*, int, nk_flags alignment); int nk_button_symbol_label_styled(nk_context* ctx, const(nk_style_button)* style, nk_symbol_type symbol, const(char)* title, nk_flags align_); int nk_button_image_label_styled(nk_context*, const(nk_style_button)*, nk_image img, const(char)*, nk_flags text_alignment); int nk_button_image_text_styled(nk_context*, const(nk_style_button)*, nk_image img, const(char)*, int, nk_flags alignment); void nk_button_set_behavior(nk_context*, nk_button_behavior); int nk_button_push_behavior(nk_context*, nk_button_behavior); int nk_button_pop_behavior(nk_context*); int nk_check_label(nk_context*, const(char)*, int active); int nk_check_text(nk_context*, const(char)*, int, int active); uint nk_check_flags_label(nk_context*, const(char)*, uint flags, uint value); uint nk_check_flags_text(nk_context*, const(char)*, int, uint flags, uint value); int nk_checkbox_label(nk_context*, const(char)*, int* active); int nk_checkbox_text(nk_context*, const(char)*, int, int* active); int nk_checkbox_flags_label(nk_context*, const(char)*, uint* flags, uint value); int nk_checkbox_flags_text(nk_context*, const(char)*, int, uint* flags, uint value); int nk_radio_label(nk_context*, const(char)*, int* active); int nk_radio_text(nk_context*, const(char)*, int, int* active); int nk_option_label(nk_context*, const(char)*, int active); int nk_option_text(nk_context*, const(char)*, int, int active); int nk_selectable_label(nk_context*, const(char)*, nk_flags align_, int* value); int nk_selectable_text(nk_context*, const(char)*, int, nk_flags align_, int* value); int nk_selectable_image_label(nk_context*, nk_image, const(char)*, nk_flags align_, int* value); int nk_selectable_image_text(nk_context*, nk_image, const(char)*, int, nk_flags align_, int* value); int nk_selectable_symbol_label(nk_context*, nk_symbol_type, const(char)*, nk_flags align_, int* value); int nk_selectable_symbol_text(nk_context*, nk_symbol_type, const(char)*, int, nk_flags align_, int* value); int nk_select_label(nk_context*, const(char)*, nk_flags align_, int value); int nk_select_text(nk_context*, const(char)*, int, nk_flags align_, int value); int nk_select_image_label(nk_context*, nk_image, const(char)*, nk_flags align_, int value); int nk_select_image_text(nk_context*, nk_image, const(char)*, int, nk_flags align_, int value); int nk_select_symbol_label(nk_context*, nk_symbol_type, const(char)*, nk_flags align_, int value); int nk_select_symbol_text(nk_context*, nk_symbol_type, const(char)*, int, nk_flags align_, int value); float nk_slide_float(nk_context*, float min, float val, float max, float step); int nk_slide_int(nk_context*, int min, int val, int max, int step); int nk_slider_float(nk_context*, float min, float* val, float max, float step); int nk_slider_int(nk_context*, int min, int* val, int max, int step); int nk_progress(nk_context*, nk_size* cur, nk_size max, int modifyable); nk_size nk_prog(nk_context*, nk_size cur, nk_size max, int modifyable); nk_colorf nk_color_picker(nk_context*, nk_colorf, nk_color_format); int nk_color_pick(nk_context*, nk_colorf*, nk_color_format); void nk_property_int(nk_context*, const(char)* name, int min, int* val, int max, int step, float inc_per_pixel); void nk_property_float(nk_context*, const(char)* name, float min, float* val, float max, float step, float inc_per_pixel); void nk_property_double(nk_context*, const(char)* name, double min, double* val, double max, double step, float inc_per_pixel); int nk_propertyi(nk_context*, const(char)* name, int min, int val, int max, int step, float inc_per_pixel); float nk_propertyf(nk_context*, const(char)* name, float min, float val, float max, float step, float inc_per_pixel); double nk_propertyd(nk_context*, const(char)* name, double min, double val, double max, double step, float inc_per_pixel); nk_flags nk_edit_string(nk_context*, nk_flags, char* buffer, int* len, int max, nk_plugin_filter); nk_flags nk_edit_string_zero_terminated(nk_context*, nk_flags, char* buffer, int max, nk_plugin_filter); nk_flags nk_edit_buffer(nk_context*, nk_flags, nk_text_edit*, nk_plugin_filter); void nk_edit_focus(nk_context*, nk_flags flags); void nk_edit_unfocus(nk_context*); int nk_chart_begin(nk_context*, nk_chart_type, int num, float min, float max); int nk_chart_begin_colored(nk_context*, nk_chart_type, nk_color, nk_color active, int num, float min, float max); void nk_chart_add_slot(nk_context* ctx, const(nk_chart_type), int count, float min_value, float max_value); void nk_chart_add_slot_colored(nk_context* ctx, const(nk_chart_type), nk_color, nk_color active, int count, float min_value, float max_value); nk_flags nk_chart_push(nk_context*, float); nk_flags nk_chart_push_slot(nk_context*, float, int); void nk_chart_end(nk_context*); void nk_plot(nk_context*, nk_chart_type, const(float)* values, int count, int offset); void nk_plot_function(nk_context*, nk_chart_type, void* userdata, float function(void* user, int index) value_getter, int count, int offset); int nk_popup_begin(nk_context*, nk_popup_type, const(char)*, nk_flags, nk_rect bounds); void nk_popup_close(nk_context*); void nk_popup_end(nk_context*); void nk_popup_get_scroll(nk_context*, nk_uint* offset_x, nk_uint* offset_y); void nk_popup_set_scroll(nk_context*, nk_uint offset_x, nk_uint offset_y); int nk_combo(nk_context*, const(char)** items, int count, int selected, int item_height, nk_vec2 size); int nk_combo_separator(nk_context*, const(char)* items_separated_by_separator, int separator, int selected, int count, int item_height, nk_vec2 size); int nk_combo_string(nk_context*, const(char)* items_separated_by_zeros, int selected, int count, int item_height, nk_vec2 size); int nk_combo_callback(nk_context*, void function(void*, int, const(char)**) item_getter, void* userdata, int selected, int count, int item_height, nk_vec2 size); void nk_combobox(nk_context*, const(char)** items, int count, int* selected, int item_height, nk_vec2 size); void nk_combobox_string(nk_context*, const(char)* items_separated_by_zeros, int* selected, int count, int item_height, nk_vec2 size); void nk_combobox_separator(nk_context*, const(char)* items_separated_by_separator, int separator, int* selected, int count, int item_height, nk_vec2 size); void nk_combobox_callback(nk_context*, void function(void*, int, const(char)**) item_getter, void*, int* selected, int count, int item_height, nk_vec2 size); int nk_combo_begin_text(nk_context*, const(char)* selected, int, nk_vec2 size); int nk_combo_begin_label(nk_context*, const(char)* selected, nk_vec2 size); int nk_combo_begin_color(nk_context*, nk_color color, nk_vec2 size); int nk_combo_begin_symbol(nk_context*, nk_symbol_type, nk_vec2 size); int nk_combo_begin_symbol_label(nk_context*, const(char)* selected, nk_symbol_type, nk_vec2 size); int nk_combo_begin_symbol_text(nk_context*, const(char)* selected, int, nk_symbol_type, nk_vec2 size); int nk_combo_begin_image(nk_context*, nk_image img, nk_vec2 size); int nk_combo_begin_image_label(nk_context*, const(char)* selected, nk_image, nk_vec2 size); int nk_combo_begin_image_text(nk_context*, const(char)* selected, int, nk_image, nk_vec2 size); int nk_combo_item_label(nk_context*, const(char)*, nk_flags alignment); int nk_combo_item_text(nk_context*, const(char)*, int, nk_flags alignment); int nk_combo_item_image_label(nk_context*, nk_image, const(char)*, nk_flags alignment); int nk_combo_item_image_text(nk_context*, nk_image, const(char)*, int, nk_flags alignment); int nk_combo_item_symbol_label(nk_context*, nk_symbol_type, const(char)*, nk_flags alignment); int nk_combo_item_symbol_text(nk_context*, nk_symbol_type, const(char)*, int, nk_flags alignment); void nk_combo_close(nk_context*); void nk_combo_end(nk_context*); int nk_contextual_begin(nk_context*, nk_flags, nk_vec2, nk_rect trigger_bounds); int nk_contextual_item_text(nk_context*, const(char)*, int, nk_flags align_); int nk_contextual_item_label(nk_context*, const(char)*, nk_flags align_); int nk_contextual_item_image_label(nk_context*, nk_image, const(char)*, nk_flags alignment); int nk_contextual_item_image_text(nk_context*, nk_image, const(char)*, int len, nk_flags alignment); int nk_contextual_item_symbol_label(nk_context*, nk_symbol_type, const(char)*, nk_flags alignment); int nk_contextual_item_symbol_text(nk_context*, nk_symbol_type, const(char)*, int, nk_flags alignment); void nk_contextual_close(nk_context*); void nk_contextual_end(nk_context*); void nk_tooltip(nk_context*, const(char)*); void nk_tooltipf(nk_context*, const(char)*, ...); void nk_tooltipfv(nk_context*, const(char)*, va_list); int nk_tooltip_begin(nk_context*, float width); void nk_tooltip_end(nk_context*); void nk_menubar_begin(nk_context*); void nk_menubar_end(nk_context*); int nk_menu_begin_text(nk_context*, const(char)* title, int title_len, nk_flags align_, nk_vec2 size); int nk_menu_begin_label(nk_context*, const(char)*, nk_flags align_, nk_vec2 size); int nk_menu_begin_image(nk_context*, const(char)*, nk_image, nk_vec2 size); int nk_menu_begin_image_text(nk_context*, const(char)*, int, nk_flags align_, nk_image, nk_vec2 size); int nk_menu_begin_image_label(nk_context*, const(char)*, nk_flags align_, nk_image, nk_vec2 size); int nk_menu_begin_symbol(nk_context*, const(char)*, nk_symbol_type, nk_vec2 size); int nk_menu_begin_symbol_text(nk_context*, const(char)*, int, nk_flags align_, nk_symbol_type, nk_vec2 size); int nk_menu_begin_symbol_label(nk_context*, const(char)*, nk_flags align_, nk_symbol_type, nk_vec2 size); int nk_menu_item_text(nk_context*, const(char)*, int, nk_flags align_); int nk_menu_item_label(nk_context*, const(char)*, nk_flags alignment); int nk_menu_item_image_label(nk_context*, nk_image, const(char)*, nk_flags alignment); int nk_menu_item_image_text(nk_context*, nk_image, const(char)*, int len, nk_flags alignment); int nk_menu_item_symbol_text(nk_context*, nk_symbol_type, const(char)*, int, nk_flags alignment); int nk_menu_item_symbol_label(nk_context*, nk_symbol_type, const(char)*, nk_flags alignment); void nk_menu_close(nk_context*); void nk_menu_end(nk_context*); void nk_style_default(nk_context*); void nk_style_from_table(nk_context*, const(nk_color)*); void nk_style_load_cursor(nk_context*, nk_style_cursor, const(nk_cursor)*); void nk_style_load_all_cursors(nk_context*, nk_cursor*); const(char)* nk_style_get_color_by_name(nk_style_colors); void nk_style_set_font(nk_context*, const(nk_user_font)*); int nk_style_set_cursor(nk_context*, nk_style_cursor); void nk_style_show_cursor(nk_context*); void nk_style_hide_cursor(nk_context*); int nk_style_push_font(nk_context*, const(nk_user_font)*); int nk_style_push_float(nk_context*, float*, float); int nk_style_push_vec2(nk_context*, nk_vec2*, nk_vec2); int nk_style_push_style_item(nk_context*, nk_style_item*, nk_style_item); int nk_style_push_flags(nk_context*, nk_flags*, nk_flags); int nk_style_push_color(nk_context*, nk_color*, nk_color); int nk_style_pop_font(nk_context*); int nk_style_pop_float(nk_context*); int nk_style_pop_vec2(nk_context*); int nk_style_pop_style_item(nk_context*); int nk_style_pop_flags(nk_context*); int nk_style_pop_color(nk_context*); nk_color nk_rgb(int r, int g, int b); nk_color nk_rgb_iv(const(int)* rgb); nk_color nk_rgb_bv(const(nk_byte)* rgb); nk_color nk_rgb_f(float r, float g, float b); nk_color nk_rgb_fv(const(float)* rgb); nk_color nk_rgb_cf(nk_colorf c); nk_color nk_rgb_hex(const(char)* rgb); nk_color nk_rgba(int r, int g, int b, int a); nk_color nk_rgba_u32(nk_uint); nk_color nk_rgba_iv(const(int)* rgba); nk_color nk_rgba_bv(const(nk_byte)* rgba); nk_color nk_rgba_f(float r, float g, float b, float a); nk_color nk_rgba_fv(const(float)* rgba); nk_color nk_rgba_cf(nk_colorf c); nk_color nk_rgba_hex(const(char)* rgb); nk_colorf nk_hsva_colorf(float h, float s, float v, float a); nk_colorf nk_hsva_colorfv(float* c); void nk_colorf_hsva_f(float* out_h, float* out_s, float* out_v, float* out_a, nk_colorf in_); void nk_colorf_hsva_fv(float* hsva, nk_colorf in_); nk_color nk_hsv(int h, int s, int v); nk_color nk_hsv_iv(const(int)* hsv); nk_color nk_hsv_bv(const(nk_byte)* hsv); nk_color nk_hsv_f(float h, float s, float v); nk_color nk_hsv_fv(const(float)* hsv); nk_color nk_hsva(int h, int s, int v, int a); nk_color nk_hsva_iv(const(int)* hsva); nk_color nk_hsva_bv(const(nk_byte)* hsva); nk_color nk_hsva_f(float h, float s, float v, float a); nk_color nk_hsva_fv(const(float)* hsva); void nk_color_f(float* r, float* g, float* b, float* a, nk_color); void nk_color_fv(float* rgba_out, nk_color); nk_colorf nk_color_cf(nk_color); void nk_color_d(double* r, double* g, double* b, double* a, nk_color); void nk_color_dv(double* rgba_out, nk_color); nk_uint nk_color_u32(nk_color); void nk_color_hex_rgba(char* output, nk_color); void nk_color_hex_rgb(char* output, nk_color); void nk_color_hsv_i(int* out_h, int* out_s, int* out_v, nk_color); void nk_color_hsv_b(nk_byte* out_h, nk_byte* out_s, nk_byte* out_v, nk_color); void nk_color_hsv_iv(int* hsv_out, nk_color); void nk_color_hsv_bv(nk_byte* hsv_out, nk_color); void nk_color_hsv_f(float* out_h, float* out_s, float* out_v, nk_color); void nk_color_hsv_fv(float* hsv_out, nk_color); void nk_color_hsva_i(int* h, int* s, int* v, int* a, nk_color); void nk_color_hsva_b(nk_byte* h, nk_byte* s, nk_byte* v, nk_byte* a, nk_color); void nk_color_hsva_iv(int* hsva_out, nk_color); void nk_color_hsva_bv(nk_byte* hsva_out, nk_color); void nk_color_hsva_f(float* out_h, float* out_s, float* out_v, float* out_a, nk_color); void nk_color_hsva_fv(float* hsva_out, nk_color); nk_handle nk_handle_ptr(void*); nk_handle nk_handle_id(int); nk_image nk_image_handle(nk_handle); nk_image nk_image_ptr(void*); nk_image nk_image_id(int); int nk_image_is_subimage(const(nk_image)* img); nk_image nk_subimage_ptr(void*, ushort w, ushort h, nk_rect sub_region); nk_image nk_subimage_id(int, ushort w, ushort h, nk_rect sub_region); nk_image nk_subimage_handle(nk_handle, ushort w, ushort h, nk_rect sub_region); nk_hash nk_murmur_hash(const(void)* key, int len, nk_hash seed); void nk_triangle_from_direction(nk_vec2* result, nk_rect r, float pad_x, float pad_y, nk_heading); pragma(mangle, `nk_vec2`) nk_vec2 nk_vec2_(float x, float y); pragma(mangle, `nk_vec2i`) nk_vec2 nk_vec2i_(int x, int y); nk_vec2 nk_vec2v(const(float)* xy); nk_vec2 nk_vec2iv(const(int)* xy); nk_rect nk_get_null_rect(); pragma(mangle, `nk_rect`) nk_rect nk_rect_(float x, float y, float w, float h); pragma(mangle, `nk_recti`) nk_rect nk_recti_(int x, int y, int w, int h); nk_rect nk_recta(nk_vec2 pos, nk_vec2 size); nk_rect nk_rectv(const(float)* xywh); nk_rect nk_rectiv(const(int)* xywh); nk_vec2 nk_rect_pos(nk_rect); nk_vec2 nk_rect_size(nk_rect); int nk_strlen(const(char)* str); int nk_stricmp(const(char)* s1, const(char)* s2); int nk_stricmpn(const(char)* s1, const(char)* s2, int n); int nk_strtoi(const(char)* str, const(char)** endptr); float nk_strtof(const(char)* str, const(char)** endptr); double nk_strtod(const(char)* str, const(char)** endptr); int nk_strfilter(const(char)* text, const(char)* regexp); int nk_strmatch_fuzzy_text(const(char)* txt, int txt_len, const(char)* pattern, int* out_score); int nk_utf_decode(const(char)*, nk_rune*, int); int nk_utf_encode(nk_rune, char*, int); int nk_utf_len(const(char)*, int byte_len); const(char)* nk_utf_at(const(char)* buffer, int length, int index, nk_rune* unicode, int* len); const(nk_rune)* nk_font_default_glyph_ranges(); const(nk_rune)* nk_font_chinese_glyph_ranges(); const(nk_rune)* nk_font_cyrillic_glyph_ranges(); const(nk_rune)* nk_font_korean_glyph_ranges(); void nk_font_atlas_init_default(nk_font_atlas*); void nk_font_atlas_init(nk_font_atlas*, nk_allocator*); void nk_font_atlas_init_custom(nk_font_atlas*, nk_allocator* persistent, nk_allocator* transient); void nk_font_atlas_begin(nk_font_atlas*); pragma(mangle, `nk_font_config`) nk_font_config nk_font_config_(float pixel_height); nk_font* nk_font_atlas_add(nk_font_atlas*, const(nk_font_config)*); nk_font* nk_font_atlas_add_from_memory(nk_font_atlas* atlas, void* memory, nk_size size, float height, const(nk_font_config)* config); nk_font* nk_font_atlas_add_compressed(nk_font_atlas*, void* memory, nk_size size, float height, const(nk_font_config)*); nk_font* nk_font_atlas_add_compressed_base85(nk_font_atlas*, const(char)* data, float height, const(nk_font_config)* config); const(void)* nk_font_atlas_bake(nk_font_atlas*, int* width, int* height, nk_font_atlas_format); void nk_font_atlas_end(nk_font_atlas*, nk_handle tex, nk_draw_null_texture*); const(nk_font_glyph)* nk_font_find_glyph(nk_font*, nk_rune unicode); void nk_font_atlas_cleanup(nk_font_atlas* atlas); void nk_font_atlas_clear(nk_font_atlas*); void nk_buffer_init_default(nk_buffer*); void nk_buffer_init(nk_buffer*, const(nk_allocator)*, nk_size size); void nk_buffer_init_fixed(nk_buffer*, void* memory, nk_size size); void nk_buffer_info(nk_memory_status*, nk_buffer*); void nk_buffer_push(nk_buffer*, nk_buffer_allocation_type type, const(void)* memory, nk_size size, nk_size align_); void nk_buffer_mark(nk_buffer*, nk_buffer_allocation_type type); void nk_buffer_reset(nk_buffer*, nk_buffer_allocation_type type); void nk_buffer_clear(nk_buffer*); void nk_buffer_free(nk_buffer*); void* nk_buffer_memory(nk_buffer*); const(void)* nk_buffer_memory_const(const(nk_buffer)*); nk_size nk_buffer_total(nk_buffer*); void nk_str_init_default(nk_str*); void nk_str_init(nk_str*, const(nk_allocator)*, nk_size size); void nk_str_init_fixed(nk_str*, void* memory, nk_size size); void nk_str_clear(nk_str*); void nk_str_free(nk_str*); int nk_str_append_text_char(nk_str*, const(char)*, int); int nk_str_append_str_char(nk_str*, const(char)*); int nk_str_append_text_utf8(nk_str*, const(char)*, int); int nk_str_append_str_utf8(nk_str*, const(char)*); int nk_str_append_text_runes(nk_str*, const(nk_rune)*, int); int nk_str_append_str_runes(nk_str*, const(nk_rune)*); int nk_str_insert_at_char(nk_str*, int pos, const(char)*, int); int nk_str_insert_at_rune(nk_str*, int pos, const(char)*, int); int nk_str_insert_text_char(nk_str*, int pos, const(char)*, int); int nk_str_insert_str_char(nk_str*, int pos, const(char)*); int nk_str_insert_text_utf8(nk_str*, int pos, const(char)*, int); int nk_str_insert_str_utf8(nk_str*, int pos, const(char)*); int nk_str_insert_text_runes(nk_str*, int pos, const(nk_rune)*, int); int nk_str_insert_str_runes(nk_str*, int pos, const(nk_rune)*); void nk_str_remove_chars(nk_str*, int len); void nk_str_remove_runes(nk_str* str, int len); void nk_str_delete_chars(nk_str*, int pos, int len); void nk_str_delete_runes(nk_str*, int pos, int len); char* nk_str_at_char(nk_str*, int pos); char* nk_str_at_rune(nk_str*, int pos, nk_rune* unicode, int* len); nk_rune nk_str_rune_at(const(nk_str)*, int pos); const(char)* nk_str_at_char_const(const(nk_str)*, int pos); const(char)* nk_str_at_const(const(nk_str)*, int pos, nk_rune* unicode, int* len); char* nk_str_get(nk_str*); const(char)* nk_str_get_const(const(nk_str)*); int nk_str_len(nk_str*); int nk_str_len_char(nk_str*); int nk_filter_default(const(nk_text_edit)*, nk_rune unicode); int nk_filter_ascii(const(nk_text_edit)*, nk_rune unicode); int nk_filter_float(const(nk_text_edit)*, nk_rune unicode); int nk_filter_decimal(const(nk_text_edit)*, nk_rune unicode); int nk_filter_hex(const(nk_text_edit)*, nk_rune unicode); int nk_filter_oct(const(nk_text_edit)*, nk_rune unicode); int nk_filter_binary(const(nk_text_edit)*, nk_rune unicode); void nk_textedit_init_default(nk_text_edit*); void nk_textedit_init(nk_text_edit*, nk_allocator*, nk_size size); void nk_textedit_init_fixed(nk_text_edit*, void* memory, nk_size size); void nk_textedit_free(nk_text_edit*); void nk_textedit_text(nk_text_edit*, const(char)*, int total_len); void nk_textedit_delete(nk_text_edit*, int where, int len); void nk_textedit_delete_selection(nk_text_edit*); void nk_textedit_select_all(nk_text_edit*); int nk_textedit_cut(nk_text_edit*); void nk_textedit_undo(nk_text_edit*); void nk_textedit_redo(nk_text_edit*); void nk_stroke_line(nk_command_buffer* b, float x0, float y0, float x1, float y1, float line_thickness, nk_color); void nk_stroke_curve(nk_command_buffer*, float, float, float, float, float, float, float, float, float line_thickness, nk_color); void nk_stroke_rect(nk_command_buffer*, nk_rect, float rounding, float line_thickness, nk_color); void nk_stroke_circle(nk_command_buffer*, nk_rect, float line_thickness, nk_color); void nk_stroke_arc(nk_command_buffer*, float cx, float cy, float radius, float a_min, float a_max, float line_thickness, nk_color); void nk_stroke_triangle(nk_command_buffer*, float, float, float, float, float, float, float line_thichness, nk_color); void nk_stroke_polyline(nk_command_buffer*, float* points, int point_count, float line_thickness, nk_color col); void nk_stroke_polygon(nk_command_buffer*, float*, int point_count, float line_thickness, nk_color); void nk_fill_rect(nk_command_buffer*, nk_rect, float rounding, nk_color); void nk_fill_rect_multi_color(nk_command_buffer*, nk_rect, nk_color left, nk_color top, nk_color right, nk_color bottom); void nk_fill_circle(nk_command_buffer*, nk_rect, nk_color); void nk_fill_arc(nk_command_buffer*, float cx, float cy, float radius, float a_min, float a_max, nk_color); void nk_fill_triangle(nk_command_buffer*, float x0, float y0, float x1, float y1, float x2, float y2, nk_color); void nk_fill_polygon(nk_command_buffer*, float*, int point_count, nk_color); void nk_draw_image(nk_command_buffer*, nk_rect, const(nk_image)*, nk_color); void nk_draw_text(nk_command_buffer*, nk_rect, const(char)* text, int len, const(nk_user_font)*, nk_color, nk_color); void nk_push_scissor(nk_command_buffer*, nk_rect); void nk_push_custom(nk_command_buffer*, nk_rect, nk_command_custom_callback, nk_handle usr); int nk_input_has_mouse_click(const(nk_input)*, nk_buttons); int nk_input_has_mouse_click_in_rect(const(nk_input)*, nk_buttons, nk_rect); int nk_input_has_mouse_click_down_in_rect(const(nk_input)*, nk_buttons, nk_rect, int down); int nk_input_is_mouse_click_in_rect(const(nk_input)*, nk_buttons, nk_rect); int nk_input_is_mouse_click_down_in_rect(const(nk_input)* i, nk_buttons id, nk_rect b, int down); int nk_input_any_mouse_click_in_rect(const(nk_input)*, nk_rect); int nk_input_is_mouse_prev_hovering_rect(const(nk_input)*, nk_rect); int nk_input_is_mouse_hovering_rect(const(nk_input)*, nk_rect); int nk_input_mouse_clicked(const(nk_input)*, nk_buttons, nk_rect); int nk_input_is_mouse_down(const(nk_input)*, nk_buttons); int nk_input_is_mouse_pressed(const(nk_input)*, nk_buttons); int nk_input_is_mouse_released(const(nk_input)*, nk_buttons); int nk_input_is_key_pressed(const(nk_input)*, nk_keys); int nk_input_is_key_released(const(nk_input)*, nk_keys); int nk_input_is_key_down(const(nk_input)*, nk_keys); void nk_draw_list_init(nk_draw_list*); void nk_draw_list_setup(nk_draw_list*, const(nk_convert_config)*, nk_buffer* cmds, nk_buffer* vertices, nk_buffer* elements, nk_anti_aliasing line_aa, nk_anti_aliasing shape_aa); const(nk_draw_command)* nk__draw_list_begin(const(nk_draw_list)*, const(nk_buffer)*); const(nk_draw_command)* nk__draw_list_next(const(nk_draw_command)*, const(nk_buffer)*, const(nk_draw_list)*); const(nk_draw_command)* nk__draw_list_end(const(nk_draw_list)*, const(nk_buffer)*); void nk_draw_list_path_clear(nk_draw_list*); void nk_draw_list_path_line_to(nk_draw_list*, nk_vec2 pos); void nk_draw_list_path_arc_to_fast(nk_draw_list*, nk_vec2 center, float radius, int a_min, int a_max); void nk_draw_list_path_arc_to(nk_draw_list*, nk_vec2 center, float radius, float a_min, float a_max, uint segments); void nk_draw_list_path_rect_to(nk_draw_list*, nk_vec2 a, nk_vec2 b, float rounding); void nk_draw_list_path_curve_to(nk_draw_list*, nk_vec2 p2, nk_vec2 p3, nk_vec2 p4, uint num_segments); void nk_draw_list_path_fill(nk_draw_list*, nk_color); void nk_draw_list_path_stroke(nk_draw_list*, nk_color, nk_draw_list_stroke closed, float thickness); void nk_draw_list_stroke_line(nk_draw_list*, nk_vec2 a, nk_vec2 b, nk_color, float thickness); void nk_draw_list_stroke_rect(nk_draw_list*, nk_rect rect, nk_color, float rounding, float thickness); void nk_draw_list_stroke_triangle(nk_draw_list*, nk_vec2 a, nk_vec2 b, nk_vec2 c, nk_color, float thickness); void nk_draw_list_stroke_circle(nk_draw_list*, nk_vec2 center, float radius, nk_color, uint segs, float thickness); void nk_draw_list_stroke_curve(nk_draw_list*, nk_vec2 p0, nk_vec2 cp0, nk_vec2 cp1, nk_vec2 p1, nk_color, uint segments, float thickness); void nk_draw_list_stroke_poly_line(nk_draw_list*, const(nk_vec2)* pnts, const(uint) cnt, nk_color, nk_draw_list_stroke, float thickness, nk_anti_aliasing); void nk_draw_list_fill_rect(nk_draw_list*, nk_rect rect, nk_color, float rounding); void nk_draw_list_fill_rect_multi_color(nk_draw_list*, nk_rect rect, nk_color left, nk_color top, nk_color right, nk_color bottom); void nk_draw_list_fill_triangle(nk_draw_list*, nk_vec2 a, nk_vec2 b, nk_vec2 c, nk_color); void nk_draw_list_fill_circle(nk_draw_list*, nk_vec2 center, float radius, nk_color col, uint segs); void nk_draw_list_fill_poly_convex(nk_draw_list*, const(nk_vec2)* points, const(uint) count, nk_color, nk_anti_aliasing); void nk_draw_list_add_image(nk_draw_list*, nk_image texture, nk_rect rect, nk_color); void nk_draw_list_add_text(nk_draw_list*, const(nk_user_font)*, nk_rect, const(char)* text, int len, float font_height, nk_color); nk_style_item nk_style_item_image(nk_image img); nk_style_item nk_style_item_color(nk_color); nk_style_item nk_style_item_hide();
D
#!/usr/bin/env rund //!env CC=c++ //!version MARS //!importPath ../../dmd/src //!importFilenamePath ../../dmd/res //!importFilenamePath ../../dmd/generated/linux/release/64 //!library ../../dmd/generated/linux/release/64/newdelete.o //!library ../../dmd/generated/linux/release/64/backend.a //!library ../../dmd/generated/linux/release/64/lexer.a /* This wrapper can be used to compile/run dmd (with some caveats). * You need to have the dmd repository cloned to "../../dmd" (relative to this file). * You need to have built the C libraries. You can build these libraries by building dmd. Note sure why, but through trial and error I determined that this is the minimum set of modules that I needed to import in order to successfully include all of the symbols to compile/link dmd. */ import dmd.eh; import dmd.dmsc; import dmd.toobj; import dmd.iasm;
D
module godot.polygon2d; import std.meta : AliasSeq, staticIndexOf; import std.traits : Unqual; import godot.d.meta; import godot.core; import godot.c; import godot.d.bind; import godot.object; import godot.classdb; import godot.node2d; import godot.texture; @GodotBaseClass struct Polygon2D { static immutable string _GODOT_internal_name = "Polygon2D"; public: union { godot_object _godot_object; Node2D base; } alias base this; alias BaseClasses = AliasSeq!(typeof(base), typeof(base).BaseClasses); bool opEquals(in Polygon2D other) const { return _godot_object.ptr is other._godot_object.ptr; } Polygon2D opAssign(T : typeof(null))(T n) { _godot_object.ptr = null; } bool opEquals(typeof(null) n) const { return _godot_object.ptr is null; } mixin baseCasts; static Polygon2D _new() { static godot_class_constructor constructor; if(constructor is null) constructor = godot_get_class_constructor("Polygon2D"); if(constructor is null) return typeof(this).init; return cast(Polygon2D)(constructor()); } package(godot) static GodotMethod!(void, PoolVector2Array) _GODOT_set_polygon; package(godot) alias _GODOT_methodBindInfo(string name : "set_polygon") = _GODOT_set_polygon; void set_polygon(in PoolVector2Array polygon) { _GODOT_set_polygon.bind("Polygon2D", "set_polygon"); ptrcall!(void)(_GODOT_set_polygon, _godot_object, polygon); } package(godot) static GodotMethod!(PoolVector2Array) _GODOT_get_polygon; package(godot) alias _GODOT_methodBindInfo(string name : "get_polygon") = _GODOT_get_polygon; PoolVector2Array get_polygon() const { _GODOT_get_polygon.bind("Polygon2D", "get_polygon"); return ptrcall!(PoolVector2Array)(_GODOT_get_polygon, _godot_object); } package(godot) static GodotMethod!(void, PoolVector2Array) _GODOT_set_uv; package(godot) alias _GODOT_methodBindInfo(string name : "set_uv") = _GODOT_set_uv; void set_uv(in PoolVector2Array uv) { _GODOT_set_uv.bind("Polygon2D", "set_uv"); ptrcall!(void)(_GODOT_set_uv, _godot_object, uv); } package(godot) static GodotMethod!(PoolVector2Array) _GODOT_get_uv; package(godot) alias _GODOT_methodBindInfo(string name : "get_uv") = _GODOT_get_uv; PoolVector2Array get_uv() const { _GODOT_get_uv.bind("Polygon2D", "get_uv"); return ptrcall!(PoolVector2Array)(_GODOT_get_uv, _godot_object); } package(godot) static GodotMethod!(void, Color) _GODOT_set_color; package(godot) alias _GODOT_methodBindInfo(string name : "set_color") = _GODOT_set_color; void set_color(in Color color) { _GODOT_set_color.bind("Polygon2D", "set_color"); ptrcall!(void)(_GODOT_set_color, _godot_object, color); } package(godot) static GodotMethod!(Color) _GODOT_get_color; package(godot) alias _GODOT_methodBindInfo(string name : "get_color") = _GODOT_get_color; Color get_color() const { _GODOT_get_color.bind("Polygon2D", "get_color"); return ptrcall!(Color)(_GODOT_get_color, _godot_object); } package(godot) static GodotMethod!(void, PoolColorArray) _GODOT_set_vertex_colors; package(godot) alias _GODOT_methodBindInfo(string name : "set_vertex_colors") = _GODOT_set_vertex_colors; void set_vertex_colors(in PoolColorArray vertex_colors) { _GODOT_set_vertex_colors.bind("Polygon2D", "set_vertex_colors"); ptrcall!(void)(_GODOT_set_vertex_colors, _godot_object, vertex_colors); } package(godot) static GodotMethod!(PoolColorArray) _GODOT_get_vertex_colors; package(godot) alias _GODOT_methodBindInfo(string name : "get_vertex_colors") = _GODOT_get_vertex_colors; PoolColorArray get_vertex_colors() const { _GODOT_get_vertex_colors.bind("Polygon2D", "get_vertex_colors"); return ptrcall!(PoolColorArray)(_GODOT_get_vertex_colors, _godot_object); } package(godot) static GodotMethod!(void, Texture) _GODOT_set_texture; package(godot) alias _GODOT_methodBindInfo(string name : "set_texture") = _GODOT_set_texture; void set_texture(in Texture texture) { _GODOT_set_texture.bind("Polygon2D", "set_texture"); ptrcall!(void)(_GODOT_set_texture, _godot_object, texture); } package(godot) static GodotMethod!(Texture) _GODOT_get_texture; package(godot) alias _GODOT_methodBindInfo(string name : "get_texture") = _GODOT_get_texture; Texture get_texture() const { _GODOT_get_texture.bind("Polygon2D", "get_texture"); return ptrcall!(Texture)(_GODOT_get_texture, _godot_object); } package(godot) static GodotMethod!(void, Vector2) _GODOT_set_texture_offset; package(godot) alias _GODOT_methodBindInfo(string name : "set_texture_offset") = _GODOT_set_texture_offset; void set_texture_offset(in Vector2 texture_offset) { _GODOT_set_texture_offset.bind("Polygon2D", "set_texture_offset"); ptrcall!(void)(_GODOT_set_texture_offset, _godot_object, texture_offset); } package(godot) static GodotMethod!(Vector2) _GODOT_get_texture_offset; package(godot) alias _GODOT_methodBindInfo(string name : "get_texture_offset") = _GODOT_get_texture_offset; Vector2 get_texture_offset() const { _GODOT_get_texture_offset.bind("Polygon2D", "get_texture_offset"); return ptrcall!(Vector2)(_GODOT_get_texture_offset, _godot_object); } package(godot) static GodotMethod!(void, float) _GODOT_set_texture_rotation; package(godot) alias _GODOT_methodBindInfo(string name : "set_texture_rotation") = _GODOT_set_texture_rotation; void set_texture_rotation(in float texture_rotation) { _GODOT_set_texture_rotation.bind("Polygon2D", "set_texture_rotation"); ptrcall!(void)(_GODOT_set_texture_rotation, _godot_object, texture_rotation); } package(godot) static GodotMethod!(float) _GODOT_get_texture_rotation; package(godot) alias _GODOT_methodBindInfo(string name : "get_texture_rotation") = _GODOT_get_texture_rotation; float get_texture_rotation() const { _GODOT_get_texture_rotation.bind("Polygon2D", "get_texture_rotation"); return ptrcall!(float)(_GODOT_get_texture_rotation, _godot_object); } package(godot) static GodotMethod!(void, float) _GODOT__set_texture_rotationd; package(godot) alias _GODOT_methodBindInfo(string name : "_set_texture_rotationd") = _GODOT__set_texture_rotationd; void _set_texture_rotationd(in float texture_rotation) { Array _GODOT_args = Array.empty_array; _GODOT_args.append(texture_rotation); String _GODOT_method_name = String("_set_texture_rotationd"); this.callv(_GODOT_method_name, _GODOT_args); } package(godot) static GodotMethod!(float) _GODOT__get_texture_rotationd; package(godot) alias _GODOT_methodBindInfo(string name : "_get_texture_rotationd") = _GODOT__get_texture_rotationd; float _get_texture_rotationd() const { Array _GODOT_args = Array.empty_array; String _GODOT_method_name = String("_get_texture_rotationd"); return this.callv(_GODOT_method_name, _GODOT_args).as!(float); } package(godot) static GodotMethod!(void, Vector2) _GODOT_set_texture_scale; package(godot) alias _GODOT_methodBindInfo(string name : "set_texture_scale") = _GODOT_set_texture_scale; void set_texture_scale(in Vector2 texture_scale) { _GODOT_set_texture_scale.bind("Polygon2D", "set_texture_scale"); ptrcall!(void)(_GODOT_set_texture_scale, _godot_object, texture_scale); } package(godot) static GodotMethod!(Vector2) _GODOT_get_texture_scale; package(godot) alias _GODOT_methodBindInfo(string name : "get_texture_scale") = _GODOT_get_texture_scale; Vector2 get_texture_scale() const { _GODOT_get_texture_scale.bind("Polygon2D", "get_texture_scale"); return ptrcall!(Vector2)(_GODOT_get_texture_scale, _godot_object); } package(godot) static GodotMethod!(void, bool) _GODOT_set_invert; package(godot) alias _GODOT_methodBindInfo(string name : "set_invert") = _GODOT_set_invert; void set_invert(in bool invert) { _GODOT_set_invert.bind("Polygon2D", "set_invert"); ptrcall!(void)(_GODOT_set_invert, _godot_object, invert); } package(godot) static GodotMethod!(bool) _GODOT_get_invert; package(godot) alias _GODOT_methodBindInfo(string name : "get_invert") = _GODOT_get_invert; bool get_invert() const { _GODOT_get_invert.bind("Polygon2D", "get_invert"); return ptrcall!(bool)(_GODOT_get_invert, _godot_object); } package(godot) static GodotMethod!(void, bool) _GODOT_set_antialiased; package(godot) alias _GODOT_methodBindInfo(string name : "set_antialiased") = _GODOT_set_antialiased; void set_antialiased(in bool antialiased) { _GODOT_set_antialiased.bind("Polygon2D", "set_antialiased"); ptrcall!(void)(_GODOT_set_antialiased, _godot_object, antialiased); } package(godot) static GodotMethod!(bool) _GODOT_get_antialiased; package(godot) alias _GODOT_methodBindInfo(string name : "get_antialiased") = _GODOT_get_antialiased; bool get_antialiased() const { _GODOT_get_antialiased.bind("Polygon2D", "get_antialiased"); return ptrcall!(bool)(_GODOT_get_antialiased, _godot_object); } package(godot) static GodotMethod!(void, float) _GODOT_set_invert_border; package(godot) alias _GODOT_methodBindInfo(string name : "set_invert_border") = _GODOT_set_invert_border; void set_invert_border(in float invert_border) { _GODOT_set_invert_border.bind("Polygon2D", "set_invert_border"); ptrcall!(void)(_GODOT_set_invert_border, _godot_object, invert_border); } package(godot) static GodotMethod!(float) _GODOT_get_invert_border; package(godot) alias _GODOT_methodBindInfo(string name : "get_invert_border") = _GODOT_get_invert_border; float get_invert_border() const { _GODOT_get_invert_border.bind("Polygon2D", "get_invert_border"); return ptrcall!(float)(_GODOT_get_invert_border, _godot_object); } package(godot) static GodotMethod!(void, Vector2) _GODOT_set_offset; package(godot) alias _GODOT_methodBindInfo(string name : "set_offset") = _GODOT_set_offset; void set_offset(in Vector2 offset) { _GODOT_set_offset.bind("Polygon2D", "set_offset"); ptrcall!(void)(_GODOT_set_offset, _godot_object, offset); } package(godot) static GodotMethod!(Vector2) _GODOT_get_offset; package(godot) alias _GODOT_methodBindInfo(string name : "get_offset") = _GODOT_get_offset; Vector2 get_offset() const { _GODOT_get_offset.bind("Polygon2D", "get_offset"); return ptrcall!(Vector2)(_GODOT_get_offset, _godot_object); } }
D
/home/sky/Workshop/solana-app/target/bpfel-unknown-unknown/release/deps/cfg_if-b1a813859962081f.rmeta: /home/sky/.cargo/registry/src/github.com-1ecc6299db9ec823/cfg-if-1.0.0/src/lib.rs /home/sky/Workshop/solana-app/target/bpfel-unknown-unknown/release/deps/libcfg_if-b1a813859962081f.rlib: /home/sky/.cargo/registry/src/github.com-1ecc6299db9ec823/cfg-if-1.0.0/src/lib.rs /home/sky/Workshop/solana-app/target/bpfel-unknown-unknown/release/deps/cfg_if-b1a813859962081f.d: /home/sky/.cargo/registry/src/github.com-1ecc6299db9ec823/cfg-if-1.0.0/src/lib.rs /home/sky/.cargo/registry/src/github.com-1ecc6299db9ec823/cfg-if-1.0.0/src/lib.rs:
D
/home/gambl3r/Rust/telegrambotdev/BotDev/target/rls/debug/build/serde-27df1f8e6eb9b120/build_script_build-27df1f8e6eb9b120: /home/gambl3r/.cargo/registry/src/github.com-1ecc6299db9ec823/serde-1.0.125/build.rs /home/gambl3r/Rust/telegrambotdev/BotDev/target/rls/debug/build/serde-27df1f8e6eb9b120/build_script_build-27df1f8e6eb9b120.d: /home/gambl3r/.cargo/registry/src/github.com-1ecc6299db9ec823/serde-1.0.125/build.rs /home/gambl3r/.cargo/registry/src/github.com-1ecc6299db9ec823/serde-1.0.125/build.rs:
D
PLONG PLAT ED95 KD LOMAGAGE HIMAGAGE SLAT SLONG RESULTNO DP DM WT ROCKTYPE 4.5 80.5 11.8999996 29 8 9 35.7000008 -106.5 304 14.1999998 14.1999998 1 extrusives, basalts, rhyolites 275.5 83.5999985 0 0 0 20 46.7999992 -90.6999969 5904 3.4000001 3.4000001 0.4 sediments 45.2999992 81.0999985 12.8999996 51.9000015 14 17 45.2999992 -110.800003 5975 13.5 18.6000004 0.666666667 sediments
D
import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric, std.container; struct BITree(alias _fun, alias E, T) if (is(typeof(E) : T)) { import std.functional : binaryFun; alias OP = binaryFun!_fun; /// this(size_t n, T[] ts) { this.n = n; this.tree.length = n+1; foreach (ref e; this.tree) e = E; foreach (i, t; ts) this.update(i, t); } void update(size_t i, T e) { i += 1; while (i <= this.n) { this.tree[i] = OP(this.tree[i], e); i += i & -i; } } /// T query(size_t i) { auto r = E; while (i > 0) { r = OP(r, this.tree[i]); i -= i & -i; } return r; } private: size_t n; T[] tree; } auto bitree(alias fun, alias init, T)(size_t n, T[] ts = []) { return BITree!(fun, init, T)(n, ts); } /// auto bitree(alias fun, alias init, T)(T[] ts) { return BITree!(fun, init, T)(ts.length, ts); } auto sum_bitree(T)(size_t n, T[] ts = []) { return bitree!("a + b", 0, T)(n, ts); } auto sum_bitree(T)(T[] ts) { return sum_bitree!T(ts.length, ts); } void main() { auto nq = readln.split.to!(int[]); auto N = nq[0]; auto Q = nq[1]; auto bit = sum_bitree!int(N+1); foreach (_; 0..N) { int a; readf(" %d", &a); bit.update(a, 1); } foreach (_; 0..Q) { int q; readf(" %d", &q); if (q < 0) { q = -q; size_t l = 1, r = N+1; while (l+1 < r) { auto m = (l+r)/2; if (bit.query(m) < q) { l = m; } else { r = m; } } bit.update(l, -1); } else { bit.update(q, 1); } } foreach (i; 1..N+1) if (bit.query(i+1) > 0) { writeln(i); return; } writeln(0); }
D
<?xml version="1.0" encoding="ASCII" standalone="no"?> <di:SashWindowsMngr xmlns:di="http://www.eclipse.org/papyrus/0.7.0/sashdi" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmi:version="2.0"> <pageList> <availablePage> <emfPageIdentifier href="VAR_15_BeT-4226597158.notation#_copSALmGEeKQQp7P9cQvNQ"/> </availablePage> </pageList> <sashModel currentSelection="//@sashModel/@windows.0/@children.0"> <windows> <children xsi:type="di:TabFolder"> <children> <emfPageIdentifier href="VAR_15_BeT-4226597158.notation#_copSALmGEeKQQp7P9cQvNQ"/> </children> </children> </windows> </sashModel> </di:SashWindowsMngr>
D
module runme; import tango.io.Stdout; static import example; void main() { /* * Call our gcd() function. */ int x = 42; int y = 105; int g = example.gcd( x, y ); Stdout.format( "The gcd of {} and {} is {}.", x, y, g ).newline; /* * Manipulate the Foo global variable. */ // Output its current value Stdout.format( "Foo = {}", example.Foo ).newline; // Change its value example.Foo = 3.1415926; // See if the change took effect Stdout.format( "Foo = {}", example.Foo ).newline; }
D
module org.serviio.library.playlist.ParsedPlaylist; import java.lang.String; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.serviio.library.playlist.PlaylistItem; public class ParsedPlaylist { private String title; private List!(PlaylistItem) items; public this(String title) { this.title = title; items = new ArrayList!(PlaylistItem)(); } public void addItem(String path) { items.add(new PlaylistItem(path, Integer.valueOf(items.size() + 1))); } public List!(PlaylistItem) getItems() { return Collections.unmodifiableList(items); } public String getTitle() { return title; } } /* Location: D:\Program Files\Serviio\lib\serviio.jar * Qualified Name: org.serviio.library.playlist.ParsedPlaylist * JD-Core Version: 0.6.2 */
D
import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric; void main() { readln; int[long] MEMO; foreach (a; readln.split.to!(long[])) { while (a%2 == 0) a /= 2; MEMO[a] = 1; } int r; foreach (_; MEMO) ++r; writeln(r); }
D
module android.java.android.view.textclassifier.TextClassifier_d_interface; import arsd.jni : IJavaObjectImplementation, JavaPackageId, JavaName, IJavaObject, ImportExportImpl, JavaInterfaceMembers; static import arsd.jni; import import1 = android.java.android.view.textclassifier.TextSelection_Request_d_interface; import import2 = android.java.java.lang.CharSequence_d_interface; import import5 = android.java.android.view.textclassifier.TextClassification_Request_d_interface; import import7 = android.java.android.view.textclassifier.TextLinks_Request_d_interface; import import13 = android.java.android.view.textclassifier.TextClassifierEvent_d_interface; import import14 = android.java.java.lang.Class_d_interface; import import0 = android.java.android.view.textclassifier.TextSelection_d_interface; import import3 = android.java.android.os.LocaleList_d_interface; import import10 = android.java.android.view.textclassifier.ConversationActions_d_interface; import import6 = android.java.android.view.textclassifier.TextLinks_d_interface; import import8 = android.java.android.view.textclassifier.TextLanguage_d_interface; import import9 = android.java.android.view.textclassifier.TextLanguage_Request_d_interface; import import11 = android.java.android.view.textclassifier.ConversationActions_Request_d_interface; import import4 = android.java.android.view.textclassifier.TextClassification_d_interface; import import12 = android.java.android.view.textclassifier.SelectionEvent_d_interface; final class TextClassifier : IJavaObject { static immutable string[] _d_canCastTo = [ ]; @Import import0.TextSelection suggestSelection(import1.TextSelection_Request); @Import import0.TextSelection suggestSelection(import2.CharSequence, int, int, import3.LocaleList); @Import import4.TextClassification classifyText(import5.TextClassification_Request); @Import import4.TextClassification classifyText(import2.CharSequence, int, int, import3.LocaleList); @Import import6.TextLinks generateLinks(import7.TextLinks_Request); @Import int getMaxGenerateLinksTextLength(); @Import import8.TextLanguage detectLanguage(import9.TextLanguage_Request); @Import import10.ConversationActions suggestConversationActions(import11.ConversationActions_Request); @Import void onSelectionEvent(import12.SelectionEvent); @Import void onTextClassifierEvent(import13.TextClassifierEvent); @Import void destroy(); @Import bool isDestroyed(); @Import import14.Class getClass(); @Import int hashCode(); @Import bool equals(IJavaObject); @Import @JavaName("toString") string toString_(); override string toString() { return arsd.jni.javaObjectToString(this); } @Import void notify(); @Import void notifyAll(); @Import void wait(long); @Import void wait(long, int); @Import void wait(); mixin IJavaObjectImplementation!(false); public static immutable string _javaParameterString = "Landroid/view/textclassifier/TextClassifier;"; }
D
module hunt.redis; import java.io.Closeable; import hunt.collection.ArraryList; import hunt.collection.List; import hunt.redis.exceptions.RedisDataException; /** * Transaction is nearly identical to Pipeline, only differences are the multi/discard behaviors */ public class Transaction extends MultiKeyPipelineBase implements Closeable { protected boolean inTransaction = true; protected Transaction() { // client will be set later in transaction block } public Transaction(final Client client) { this.client = client; } @Override protected Client getClient(String key) { return client; } @Override protected Client getClient(byte[] key) { return client; } public void clear() { if (inTransaction) { discard(); } } public List<Object> exec() { // Discard QUEUED or ERROR client.getMany(getPipelinedResponseLength()); client.exec(); inTransaction = false; List<Object> unformatted = client.getObjectMultiBulkReply(); if (unformatted == null) { return null; } List<Object> formatted = new ArrayList<Object>(); for (Object o : unformatted) { try { formatted.add(generateResponse(o).get()); } catch (RedisDataException e) { formatted.add(e); } } return formatted; } public List<Response<?>> execGetResponse() { // Discard QUEUED or ERROR client.getMany(getPipelinedResponseLength()); client.exec(); inTransaction = false; List<Object> unformatted = client.getObjectMultiBulkReply(); if (unformatted == null) { return null; } List<Response<?>> response = new ArrayList<Response<?>>(); for (Object o : unformatted) { response.add(generateResponse(o)); } return response; } public String discard() { client.getMany(getPipelinedResponseLength()); client.discard(); inTransaction = false; clean(); return client.getStatusCodeReply(); } public void setClient(Client client) { this.client = client; } @Override public void close() { clear(); } }
D
module UnrealScript.Engine.InterpTrackInstMove; import ScriptClasses; import UnrealScript.Helpers; import UnrealScript.Engine.InterpTrackInst; import UnrealScript.Core.UObject; extern(C++) interface InterpTrackInstMove : InterpTrackInst { public extern(D): private static __gshared ScriptClass mStaticClass; @property final static ScriptClass StaticClass() { mixin(MGSCC("Class Engine.InterpTrackInstMove")); } private static __gshared InterpTrackInstMove mDefaultProperties; @property final static InterpTrackInstMove DefaultProperties() { mixin(MGDPC("InterpTrackInstMove", "InterpTrackInstMove Engine.Default__InterpTrackInstMove")); } @property final auto ref { UObject.Quat InitialQuat() { mixin(MGPC("UObject.Quat", 160)); } UObject.Matrix InitialTM() { mixin(MGPC("UObject.Matrix", 96)); } Rotator ResetRotation() { mixin(MGPC("Rotator", 72)); } Vector ResetLocation() { mixin(MGPC("Vector", 60)); } } }
D
/Users/seijiro/work/rust/20191110/201912/webapi/target/debug/deps/string-a0b2768ac078a4a9.rmeta: /Users/seijiro/.cargo/registry/src/github.com-1ecc6299db9ec823/string-0.2.1/src/lib.rs /Users/seijiro/work/rust/20191110/201912/webapi/target/debug/deps/string-a0b2768ac078a4a9.d: /Users/seijiro/.cargo/registry/src/github.com-1ecc6299db9ec823/string-0.2.1/src/lib.rs /Users/seijiro/.cargo/registry/src/github.com-1ecc6299db9ec823/string-0.2.1/src/lib.rs:
D
# FIXED F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/source/F2837xD_EPwm.c F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_device.h F2837xD_EPwm.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/assert.h F2837xD_EPwm.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/_ti_config.h F2837xD_EPwm.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/linkage.h F2837xD_EPwm.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/stdarg.h F2837xD_EPwm.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/sys/_types.h F2837xD_EPwm.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/sys/cdefs.h F2837xD_EPwm.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/machine/_types.h F2837xD_EPwm.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/stdbool.h F2837xD_EPwm.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/stddef.h F2837xD_EPwm.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/stdint.h F2837xD_EPwm.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/_stdint40.h F2837xD_EPwm.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/sys/stdint.h F2837xD_EPwm.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/machine/_stdint.h F2837xD_EPwm.obj: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/sys/_stdint.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_adc.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_analogsubsys.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_cla.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_cmpss.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_cputimer.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_dac.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_dcsm.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_dma.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_ecap.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_emif.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_epwm.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_epwm_xbar.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_eqep.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_flash.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_gpio.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_i2c.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_input_xbar.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_ipc.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_mcbsp.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_memconfig.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_nmiintrupt.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_output_xbar.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_piectrl.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_pievect.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_sci.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_sdfm.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_spi.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_sysctrl.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_upp.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_xbar.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_xint.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_can.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Examples.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_GlobalPrototypes.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_cputimervars.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Cla_defines.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_EPwm_defines.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Adc_defines.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Emif_defines.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Gpio_defines.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_I2c_defines.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Ipc_defines.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Pie_defines.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Dma_defines.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_SysCtrl_defines.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Upp_defines.h F2837xD_EPwm.obj: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_defaultisr.h C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/source/F2837xD_EPwm.c: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_device.h: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/assert.h: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/_ti_config.h: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/linkage.h: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/stdarg.h: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/sys/_types.h: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/sys/cdefs.h: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/machine/_types.h: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/stdbool.h: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/stddef.h: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/stdint.h: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/_stdint40.h: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/sys/stdint.h: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/machine/_stdint.h: C:/ti/ccsv6/tools/compiler/ti-cgt-c2000_20.12.0.STS/include/sys/_stdint.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_adc.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_analogsubsys.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_cla.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_cmpss.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_cputimer.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_dac.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_dcsm.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_dma.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_ecap.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_emif.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_epwm.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_epwm_xbar.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_eqep.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_flash.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_gpio.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_i2c.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_input_xbar.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_ipc.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_mcbsp.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_memconfig.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_nmiintrupt.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_output_xbar.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_piectrl.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_pievect.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_sci.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_sdfm.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_spi.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_sysctrl.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_upp.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_xbar.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_xint.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_headers/include/F2837xD_can.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Examples.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_GlobalPrototypes.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_cputimervars.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Cla_defines.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_EPwm_defines.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Adc_defines.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Emif_defines.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Gpio_defines.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_I2c_defines.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Ipc_defines.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Pie_defines.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Dma_defines.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_SysCtrl_defines.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_Upp_defines.h: C:/ti/controlSUITE/device_support/F2837xD/v210/F2837xD_common/include/F2837xD_defaultisr.h:
D
/** Relative Strength Index. http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:relative_strength_index_rsi */ module crypto.exchanges.indicators.rsi; import crypto.exchanges.indicators.base; import crypto.exchanges.indicators.smma; /// Relative Strength Index Indicator. class RSI : Indicator { bool _init = false; float _lastClose; int _age; float _u, _d; SMMA _avgU, _avgD; float _rs; this(int weight) { _avgU = new SMMA(weight); _avgD = new SMMA(weight); } override float update(in float price) pure nothrow @safe @nogc { auto currentClose = price; if (!_init) { _lastClose = currentClose; _init = true; return 0; } if (currentClose > _lastClose) { _u = currentClose - _lastClose; _d = 0; } else { _u = 0; _d = _lastClose - currentClose; } _lastClose = currentClose; auto _avgUResult = _avgU.update(_u); auto _avgDResult = _avgD.update(_d); if (_avgDResult is 0 && _avgUResult !is 0) return 100; else if (_avgDResult is 0) return 0; else { float rs = _avgUResult / _avgDResult; return 100 - (100 / (1 + rs)); } } } /// unittest { import std.algorithm.comparison : equal; import std.math : approxEqual; float[] prices = [81, 24, 75, 21, 34, 25, 72, 92, 99, 2, 86, 80, 76, 8, 87, 75, 32, 65, 41, 9, 13, 26, 56, 28, 65, 58, 17, 90, 87, 86, 99, 3, 70, 1, 27, 9, 92, 68, 9]; float[] exp_12 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49.44320712694878, 42.432667245873155, 51.2017782300719, 49.94116787991835, 45.55663590860508, 49.284333951746184, 46.74501674557244, 43.4860123510052, 44.01823674189631, 45.82704797004994, 49.90209564896179, 46.351969981868436, 51.34208640997234, 50.37501845071388, 44.96351306736635, 54.464714123844956, 54.04642006918241, 53.895901697369816, 55.6476477612053, 42.60631369413207, 51.2964732419777, 43.83906729252931, 47.00600661743475, 45.08586375053323, 54.44633399991266, 51.6681674437389, 45.44886082103851]; assert(equal!approxEqual(exp_12, new RSI(12).compute(prices))); }
D
a person working in the service of another (especially in the household) in a subordinate position
D
import std.stdio, std.array, std.string, std.conv, std.algorithm; import std.typecons, std.range, std.random, std.math, std.container; import std.numeric, std.bigint, core.bitop; immutable long INF = 10L ^^ 18 + 1000; void main() { auto S = readln.chomp; auto N = S.length.to!int; auto K = readln.chomp.to!long; auto chars = new int[][](26, N); foreach (i; 0..26) { int tmp = -1; for (int j = N - 1; j >= 0; j--) { if (S[j] - 'a' == i) tmp = j; chars[i][j] = tmp; } } auto dp = new long[](N); fill(dp, 1); for (int i = N - 2; i >= 0; i--) { foreach (j; 0..26) { int m = chars[j][i + 1]; if (m == -1) continue; if (dp[m] == INF) { dp[i] = INF; continue; } dp[i] += dp[m]; if (dp[i] > INF || dp[i] <= 0) { dp[i] = INF; continue; } } } string ans = ""; void dfs(int p, long acm) { if (acm == K) return; foreach (i; 0..26) { int m = chars[i][p]; if (m == -1) continue; if (acm + dp[chars[i][m]] >= K) { ans ~= i.to!char + 'a'; dfs(chars[i][m] + 1, acm + 1); return; } acm += dp[chars[i][m]]; } } dfs(0, 0); if (ans == "") writeln("Eel"); else writeln(ans); }
D
module D; import A; import B; void test() { //foo(); // error, A.foo() or B.foo() ? A.foo(); // ok, call A.foo() B.foo(); // ok, call B.foo() }
D
/Users/andre/Devel/rust_project/rust_from_python/target/release/deps/libindoc_impl-427e4191f5066e6c.dylib: /Users/andre/.cargo/registry/src/github.com-1ecc6299db9ec823/indoc-impl-0.3.6/src/lib.rs /Users/andre/Devel/rust_project/rust_from_python/target/release/deps/indoc_impl-427e4191f5066e6c.d: /Users/andre/.cargo/registry/src/github.com-1ecc6299db9ec823/indoc-impl-0.3.6/src/lib.rs /Users/andre/.cargo/registry/src/github.com-1ecc6299db9ec823/indoc-impl-0.3.6/src/lib.rs:
D
/home/hustccc/OS_Tutorial_Summer_of_Code/rCore_Labs/Lab4/os/target/debug/build/log-a2da96f803a2c8ca/build_script_build-a2da96f803a2c8ca: /home/hustccc/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/log-0.4.8/build.rs /home/hustccc/OS_Tutorial_Summer_of_Code/rCore_Labs/Lab4/os/target/debug/build/log-a2da96f803a2c8ca/build_script_build-a2da96f803a2c8ca.d: /home/hustccc/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/log-0.4.8/build.rs /home/hustccc/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/log-0.4.8/build.rs:
D
; Copyright (C) 2008 The Android Open Source Project ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. .source T_check_cast_6.java .class public dot.junit.opcodes.check_cast.d.T_check_cast_6 .super java/lang/Object .method public <init>()V .limit regs 1 invoke-direct {v0}, java/lang/Object/<init>()V return-void .end method .method public run(Ljava/lang/Object;)V .limit regs 5 check-cast v5, java/lang/String return-void .end method
D
instance BDT_1031_Fluechtling(Npc_Default) { name[0] = NAME_Fluechtling; guild = GIL_BDT; id = 1031; voice = 7; flags = 0; npcType = npctype_main; aivar[AIV_EnemyOverride] = TRUE; B_SetAttributesToChapter(self,3); fight_tactic = FAI_HUMAN_STRONG; EquipItem(self,ItMw_1h_Sld_Sword_New); B_CreateAmbientInv(self); CreateInvItems(self,ItWr_MorgahardTip,1); B_SetNpcVisual(self,MALE,"Hum_Head_Bald",Face_B_Normal01,BodyTex_B,ITAR_Prisoner); Mdl_SetModelFatness(self,0); Mdl_ApplyOverlayMds(self,"Humans_Relaxed.mds"); B_GiveNpcTalents(self); B_SetFightSkills(self,60); daily_routine = Rtn_Start_1031; }; func void Rtn_Start_1031() { TA_Sit_Chair(8,0,23,0,"NW_XARDAS_BANDITS_LEFT"); TA_Sit_Chair(23,0,8,0,"NW_XARDAS_BANDITS_LEFT"); };
D
instance Mod_1552_SKE_Skelett_DI2 (Npc_Default) { // ------ NSC ------ name = "Sprechender Zombie"; guild = GIL_zombie; id = 1552; voice = 0; flags = 2; level = 34; // ------ Attribute ------ attribute [ATR_STRENGTH] = 100; //+50 Waffe attribute [ATR_DEXTERITY] = 150; attribute [ATR_HITPOINTS_MAX] = 150; attribute [ATR_HITPOINTS] = 150; attribute [ATR_MANA_MAX] = 0; attribute [ATR_MANA] = 0; //----- Protection ---- protection [PROT_BLUNT] = 125; protection [PROT_EDGE] = 125; protection [PROT_POINT] = -1; protection [PROT_FIRE] = 125; protection [PROT_FLY] = 125; protection [PROT_MAGIC] = 0; // ------ Kampf-Taktik ------ fight_tactic = FAI_ZOMBIE; // ------ Equippte Waffen ------ // ------ Inventory ------ // ------ visuals ------ Mdl_SetVisual (self, "Zombie.mds"); // Body-Mesh Body-Tex Skin-Color Head-MMS Head-Tex Teeth-Tex ARMOR Mdl_SetVisualBody (self, "Zom_Body", 0, 1, "Zom_Head", 1, DEFAULT, ITAR_Pir_Zombie); // ------ NSC-relevante Talente vergeben ------ // ------ Kampf-Talente ------ senses = SENSE_SEE; senses_range = 100; CreateInvItems (self, ItWr_BookFromSkeleton, 1); // ------ TA anmelden ------ daily_routine = Rtn_Start_1552; }; FUNC VOID Rtn_Start_1552 () { TA_Stand_Zombie (08,00,19,02,"WP_DI_SKELETON_STAND"); TA_Stand_Zombie (19,02,23,00,"WP_DI_SKELETON_STAND"); };
D
/** * Compiler implementation of the * $(LINK2 http://www.dlang.org, D programming language). * * Copyright: Copyright (C) 1999-2019 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/dsymbol.d, _dsymbol.d) * Documentation: https://dlang.org/phobos/dmd_dsymbol.html * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/dsymbol.d */ module dmd.dsymbol; import core.stdc.stdarg; import core.stdc.stdio; import core.stdc.string; import core.stdc.stdlib; import dmd.aggregate; import dmd.aliasthis; import dmd.arraytypes; import dmd.attrib; import dmd.ast_node; import dmd.gluelayer; import dmd.dclass; import dmd.declaration; import dmd.denum; import dmd.dimport; import dmd.dmodule; import dmd.dscope; import dmd.dstruct; import dmd.dsymbolsem; import dmd.dtemplate; import dmd.errors; import dmd.expression; import dmd.expressionsem; import dmd.func; import dmd.globals; import dmd.id; import dmd.identifier; import dmd.init; import dmd.lexer; import dmd.mtype; import dmd.nspace; import dmd.opover; import dmd.root.aav; import dmd.root.rmem; import dmd.root.rootobject; import dmd.root.speller; import dmd.statement; import dmd.tokens; import dmd.visitor; /*************************************** * Calls dg(Dsymbol *sym) for each Dsymbol. * If dg returns !=0, stops and returns that value else returns 0. * Params: * symbols = Dsymbols * dg = delegate to call for each Dsymbol * Returns: * last value returned by dg() */ int foreachDsymbol(Dsymbols* symbols, scope int delegate(Dsymbol) dg) { assert(dg); if (symbols) { /* Do not use foreach, as the size of the array may expand during iteration */ for (size_t i = 0; i < symbols.dim; ++i) { Dsymbol s = (*symbols)[i]; const result = dg(s); if (result) return result; } } return 0; } /*************************************** * Calls dg(Dsymbol *sym) for each Dsymbol. * Params: * symbols = Dsymbols * dg = delegate to call for each Dsymbol */ void foreachDsymbol(Dsymbols* symbols, scope void delegate(Dsymbol) dg) { assert(dg); if (symbols) { /* Do not use foreach, as the size of the array may expand during iteration */ for (size_t i = 0; i < symbols.dim; ++i) { Dsymbol s = (*symbols)[i]; dg(s); } } } struct Ungag { uint oldgag; extern (D) this(uint old) { this.oldgag = old; } extern (C++) ~this() { global.gag = oldgag; } } struct Prot { /// enum Kind : int { undefined, none, // no access private_, package_, protected_, public_, export_, } Kind kind; Package pkg; extern (D) this(Prot.Kind kind) { this.kind = kind; } extern (C++): /** * Checks if `this` is superset of `other` restrictions. * For example, "protected" is more restrictive than "public". */ bool isMoreRestrictiveThan(const Prot other) const { return this.kind < other.kind; } /** * Checks if `this` is absolutely identical protection attribute to `other` */ bool opEquals(ref const Prot other) const { if (this.kind == other.kind) { if (this.kind == Prot.Kind.package_) return this.pkg == other.pkg; return true; } return false; } /** * Checks if parent defines different access restrictions than this one. * * Params: * parent = protection attribute for scope that hosts this one * * Returns: * 'true' if parent is already more restrictive than this one and thus * no differentiation is needed. */ bool isSubsetOf(ref const Prot parent) const { if (this.kind != parent.kind) return false; if (this.kind == Prot.Kind.package_) { if (!this.pkg) return true; if (!parent.pkg) return false; if (parent.pkg.isAncestorPackageOf(this.pkg)) return true; } return true; } } enum PASS : int { init, // initial state semantic, // semantic() started semanticdone, // semantic() done semantic2, // semantic2() started semantic2done, // semantic2() done semantic3, // semantic3() started semantic3done, // semantic3() done inline, // inline started inlinedone, // inline done obj, // toObjFile() run } // Search options enum : int { IgnoreNone = 0x00, // default IgnorePrivateImports = 0x01, // don't search private imports IgnoreErrors = 0x02, // don't give error messages IgnoreAmbiguous = 0x04, // return NULL if ambiguous SearchLocalsOnly = 0x08, // only look at locals (don't search imports) SearchImportsOnly = 0x10, // only look in imports SearchUnqualifiedModule = 0x20, // the module scope search is unqualified, // meaning don't search imports in that scope, // because qualified module searches search // their imports IgnoreSymbolVisibility = 0x80, // also find private and package protected symbols } extern (C++) alias Dsymbol_apply_ft_t = int function(Dsymbol, void*); /*********************************************************** */ extern (C++) class Dsymbol : ASTNode { Identifier ident; Dsymbol parent; Symbol* csym; // symbol for code generator Symbol* isym; // import version of csym const(char)* comment; // documentation comment for this Dsymbol const Loc loc; // where defined Scope* _scope; // !=null means context to use for semantic() const(char)* prettystring; // cached value of toPrettyChars() bool errors; // this symbol failed to pass semantic() PASS semanticRun = PASS.init; DeprecatedDeclaration depdecl; // customized deprecation message UserAttributeDeclaration userAttribDecl; // user defined attributes // !=null means there's a ddoc unittest associated with this symbol // (only use this with ddoc) UnitTestDeclaration ddocUnittest; final extern (D) this() { //printf("Dsymbol::Dsymbol(%p)\n", this); loc = Loc(null, 0, 0); } final extern (D) this(Identifier ident) { //printf("Dsymbol::Dsymbol(%p, ident)\n", this); this.loc = Loc(null, 0, 0); this.ident = ident; } final extern (D) this(const ref Loc loc, Identifier ident) { //printf("Dsymbol::Dsymbol(%p, ident)\n", this); this.loc = loc; this.ident = ident; } static Dsymbol create(Identifier ident) { return new Dsymbol(ident); } override const(char)* toChars() { return ident ? ident.toChars() : "__anonymous"; } // helper to print fully qualified (template) arguments const(char)* toPrettyCharsHelper() { return toChars(); } final const(Loc) getLoc() { if (!loc.isValid()) // avoid bug 5861. { auto m = getModule(); if (m && m.srcfile) { return Loc(m.srcfile.toChars(), 0, 0); } } return loc; } final const(char)* locToChars() { return getLoc().toChars(); } override bool equals(RootObject o) { if (this == o) return true; if (o.dyncast() != DYNCAST.dsymbol) return false; Dsymbol s = cast(Dsymbol)o; // Overload sets don't have an ident if (s && ident && s.ident && ident.equals(s.ident)) return true; return false; } bool isAnonymous() { return ident is null; } final void error(const ref Loc loc, const(char)* format, ...) { va_list ap; va_start(ap, format); const cstr = toPrettyChars(); const pretty = '`' ~ cstr[0 .. strlen(cstr)] ~ "`\0"; .verror(loc, format, ap, kind(), pretty.ptr); va_end(ap); } final void error(const(char)* format, ...) { va_list ap; va_start(ap, format); const cstr = toPrettyChars(); const pretty = '`' ~ cstr[0 .. strlen(cstr)] ~ "`\0"; const loc = getLoc(); .verror(loc, format, ap, kind(), pretty.ptr); va_end(ap); } final void deprecation(const ref Loc loc, const(char)* format, ...) { va_list ap; va_start(ap, format); const cstr = toPrettyChars(); const pretty = '`' ~ cstr[0 .. strlen(cstr)] ~ "`\0"; .vdeprecation(loc, format, ap, kind(), pretty.ptr); va_end(ap); } final void deprecation(const(char)* format, ...) { va_list ap; va_start(ap, format); const cstr = toPrettyChars(); const pretty = '`' ~ cstr[0 .. strlen(cstr)] ~ "`\0"; const loc = getLoc(); .vdeprecation(loc, format, ap, kind(), pretty.ptr); va_end(ap); } final bool checkDeprecated(const ref Loc loc, Scope* sc) { if (global.params.useDeprecated != DiagnosticReporting.off && isDeprecated()) { // Don't complain if we're inside a deprecated symbol's scope if (sc.isDeprecated()) return false; const(char)* message = null; for (Dsymbol p = this; p; p = p.parent) { message = p.depdecl ? p.depdecl.getMessage() : null; if (message) break; } if (message) deprecation(loc, "is deprecated - %s", message); else deprecation(loc, "is deprecated"); return true; } return false; } /********************************** * Determine which Module a Dsymbol is in. */ final Module getModule() { //printf("Dsymbol::getModule()\n"); if (TemplateInstance ti = isInstantiated()) return ti.tempdecl.getModule(); Dsymbol s = this; while (s) { //printf("\ts = %s '%s'\n", s.kind(), s.toPrettyChars()); Module m = s.isModule(); if (m) return m; s = s.parent; } return null; } /********************************** * Determine which Module a Dsymbol is in, as far as access rights go. */ final Module getAccessModule() { //printf("Dsymbol::getAccessModule()\n"); if (TemplateInstance ti = isInstantiated()) return ti.tempdecl.getAccessModule(); Dsymbol s = this; while (s) { //printf("\ts = %s '%s'\n", s.kind(), s.toPrettyChars()); Module m = s.isModule(); if (m) return m; TemplateInstance ti = s.isTemplateInstance(); if (ti && ti.enclosing) { /* Because of local template instantiation, the parent isn't where the access * rights come from - it's the template declaration */ s = ti.tempdecl; } else s = s.parent; } return null; } /** * `pastMixin` returns the enclosing symbol if this is a template mixin. * * `pastMixinAndNspace` does likewise, additionally skipping over Nspaces that * are mangleOnly. * * See also `parent`, `toParent`, `toParent2` and `toParent3`. */ final inout(Dsymbol) pastMixin() inout { //printf("Dsymbol::pastMixin() %s\n", toChars()); if (!isTemplateMixin() && !isForwardingAttribDeclaration()) return this; if (!parent) return null; return parent.pastMixin(); } /// ditto final inout(Dsymbol) pastMixinAndNspace() inout { //printf("Dsymbol::pastMixin() %s\n", toChars()); auto nspace = isNspace(); if (!(nspace && nspace.mangleOnly) && !isTemplateMixin() && !isForwardingAttribDeclaration()) return this; if (!parent) return null; return parent.pastMixinAndNspace(); } /********************************** * `parent` field returns a lexically enclosing scope symbol this is a member of. * * `toParent()` returns a logically enclosing scope symbol this is a member of. * It skips over TemplateMixin's and Nspaces that are mangleOnly. * * `toParent2()` returns an enclosing scope symbol this is living at runtime. * It skips over both TemplateInstance's and TemplateMixin's. * It's used when looking for the 'this' pointer of the enclosing function/class. * * `toParent3()` returns a logically enclosing scope symbol this is a member of. * It skips over TemplateMixin's. * * Examples: * module mod; * template Foo(alias a) { mixin Bar!(); } * mixin template Bar() { * public { // ProtDeclaration * void baz() { a = 2; } * } * } * void test() { * int v = 1; * alias foo = Foo!(v); * foo.baz(); * assert(v == 2); * } * * // s == FuncDeclaration('mod.test.Foo!().Bar!().baz()') * // s.parent == TemplateMixin('mod.test.Foo!().Bar!()') * // s.toParent() == TemplateInstance('mod.test.Foo!()') * // s.toParent2() == FuncDeclaration('mod.test') */ final inout(Dsymbol) toParent() inout { return parent ? parent.pastMixinAndNspace() : null; } /// ditto final inout(Dsymbol) toParent2() inout { if (!parent || !parent.isTemplateInstance && !parent.isForwardingAttribDeclaration()) return parent; return parent.toParent2; } /// ditto final inout(Dsymbol) toParent3() inout { return parent ? parent.pastMixin() : null; } final inout(TemplateInstance) isInstantiated() inout { if (!parent) return null; auto ti = parent.isTemplateInstance(); if (ti && !ti.isTemplateMixin()) return ti; return parent.isInstantiated(); } // Check if this function is a member of a template which has only been // instantiated speculatively, eg from inside is(typeof()). // Return the speculative template instance it is part of, // or NULL if not speculative. final inout(TemplateInstance) isSpeculative() inout { if (!parent) return null; auto ti = parent.isTemplateInstance(); if (ti && ti.gagged) return ti; if (!parent.toParent()) return null; return parent.isSpeculative(); } final Ungag ungagSpeculative() const { uint oldgag = global.gag; if (global.gag && !isSpeculative() && !toParent2().isFuncDeclaration()) global.gag = 0; return Ungag(oldgag); } // kludge for template.isSymbol() override final DYNCAST dyncast() const { return DYNCAST.dsymbol; } /************************************* * Do syntax copy of an array of Dsymbol's. */ extern (D) static Dsymbols* arraySyntaxCopy(Dsymbols* a) { Dsymbols* b = null; if (a) { b = a.copy(); for (size_t i = 0; i < b.dim; i++) { (*b)[i] = (*b)[i].syntaxCopy(null); } } return b; } Identifier getIdent() { return ident; } const(char)* toPrettyChars(bool QualifyTypes = false) { if (prettystring && !QualifyTypes) return prettystring; //printf("Dsymbol::toPrettyChars() '%s'\n", toChars()); if (!parent) { auto s = toChars(); if (!QualifyTypes) prettystring = s; return s; } // Computer number of components size_t complength = 0; for (Dsymbol p = this; p; p = p.parent) ++complength; // Allocate temporary array comp[] alias T = const(char)[]; auto compptr = cast(T*)malloc(complength * T.sizeof); if (!compptr) Mem.error(); auto comp = compptr[0 .. complength]; // Fill in comp[] and compute length of final result size_t length = 0; int i; for (Dsymbol p = this; p; p = p.parent) { const s = QualifyTypes ? p.toPrettyCharsHelper() : p.toChars(); const len = strlen(s); comp[i] = s[0 .. len]; ++i; length += len + 1; } auto s = cast(char*)mem.xmalloc(length); auto q = s + length - 1; *q = 0; foreach (j; 0 .. complength) { const t = comp[j].ptr; const len = comp[j].length; q -= len; memcpy(q, t, len); if (q == s) break; *--q = '.'; } free(comp.ptr); if (!QualifyTypes) prettystring = s; return s; } const(char)* kind() const pure nothrow @nogc @safe { return "symbol"; } /********************************* * If this symbol is really an alias for another, * return that other. * If needed, semantic() is invoked due to resolve forward reference. */ Dsymbol toAlias() { return this; } /********************************* * Resolve recursive tuple expansion in eponymous template. */ Dsymbol toAlias2() { return toAlias(); } /********************************* * Iterate this dsymbol or members of this scoped dsymbol, then * call `fp` with the found symbol and `param`. * Params: * fp = function pointer to process the iterated symbol. * If it returns nonzero, the iteration will be aborted. * param = a parameter passed to fp. * Returns: * nonzero if the iteration is aborted by the return value of fp, * or 0 if it's completed. */ int apply(Dsymbol_apply_ft_t fp, void* param) { return (*fp)(this, param); } void addMember(Scope* sc, ScopeDsymbol sds) { //printf("Dsymbol::addMember('%s')\n", toChars()); //printf("Dsymbol::addMember(this = %p, '%s' scopesym = '%s')\n", this, toChars(), sds.toChars()); //printf("Dsymbol::addMember(this = %p, '%s' sds = %p, sds.symtab = %p)\n", this, toChars(), sds, sds.symtab); parent = sds; if (!isAnonymous()) // no name, so can't add it to symbol table { if (!sds.symtabInsert(this)) // if name is already defined { Dsymbol s2 = sds.symtabLookup(this,ident); if (!s2.overloadInsert(this)) { sds.multiplyDefined(Loc.initial, this, s2); errors = true; } } if (sds.isAggregateDeclaration() || sds.isEnumDeclaration()) { if (ident == Id.__sizeof || ident == Id.__xalignof || ident == Id._mangleof) { error("`.%s` property cannot be redefined", ident.toChars()); errors = true; } } } } /************************************* * Set scope for future semantic analysis so we can * deal better with forward references. */ void setScope(Scope* sc) { //printf("Dsymbol::setScope() %p %s, %p stc = %llx\n", this, toChars(), sc, sc.stc); if (!sc.nofree) sc.setNoFree(); // may need it even after semantic() finishes _scope = sc; if (sc.depdecl) depdecl = sc.depdecl; if (!userAttribDecl) userAttribDecl = sc.userAttribDecl; } void importAll(Scope* sc) { } /********************************************* * Search for ident as member of s. * Params: * loc = location to print for error messages * ident = identifier to search for * flags = IgnoreXXXX * Returns: * null if not found */ Dsymbol search(const ref Loc loc, Identifier ident, int flags = IgnoreNone) { //printf("Dsymbol::search(this=%p,%s, ident='%s')\n", this, toChars(), ident.toChars()); return null; } final Dsymbol search_correct(Identifier ident) { /*************************************************** * Search for symbol with correct spelling. */ extern (D) void* symbol_search_fp(const(char)* seed, ref int cost) { /* If not in the lexer's string table, it certainly isn't in the symbol table. * Doing this first is a lot faster. */ size_t len = strlen(seed); if (!len) return null; Identifier id = Identifier.lookup(seed, len); if (!id) return null; cost = 0; Dsymbol s = this; Module.clearCache(); return cast(void*)s.search(Loc.initial, id, IgnoreErrors); } if (global.gag) return null; // don't do it for speculative compiles; too time consuming return cast(Dsymbol)speller(ident.toChars(), &symbol_search_fp, idchars); } /*************************************** * Search for identifier id as a member of `this`. * `id` may be a template instance. * * Params: * loc = location to print the error messages * sc = the scope where the symbol is located * id = the id of the symbol * flags = the search flags which can be `SearchLocalsOnly` or `IgnorePrivateImports` * * Returns: * symbol found, NULL if not */ final Dsymbol searchX(const ref Loc loc, Scope* sc, RootObject id, int flags) { //printf("Dsymbol::searchX(this=%p,%s, ident='%s')\n", this, toChars(), ident.toChars()); Dsymbol s = toAlias(); Dsymbol sm; if (Declaration d = s.isDeclaration()) { if (d.inuse) { .error(loc, "circular reference to `%s`", d.toPrettyChars()); return null; } } switch (id.dyncast()) { case DYNCAST.identifier: sm = s.search(loc, cast(Identifier)id, flags); break; case DYNCAST.dsymbol: { // It's a template instance //printf("\ttemplate instance id\n"); Dsymbol st = cast(Dsymbol)id; TemplateInstance ti = st.isTemplateInstance(); sm = s.search(loc, ti.name); if (!sm) { sm = s.search_correct(ti.name); if (sm) .error(loc, "template identifier `%s` is not a member of %s `%s`, did you mean %s `%s`?", ti.name.toChars(), s.kind(), s.toPrettyChars(), sm.kind(), sm.toChars()); else .error(loc, "template identifier `%s` is not a member of %s `%s`", ti.name.toChars(), s.kind(), s.toPrettyChars()); return null; } sm = sm.toAlias(); TemplateDeclaration td = sm.isTemplateDeclaration(); if (!td) { .error(loc, "`%s.%s` is not a template, it is a %s", s.toPrettyChars(), ti.name.toChars(), sm.kind()); return null; } ti.tempdecl = td; if (!ti.semanticRun) ti.dsymbolSemantic(sc); sm = ti.toAlias(); break; } case DYNCAST.type: case DYNCAST.expression: default: assert(0); } return sm; } bool overloadInsert(Dsymbol s) { //printf("Dsymbol::overloadInsert('%s')\n", s.toChars()); return false; } /********************************* * Returns: * SIZE_INVALID when the size cannot be determined */ d_uns64 size(const ref Loc loc) { error("Dsymbol `%s` has no size", toChars()); return SIZE_INVALID; } bool isforwardRef() { return false; } // is a 'this' required to access the member inout(AggregateDeclaration) isThis() inout { return null; } // is Dsymbol exported? bool isExport() const { return false; } // is Dsymbol imported? bool isImportedSymbol() const { return false; } // is Dsymbol deprecated? bool isDeprecated() { return false; } bool isOverloadable() { return false; } // is this a LabelDsymbol()? LabelDsymbol isLabel() { return null; } /// Returns an AggregateDeclaration when toParent() is that. final inout(AggregateDeclaration) isMember() inout { //printf("Dsymbol::isMember() %s\n", toChars()); auto p = toParent(); //printf("parent is %s %s\n", p.kind(), p.toChars()); return p ? p.isAggregateDeclaration() : null; } /// Returns an AggregateDeclaration when toParent2() is that. final inout(AggregateDeclaration) isMember2() inout { //printf("Dsymbol::isMember2() '%s'\n", toChars()); auto p = toParent2(); //printf("parent is %s %s\n", p.kind(), p.toChars()); return p ? p.isAggregateDeclaration() : null; } // is this a member of a ClassDeclaration? final ClassDeclaration isClassMember() { auto ad = isMember(); return ad ? ad.isClassDeclaration() : null; } // is this a type? Type getType() { return null; } // need a 'this' pointer? bool needThis() { return false; } /************************************* */ Prot prot() { return Prot(Prot.Kind.public_); } /************************************** * Copy the syntax. * Used for template instantiations. * If s is NULL, allocate the new object, otherwise fill it in. */ Dsymbol syntaxCopy(Dsymbol s) { printf("%s %s\n", kind(), toChars()); assert(0); } /************************************** * Determine if this symbol is only one. * Returns: * false, *ps = NULL: There are 2 or more symbols * true, *ps = NULL: There are zero symbols * true, *ps = symbol: The one and only one symbol */ bool oneMember(Dsymbol* ps, Identifier ident) { //printf("Dsymbol::oneMember()\n"); *ps = this; return true; } /***************************************** * Same as Dsymbol::oneMember(), but look at an array of Dsymbols. */ extern (D) static bool oneMembers(Dsymbols* members, Dsymbol* ps, Identifier ident) { //printf("Dsymbol::oneMembers() %d\n", members ? members.dim : 0); Dsymbol s = null; if (members) { for (size_t i = 0; i < members.dim; i++) { Dsymbol sx = (*members)[i]; bool x = sx.oneMember(ps, ident); //printf("\t[%d] kind %s = %d, s = %p\n", i, sx.kind(), x, *ps); if (!x) { //printf("\tfalse 1\n"); assert(*ps is null); return false; } if (*ps) { assert(ident); if (!(*ps).ident || !(*ps).ident.equals(ident)) continue; if (!s) s = *ps; else if (s.isOverloadable() && (*ps).isOverloadable()) { // keep head of overload set FuncDeclaration f1 = s.isFuncDeclaration(); FuncDeclaration f2 = (*ps).isFuncDeclaration(); if (f1 && f2) { assert(!f1.isFuncAliasDeclaration()); assert(!f2.isFuncAliasDeclaration()); for (; f1 != f2; f1 = f1.overnext0) { if (f1.overnext0 is null) { f1.overnext0 = f2; break; } } } } else // more than one symbol { *ps = null; //printf("\tfalse 2\n"); return false; } } } } *ps = s; // s is the one symbol, null if none //printf("\ttrue\n"); return true; } void setFieldOffset(AggregateDeclaration ad, uint* poffset, bool isunion) { } /***************************************** * Is Dsymbol a variable that contains pointers? */ bool hasPointers() { //printf("Dsymbol::hasPointers() %s\n", toChars()); return false; } bool hasStaticCtorOrDtor() { //printf("Dsymbol::hasStaticCtorOrDtor() %s\n", toChars()); return false; } void addLocalClass(ClassDeclarations*) { } void addObjcSymbols(ClassDeclarations* classes, ClassDeclarations* categories) { } void checkCtorConstInit() { } /**************************************** * Add documentation comment to Dsymbol. * Ignore NULL comments. */ void addComment(const(char)* comment) { //if (comment) // printf("adding comment '%s' to symbol %p '%s'\n", comment, this, toChars()); if (!this.comment) this.comment = comment; else if (comment && strcmp(cast(char*)comment, cast(char*)this.comment) != 0) { // Concatenate the two this.comment = Lexer.combineComments(this.comment, comment, true); } } /**************************************** * Returns true if this symbol is defined in a non-root module without instantiation. */ final bool inNonRoot() { Dsymbol s = parent; for (; s; s = s.toParent()) { if (auto ti = s.isTemplateInstance()) { return false; } if (auto m = s.isModule()) { if (!m.isRoot()) return true; break; } } return false; } // Eliminate need for dynamic_cast inout(Package) isPackage() inout { return null; } inout(Module) isModule() inout { return null; } inout(EnumMember) isEnumMember() inout { return null; } inout(TemplateDeclaration) isTemplateDeclaration() inout { return null; } inout(TemplateInstance) isTemplateInstance() inout { return null; } inout(TemplateMixin) isTemplateMixin() inout { return null; } inout(ForwardingAttribDeclaration) isForwardingAttribDeclaration() inout { return null; } inout(Nspace) isNspace() inout { return null; } inout(Declaration) isDeclaration() inout { return null; } inout(StorageClassDeclaration) isStorageClassDeclaration() inout { return null; } inout(ExpressionDsymbol) isExpressionDsymbol() inout { return null; } inout(ThisDeclaration) isThisDeclaration() inout { return null; } inout(TypeInfoDeclaration) isTypeInfoDeclaration() inout { return null; } inout(TupleDeclaration) isTupleDeclaration() inout { return null; } inout(AliasDeclaration) isAliasDeclaration() inout { return null; } inout(AggregateDeclaration) isAggregateDeclaration() inout pure nothrow @safe @nogc { return null; } inout(FuncDeclaration) isFuncDeclaration() inout { return null; } inout(FuncAliasDeclaration) isFuncAliasDeclaration() inout { return null; } inout(OverDeclaration) isOverDeclaration() inout { return null; } inout(FuncLiteralDeclaration) isFuncLiteralDeclaration() inout { return null; } inout(CtorDeclaration) isCtorDeclaration() inout { return null; } inout(PostBlitDeclaration) isPostBlitDeclaration() inout { return null; } inout(DtorDeclaration) isDtorDeclaration() inout { return null; } inout(StaticCtorDeclaration) isStaticCtorDeclaration() inout { return null; } inout(StaticDtorDeclaration) isStaticDtorDeclaration() inout { return null; } inout(SharedStaticCtorDeclaration) isSharedStaticCtorDeclaration() inout { return null; } inout(SharedStaticDtorDeclaration) isSharedStaticDtorDeclaration() inout { return null; } inout(InvariantDeclaration) isInvariantDeclaration() inout { return null; } inout(UnitTestDeclaration) isUnitTestDeclaration() inout { return null; } inout(NewDeclaration) isNewDeclaration() inout { return null; } inout(VarDeclaration) isVarDeclaration() inout { return null; } inout(ClassDeclaration) isClassDeclaration() inout { return null; } inout(StructDeclaration) isStructDeclaration() inout { return null; } inout(UnionDeclaration) isUnionDeclaration() inout { return null; } inout(InterfaceDeclaration) isInterfaceDeclaration() inout { return null; } inout(ScopeDsymbol) isScopeDsymbol() inout { return null; } inout(ForwardingScopeDsymbol) isForwardingScopeDsymbol() inout { return null; } inout(WithScopeSymbol) isWithScopeSymbol() inout { return null; } inout(ArrayScopeSymbol) isArrayScopeSymbol() inout { return null; } inout(Import) isImport() inout { return null; } inout(EnumDeclaration) isEnumDeclaration() inout { return null; } inout(DeleteDeclaration) isDeleteDeclaration() inout { return null; } inout(SymbolDeclaration) isSymbolDeclaration() inout { return null; } inout(AttribDeclaration) isAttribDeclaration() inout { return null; } inout(AnonDeclaration) isAnonDeclaration() inout { return null; } inout(ProtDeclaration) isProtDeclaration() inout { return null; } inout(OverloadSet) isOverloadSet() inout { return null; } /************ */ override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * Dsymbol that generates a scope */ extern (C++) class ScopeDsymbol : Dsymbol { Dsymbols* members; // all Dsymbol's in this scope DsymbolTable symtab; // members[] sorted into table uint endlinnum; // the linnumber of the statement after the scope (0 if unknown) private: /// symbols whose members have been imported, i.e. imported modules and template mixins Dsymbols* importedScopes; Prot.Kind* prots; // array of Prot.Kind, one for each import import dmd.root.array : BitArray; BitArray accessiblePackages, privateAccessiblePackages;// whitelists of accessible (imported) packages public: final extern (D) this() { } final extern (D) this(Identifier ident) { super(ident); } final extern (D) this(const ref Loc loc, Identifier ident) { super(loc, ident); } override Dsymbol syntaxCopy(Dsymbol s) { //printf("ScopeDsymbol::syntaxCopy('%s')\n", toChars()); ScopeDsymbol sds = s ? cast(ScopeDsymbol)s : new ScopeDsymbol(ident); sds.members = arraySyntaxCopy(members); sds.endlinnum = endlinnum; return sds; } /***************************************** * This function is #1 on the list of functions that eat cpu time. * Be very, very careful about slowing it down. */ override Dsymbol search(const ref Loc loc, Identifier ident, int flags = SearchLocalsOnly) { //printf("%s.ScopeDsymbol::search(ident='%s', flags=x%x)\n", toChars(), ident.toChars(), flags); //if (strcmp(ident.toChars(),"c") == 0) *(char*)0=0; // Look in symbols declared in this module if (symtab && !(flags & SearchImportsOnly)) { //printf(" look in locals\n"); auto s1 = symtab.lookup(ident); if (s1) { //printf("\tfound in locals = '%s.%s'\n",toChars(),s1.toChars()); return s1; } } //printf(" not found in locals\n"); // Look in imported scopes if (importedScopes) { //printf(" look in imports\n"); Dsymbol s = null; OverloadSet a = null; // Look in imported modules for (size_t i = 0; i < importedScopes.dim; i++) { // If private import, don't search it if ((flags & IgnorePrivateImports) && prots[i] == Prot.Kind.private_) continue; int sflags = flags & (IgnoreErrors | IgnoreAmbiguous | IgnoreSymbolVisibility); // remember these in recursive searches Dsymbol ss = (*importedScopes)[i]; //printf("\tscanning import '%s', prots = %d, isModule = %p, isImport = %p\n", ss.toChars(), prots[i], ss.isModule(), ss.isImport()); if (ss.isModule()) { if (flags & SearchLocalsOnly) continue; } else // mixin template { if (flags & SearchImportsOnly) continue; // compatibility with -transition=import // https://issues.dlang.org/show_bug.cgi?id=15925 // SearchLocalsOnly should always get set for new lookup rules if (global.params.check10378) sflags |= (flags & SearchLocalsOnly); else sflags |= SearchLocalsOnly; } /* Don't find private members if ss is a module */ Dsymbol s2 = ss.search(loc, ident, sflags | (ss.isModule() ? IgnorePrivateImports : IgnoreNone)); import dmd.access : symbolIsVisible; if (!s2 || !(flags & IgnoreSymbolVisibility) && !symbolIsVisible(this, s2)) continue; if (!s) { s = s2; if (s && s.isOverloadSet()) a = mergeOverloadSet(ident, a, s); } else if (s2 && s != s2) { if (s.toAlias() == s2.toAlias() || s.getType() == s2.getType() && s.getType()) { /* After following aliases, we found the same * symbol, so it's not an ambiguity. But if one * alias is deprecated or less accessible, prefer * the other. */ if (s.isDeprecated() || s.prot().isMoreRestrictiveThan(s2.prot()) && s2.prot().kind != Prot.Kind.none) s = s2; } else { /* Two imports of the same module should be regarded as * the same. */ Import i1 = s.isImport(); Import i2 = s2.isImport(); if (!(i1 && i2 && (i1.mod == i2.mod || (!i1.parent.isImport() && !i2.parent.isImport() && i1.ident.equals(i2.ident))))) { /* https://issues.dlang.org/show_bug.cgi?id=8668 * Public selective import adds AliasDeclaration in module. * To make an overload set, resolve aliases in here and * get actual overload roots which accessible via s and s2. */ s = s.toAlias(); s2 = s2.toAlias(); /* If both s2 and s are overloadable (though we only * need to check s once) */ if ((s2.isOverloadSet() || s2.isOverloadable()) && (a || s.isOverloadable())) { if (symbolIsVisible(this, s2)) { a = mergeOverloadSet(ident, a, s2); } if (!symbolIsVisible(this, s)) s = s2; continue; } if (flags & IgnoreAmbiguous) // if return NULL on ambiguity return null; if (!(flags & IgnoreErrors)) ScopeDsymbol.multiplyDefined(loc, s, s2); break; } } } } if (s) { /* Build special symbol if we had multiple finds */ if (a) { if (!s.isOverloadSet()) a = mergeOverloadSet(ident, a, s); s = a; } // TODO: remove once private symbol visibility has been deprecated if (!(flags & IgnoreErrors) && s.prot().kind == Prot.Kind.private_ && !s.isOverloadable() && !s.parent.isTemplateMixin() && !s.parent.isNspace()) { AliasDeclaration ad = void; // accessing private selective and renamed imports is // deprecated by restricting the symbol visibility if (s.isImport() || (ad = s.isAliasDeclaration()) !is null && ad._import !is null) {} else error(loc, "%s `%s` is `private`", s.kind(), s.toPrettyChars()); } //printf("\tfound in imports %s.%s\n", toChars(), s.toChars()); return s; } //printf(" not found in imports\n"); } return null; } final OverloadSet mergeOverloadSet(Identifier ident, OverloadSet os, Dsymbol s) { if (!os) { os = new OverloadSet(ident); os.parent = this; } if (OverloadSet os2 = s.isOverloadSet()) { // Merge the cross-module overload set 'os2' into 'os' if (os.a.dim == 0) { os.a.setDim(os2.a.dim); memcpy(os.a.tdata(), os2.a.tdata(), (os.a[0]).sizeof * os2.a.dim); } else { for (size_t i = 0; i < os2.a.dim; i++) { os = mergeOverloadSet(ident, os, os2.a[i]); } } } else { assert(s.isOverloadable()); /* Don't add to os[] if s is alias of previous sym */ for (size_t j = 0; j < os.a.dim; j++) { Dsymbol s2 = os.a[j]; if (s.toAlias() == s2.toAlias()) { if (s2.isDeprecated() || (s2.prot().isMoreRestrictiveThan(s.prot()) && s.prot().kind != Prot.Kind.none)) { os.a[j] = s; } goto Lcontinue; } } os.push(s); Lcontinue: } return os; } void importScope(Dsymbol s, Prot protection) { //printf("%s.ScopeDsymbol::importScope(%s, %d)\n", toChars(), s.toChars(), protection); // No circular or redundant import's if (s != this) { if (!importedScopes) importedScopes = new Dsymbols(); else { for (size_t i = 0; i < importedScopes.dim; i++) { Dsymbol ss = (*importedScopes)[i]; if (ss == s) // if already imported { if (protection.kind > prots[i]) prots[i] = protection.kind; // upgrade access return; } } } importedScopes.push(s); prots = cast(Prot.Kind*)mem.xrealloc(prots, importedScopes.dim * (prots[0]).sizeof); prots[importedScopes.dim - 1] = protection.kind; } } final void addAccessiblePackage(Package p, Prot protection) { // https://issues.dlang.org/show_bug.cgi?id=17991 // An import of truly empty file/package can happen if (p is null) return; auto pary = protection.kind == Prot.Kind.private_ ? &privateAccessiblePackages : &accessiblePackages; if (pary.length <= p.tag) pary.length = p.tag + 1; (*pary)[p.tag] = true; } bool isPackageAccessible(Package p, Prot protection, int flags = 0) { if (p.tag < accessiblePackages.length && accessiblePackages[p.tag] || protection.kind == Prot.Kind.private_ && p.tag < privateAccessiblePackages.length && privateAccessiblePackages[p.tag]) return true; foreach (i, ss; importedScopes ? (*importedScopes)[] : null) { // only search visible scopes && imported modules should ignore private imports if (protection.kind <= prots[i] && ss.isScopeDsymbol.isPackageAccessible(p, protection, IgnorePrivateImports)) return true; } return false; } override final bool isforwardRef() { return (members is null); } static void multiplyDefined(const ref Loc loc, Dsymbol s1, Dsymbol s2) { version (none) { printf("ScopeDsymbol::multiplyDefined()\n"); printf("s1 = %p, '%s' kind = '%s', parent = %s\n", s1, s1.toChars(), s1.kind(), s1.parent ? s1.parent.toChars() : ""); printf("s2 = %p, '%s' kind = '%s', parent = %s\n", s2, s2.toChars(), s2.kind(), s2.parent ? s2.parent.toChars() : ""); } if (loc.isValid()) { .error(loc, "`%s` at %s conflicts with `%s` at %s", s1.toPrettyChars(), s1.locToChars(), s2.toPrettyChars(), s2.locToChars()); } else { s1.error(s1.loc, "conflicts with %s `%s` at %s", s2.kind(), s2.toPrettyChars(), s2.locToChars()); } } override const(char)* kind() const { return "ScopeDsymbol"; } /******************************************* * Look for member of the form: * const(MemberInfo)[] getMembers(string); * Returns NULL if not found */ final FuncDeclaration findGetMembers() { Dsymbol s = search_function(this, Id.getmembers); FuncDeclaration fdx = s ? s.isFuncDeclaration() : null; version (none) { // Finish __gshared TypeFunction tfgetmembers; if (!tfgetmembers) { Scope sc; auto parameters = new Parameters(); Parameters* p = new Parameter(STC.in_, Type.tchar.constOf().arrayOf(), null, null); parameters.push(p); Type tret = null; tfgetmembers = new TypeFunction(parameters, tret, VarArg.none, LINK.d); tfgetmembers = cast(TypeFunction)tfgetmembers.dsymbolSemantic(Loc.initial, &sc); } if (fdx) fdx = fdx.overloadExactMatch(tfgetmembers); } if (fdx && fdx.isVirtual()) fdx = null; return fdx; } Dsymbol symtabInsert(Dsymbol s) { return symtab.insert(s); } /**************************************** * Look up identifier in symbol table. */ Dsymbol symtabLookup(Dsymbol s, Identifier id) { return symtab.lookup(id); } /**************************************** * Return true if any of the members are static ctors or static dtors, or if * any members have members that are. */ override bool hasStaticCtorOrDtor() { if (members) { for (size_t i = 0; i < members.dim; i++) { Dsymbol member = (*members)[i]; if (member.hasStaticCtorOrDtor()) return true; } } return false; } extern (D) alias ForeachDg = int delegate(size_t idx, Dsymbol s); /*************************************** * Expands attribute declarations in members in depth first * order. Calls dg(size_t symidx, Dsymbol *sym) for each * member. * If dg returns !=0, stops and returns that value else returns 0. * Use this function to avoid the O(N + N^2/2) complexity of * calculating dim and calling N times getNth. * Returns: * last value returned by dg() */ extern (D) static int _foreach(Scope* sc, Dsymbols* members, scope ForeachDg dg, size_t* pn = null) { assert(dg); if (!members) return 0; size_t n = pn ? *pn : 0; // take over index int result = 0; foreach (size_t i; 0 .. members.dim) { Dsymbol s = (*members)[i]; if (AttribDeclaration a = s.isAttribDeclaration()) result = _foreach(sc, a.include(sc), dg, &n); else if (TemplateMixin tm = s.isTemplateMixin()) result = _foreach(sc, tm.members, dg, &n); else if (s.isTemplateInstance()) { } else if (s.isUnitTestDeclaration()) { } else result = dg(n++, s); if (result) break; } if (pn) *pn = n; // update index return result; } override final inout(ScopeDsymbol) isScopeDsymbol() inout { return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * With statement scope */ extern (C++) final class WithScopeSymbol : ScopeDsymbol { WithStatement withstate; extern (D) this(WithStatement withstate) { this.withstate = withstate; } override Dsymbol search(const ref Loc loc, Identifier ident, int flags = SearchLocalsOnly) { //printf("WithScopeSymbol.search(%s)\n", ident.toChars()); if (flags & SearchImportsOnly) return null; // Acts as proxy to the with class declaration Dsymbol s = null; Expression eold = null; for (Expression e = withstate.exp; e != eold; e = resolveAliasThis(_scope, e)) { if (e.op == TOK.scope_) { s = (cast(ScopeExp)e).sds; } else if (e.op == TOK.type) { s = e.type.toDsymbol(null); } else { Type t = e.type.toBasetype(); s = t.toDsymbol(null); } if (s) { s = s.search(loc, ident, flags); if (s) return s; } eold = e; } return null; } override inout(WithScopeSymbol) isWithScopeSymbol() inout { return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * Array Index/Slice scope */ extern (C++) final class ArrayScopeSymbol : ScopeDsymbol { Expression exp; // IndexExp or SliceExp TypeTuple type; // for tuple[length] TupleDeclaration td; // for tuples of objects Scope* sc; extern (D) this(Scope* sc, Expression exp) { super(exp.loc, null); assert(exp.op == TOK.index || exp.op == TOK.slice || exp.op == TOK.array); this.exp = exp; this.sc = sc; } extern (D) this(Scope* sc, TypeTuple type) { this.type = type; this.sc = sc; } extern (D) this(Scope* sc, TupleDeclaration td) { this.td = td; this.sc = sc; } override Dsymbol search(const ref Loc loc, Identifier ident, int flags = IgnoreNone) { //printf("ArrayScopeSymbol::search('%s', flags = %d)\n", ident.toChars(), flags); if (ident == Id.dollar) { VarDeclaration* pvar; Expression ce; L1: if (td) { /* $ gives the number of elements in the tuple */ auto v = new VarDeclaration(loc, Type.tsize_t, Id.dollar, null); Expression e = new IntegerExp(Loc.initial, td.objects.dim, Type.tsize_t); v._init = new ExpInitializer(Loc.initial, e); v.storage_class |= STC.temp | STC.static_ | STC.const_; v.dsymbolSemantic(sc); return v; } if (type) { /* $ gives the number of type entries in the type tuple */ auto v = new VarDeclaration(loc, Type.tsize_t, Id.dollar, null); Expression e = new IntegerExp(Loc.initial, type.arguments.dim, Type.tsize_t); v._init = new ExpInitializer(Loc.initial, e); v.storage_class |= STC.temp | STC.static_ | STC.const_; v.dsymbolSemantic(sc); return v; } if (exp.op == TOK.index) { /* array[index] where index is some function of $ */ IndexExp ie = cast(IndexExp)exp; pvar = &ie.lengthVar; ce = ie.e1; } else if (exp.op == TOK.slice) { /* array[lwr .. upr] where lwr or upr is some function of $ */ SliceExp se = cast(SliceExp)exp; pvar = &se.lengthVar; ce = se.e1; } else if (exp.op == TOK.array) { /* array[e0, e1, e2, e3] where e0, e1, e2 are some function of $ * $ is a opDollar!(dim)() where dim is the dimension(0,1,2,...) */ ArrayExp ae = cast(ArrayExp)exp; pvar = &ae.lengthVar; ce = ae.e1; } else { /* Didn't find $, look in enclosing scope(s). */ return null; } while (ce.op == TOK.comma) ce = (cast(CommaExp)ce).e2; /* If we are indexing into an array that is really a type * tuple, rewrite this as an index into a type tuple and * try again. */ if (ce.op == TOK.type) { Type t = (cast(TypeExp)ce).type; if (t.ty == Ttuple) { type = cast(TypeTuple)t; goto L1; } } /* *pvar is lazily initialized, so if we refer to $ * multiple times, it gets set only once. */ if (!*pvar) // if not already initialized { /* Create variable v and set it to the value of $ */ VarDeclaration v; Type t; if (ce.op == TOK.tuple) { /* It is for an expression tuple, so the * length will be a const. */ Expression e = new IntegerExp(Loc.initial, (cast(TupleExp)ce).exps.dim, Type.tsize_t); v = new VarDeclaration(loc, Type.tsize_t, Id.dollar, new ExpInitializer(Loc.initial, e)); v.storage_class |= STC.temp | STC.static_ | STC.const_; } else if (ce.type && (t = ce.type.toBasetype()) !is null && (t.ty == Tstruct || t.ty == Tclass)) { // Look for opDollar assert(exp.op == TOK.array || exp.op == TOK.slice); AggregateDeclaration ad = isAggregate(t); assert(ad); Dsymbol s = ad.search(loc, Id.opDollar); if (!s) // no dollar exists -- search in higher scope return null; s = s.toAlias(); Expression e = null; // Check for multi-dimensional opDollar(dim) template. if (TemplateDeclaration td = s.isTemplateDeclaration()) { dinteger_t dim = 0; if (exp.op == TOK.array) { dim = (cast(ArrayExp)exp).currentDimension; } else if (exp.op == TOK.slice) { dim = 0; // slices are currently always one-dimensional } else { assert(0); } auto tiargs = new Objects(); Expression edim = new IntegerExp(Loc.initial, dim, Type.tsize_t); edim = edim.expressionSemantic(sc); tiargs.push(edim); e = new DotTemplateInstanceExp(loc, ce, td.ident, tiargs); } else { /* opDollar exists, but it's not a template. * This is acceptable ONLY for single-dimension indexing. * Note that it's impossible to have both template & function opDollar, * because both take no arguments. */ if (exp.op == TOK.array && (cast(ArrayExp)exp).arguments.dim != 1) { exp.error("`%s` only defines opDollar for one dimension", ad.toChars()); return null; } Declaration d = s.isDeclaration(); assert(d); e = new DotVarExp(loc, ce, d); } e = e.expressionSemantic(sc); if (!e.type) exp.error("`%s` has no value", e.toChars()); t = e.type.toBasetype(); if (t && t.ty == Tfunction) e = new CallExp(e.loc, e); v = new VarDeclaration(loc, null, Id.dollar, new ExpInitializer(Loc.initial, e)); v.storage_class |= STC.temp | STC.ctfe | STC.rvalue; } else { /* For arrays, $ will either be a compile-time constant * (in which case its value in set during constant-folding), * or a variable (in which case an expression is created in * toir.c). */ auto e = new VoidInitializer(Loc.initial); e.type = Type.tsize_t; v = new VarDeclaration(loc, Type.tsize_t, Id.dollar, e); v.storage_class |= STC.temp | STC.ctfe; // it's never a true static variable } *pvar = v; } (*pvar).dsymbolSemantic(sc); return (*pvar); } return null; } override inout(ArrayScopeSymbol) isArrayScopeSymbol() inout { return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * Overload Sets */ extern (C++) final class OverloadSet : Dsymbol { Dsymbols a; // array of Dsymbols extern (D) this(Identifier ident, OverloadSet os = null) { super(ident); if (os) { a.pushSlice(os.a[]); } } void push(Dsymbol s) { a.push(s); } override inout(OverloadSet) isOverloadSet() inout { return this; } override const(char)* kind() const { return "overloadset"; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * Forwarding ScopeDsymbol. Used by ForwardingAttribDeclaration and * ForwardingScopeDeclaration to forward symbol insertions to another * scope. See `dmd.attrib.ForwardingAttribDeclaration` for more * details. */ extern (C++) final class ForwardingScopeDsymbol : ScopeDsymbol { /************************* * Symbol to forward insertions to. * Can be `null` before being lazily initialized. */ ScopeDsymbol forward; extern (D) this(ScopeDsymbol forward) { super(null); this.forward = forward; } override Dsymbol symtabInsert(Dsymbol s) { assert(forward); if (auto d = s.isDeclaration()) { if (d.storage_class & STC.local) { // Symbols with storage class STC.local are not // forwarded, but stored in the local symbol // table. (Those are the `static foreach` variables.) if (!symtab) { symtab = new DsymbolTable(); } return super.symtabInsert(s); // insert locally } } if (!forward.symtab) { forward.symtab = new DsymbolTable(); } // Non-STC.local symbols are forwarded to `forward`. return forward.symtabInsert(s); } /************************ * This override handles the following two cases: * static foreach (i, i; [0]) { ... } * and * static foreach (i; [0]) { enum i = 2; } */ override Dsymbol symtabLookup(Dsymbol s, Identifier id) { assert(forward); // correctly diagnose clashing foreach loop variables. if (auto d = s.isDeclaration()) { if (d.storage_class & STC.local) { if (!symtab) { symtab = new DsymbolTable(); } return super.symtabLookup(s,id); } } // Declarations within `static foreach` do not clash with // `static foreach` loop variables. if (!forward.symtab) { forward.symtab = new DsymbolTable(); } return forward.symtabLookup(s,id); } override void importScope(Dsymbol s, Prot protection) { forward.importScope(s, protection); } override const(char)* kind()const{ return "local scope"; } override inout(ForwardingScopeDsymbol) isForwardingScopeDsymbol() inout { return this; } } /** * Class that holds an expression in a Dsymbol wraper. * This is not an AST node, but a class used to pass * an expression as a function parameter of type Dsymbol. */ extern (C++) final class ExpressionDsymbol : Dsymbol { Expression exp; this(Expression exp) { super(); this.exp = exp; } override inout(ExpressionDsymbol) isExpressionDsymbol() inout { return this; } } /*********************************************************** * Table of Dsymbol's */ extern (C++) final class DsymbolTable : RootObject { AssocArray!(Identifier, Dsymbol) tab; // Look up Identifier. Return Dsymbol if found, NULL if not. Dsymbol lookup(const Identifier ident) { //printf("DsymbolTable::lookup(%s)\n", ident.toChars()); return tab[ident]; } // Insert Dsymbol in table. Return NULL if already there. Dsymbol insert(Dsymbol s) { //printf("DsymbolTable::insert(this = %p, '%s')\n", this, s.ident.toChars()); return insert(s.ident, s); } // Look for Dsymbol in table. If there, return it. If not, insert s and return that. Dsymbol update(Dsymbol s) { const ident = s.ident; Dsymbol* ps = tab.getLvalue(ident); *ps = s; return s; } // when ident and s are not the same Dsymbol insert(const Identifier ident, Dsymbol s) { //printf("DsymbolTable::insert()\n"); Dsymbol* ps = tab.getLvalue(ident); if (*ps) return null; // already in table *ps = s; return s; } /***** * Returns: * number of symbols in symbol table */ uint len() const pure { return cast(uint)tab.length; } }
D
// EXTRA_SOURCES: imports/test45a.d imports/test45b.d // PERMUTE_ARGS: import imports.test45a; import imports.test45b; alias int function() fp1; alias int function(int) fp2; void main() { auto i = foo(); assert(i == 1); i = foo(1); assert(i == 2); i = foo; assert(i == 1); fp1 fp = &foo; i = (*fp)(); assert(i == 1); fp2 fpi = &foo; i = (*fpi)(1); assert(i == 2); i = bar(1); assert(i == 3); i = bar(1, 2); assert(i == 4); }
D
/** MongoCollection class Copyright: © 2012-2016 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 vibe.db.mongo.collection; public import vibe.db.mongo.cursor; public import vibe.db.mongo.connection; public import vibe.db.mongo.flags; import vibe.core.log; import vibe.db.mongo.client; import core.time; import std.algorithm : countUntil, find; import std.array; import std.conv; import std.exception; import std.string; import std.typecons : Tuple, tuple; /** Represents a single collection inside a MongoDB. All methods take arbitrary types for Bson arguments. serializeToBson() is implicitly called on them before they are send to the database. The following example shows some possible ways to specify objects. */ struct MongoCollection { private { MongoClient m_client; MongoDatabase m_db; string m_name; string m_fullPath; } this(MongoClient client, string fullPath) { assert(client !is null); m_client = client; auto dotidx = fullPath.indexOf('.'); assert(dotidx > 0, "The collection name passed to MongoCollection must be of the form \"dbname.collectionname\"."); m_fullPath = fullPath; m_db = m_client.getDatabase(fullPath[0 .. dotidx]); m_name = fullPath[dotidx+1 .. $]; } this(ref MongoDatabase db, string name) { assert(db.client !is null); m_client = db.client; m_fullPath = db.name ~ "." ~ name; m_db = db; m_name = name; } /** Returns: Root database to which this collection belongs. */ @property MongoDatabase database() { return m_db; } /** Returns: Name of this collection (excluding the database name). */ @property string name() const { return m_name; } /** Performs an update operation on documents matching 'selector', updating them with 'update'. Throws: Exception if a DB communication error occured. See_Also: $(LINK http://www.mongodb.org/display/DOCS/Updating) */ void update(T, U)(T selector, U update, UpdateFlags flags = UpdateFlags.None) { assert(m_client !is null, "Updating uninitialized MongoCollection."); auto conn = m_client.lockConnection(); ubyte[256] selector_buf = void, update_buf = void; conn.update(m_fullPath, flags, serializeToBson(selector, selector_buf), serializeToBson(update, update_buf)); } /** Inserts new documents into the collection. Note that if the `_id` field of the document(s) is not set, typically using `BsonObjectID.generate()`, the server will generate IDs automatically. If you need to know the IDs of the inserted documents, you need to generate them locally. Throws: Exception if a DB communication error occured. See_Also: $(LINK http://www.mongodb.org/display/DOCS/Inserting) */ void insert(T)(T document_or_documents, InsertFlags flags = InsertFlags.None) { assert(m_client !is null, "Inserting into uninitialized MongoCollection."); auto conn = m_client.lockConnection(); Bson[] docs; Bson bdocs = serializeToBson(document_or_documents); if( bdocs.type == Bson.Type.Array ) docs = cast(Bson[])bdocs; else docs = (&bdocs)[0 .. 1]; conn.insert(m_fullPath, flags, docs); } /** Queries the collection for existing documents. If no arguments are passed to find(), all documents of the collection will be returned. See_Also: $(LINK http://www.mongodb.org/display/DOCS/Querying) */ MongoCursor!(T, R, U) find(R = Bson, T, U)(T query, U returnFieldSelector, QueryFlags flags = QueryFlags.None, int num_skip = 0, int num_docs_per_chunk = 0) { assert(m_client !is null, "Querying uninitialized MongoCollection."); return MongoCursor!(T, R, U)(m_client, m_fullPath, flags, num_skip, num_docs_per_chunk, query, returnFieldSelector); } /// ditto MongoCursor!(T, R, typeof(null)) find(R = Bson, T)(T query) { return find!R(query, null); } /// ditto MongoCursor!(Bson, R, typeof(null)) find(R = Bson)() { return find!R(Bson.emptyObject, null); } /** Queries the collection for existing documents. Returns: By default, a Bson value of the matching document is returned, or $(D Bson(null)) when no document matched. For types R that are not Bson, the returned value is either of type $(D R), or of type $(Nullable!R), if $(D R) is not a reference/pointer type. Throws: Exception if a DB communication error or a query error occured. See_Also: $(LINK http://www.mongodb.org/display/DOCS/Querying) */ auto findOne(R = Bson, T, U)(T query, U returnFieldSelector, QueryFlags flags = QueryFlags.None) { import std.traits; import std.typecons; auto c = find!R(query, returnFieldSelector, flags, 0, 1); static if (is(R == Bson)) { foreach (doc; c) return doc; return Bson(null); } else static if (is(R == class) || isPointer!R || isDynamicArray!R || isAssociativeArray!R) { foreach (doc; c) return doc; return null; } else { foreach (doc; c) { Nullable!R ret; ret = doc; return ret; } return Nullable!R.init; } } /// ditto auto findOne(R = Bson, T)(T query) { return findOne!R(query, Bson(null)); } /** Removes documents from the collection. Throws: Exception if a DB communication error occured. See_Also: $(LINK http://www.mongodb.org/display/DOCS/Removing) */ void remove(T)(T selector, DeleteFlags flags = DeleteFlags.None) { assert(m_client !is null, "Removnig from uninitialized MongoCollection."); auto conn = m_client.lockConnection(); ubyte[256] selector_buf = void; conn.delete_(m_fullPath, flags, serializeToBson(selector, selector_buf)); } /// ditto void remove()() { remove(Bson.emptyObject); } /** Combines a modify and find operation to a single atomic operation. Params: query = MongoDB query expression to identify the matched document update = Update expression for the matched document returnFieldSelector = Optional map of fields to return in the response Throws: An `Exception` will be thrown if an error occurs in the communication with the database server. See_Also: $(LINK http://docs.mongodb.org/manual/reference/command/findAndModify) */ Bson findAndModify(T, U, V)(T query, U update, V returnFieldSelector) { static struct CMD { string findAndModify; T query; U update; V fields; } CMD cmd; cmd.findAndModify = m_name; cmd.query = query; cmd.update = update; cmd.fields = returnFieldSelector; auto ret = database.runCommand(cmd); if( !ret["ok"].get!double ) throw new Exception("findAndModify failed."); return ret["value"]; } /// ditto Bson findAndModify(T, U)(T query, U update) { return findAndModify(query, update, null); } /** Combines a modify and find operation to a single atomic operation with generic options support. Params: query = MongoDB query expression to identify the matched document update = Update expression for the matched document options = Generic BSON object that contains additional options fields, such as `"new": true` Throws: An `Exception` will be thrown if an error occurs in the communication with the database server. See_Also: $(LINK http://docs.mongodb.org/manual/reference/command/findAndModify) */ Bson findAndModifyExt(T, U, V)(T query, U update, V options) { auto bopt = serializeToBson(options); assert(bopt.type == Bson.Type.object, "The options parameter to findAndModifyExt must be a BSON object."); Bson cmd = Bson.emptyObject; cmd["findAndModify"] = m_name; cmd["query"] = serializeToBson(query); cmd["update"] = serializeToBson(update); foreach (string key, value; bopt) cmd[key] = value; auto ret = database.runCommand(cmd); enforce(ret["ok"].get!double != 0, "findAndModifyExt failed."); return ret["value"]; } /// unittest { import vibe.db.mongo.mongo; void test() { auto coll = connectMongoDB("127.0.0.1").getCollection("test"); coll.findAndModifyExt(["name": "foo"], ["$set": ["value": "bar"]], ["new": true]); } } /** Counts the results of the specified query expression. Throws Exception if a DB communication error occured. See_Also: $(LINK http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-{{count%28%29}}) */ ulong count(T)(T query) { static struct Empty {} static struct CMD { string count; T query; Empty fields; } CMD cmd; cmd.count = m_name; cmd.query = query; auto reply = database.runCommand(cmd); enforce(reply["ok"].opt!double == 1 || reply["ok"].opt!int == 1, "Count command failed."); switch (reply["n"].type) with (Bson.Type) { default: assert(false, "Unsupported data type in BSON reply for COUNT"); case double_: return cast(ulong)reply["n"].get!double; // v2.x case int_: return reply["n"].get!int; // v3.x case long_: return reply["n"].get!long; // just in case } } /** Calculates aggregate values for the data in a collection. Params: pipeline = A sequence of data aggregation processes. These can either be given as separate parameters, or as a single array parameter. Returns: An array of documents returned by the pipeline Throws: Exception if a DB communication error occured See_Also: $(LINK http://docs.mongodb.org/manual/reference/method/db.collection.aggregate) */ Bson aggregate(ARGS...)(ARGS pipeline) { import std.traits; static if (ARGS.length == 1 && isArray!(ARGS[0])) alias Pipeline = ARGS[0]; else static struct Pipeline { ARGS args; } static struct CMD { string aggregate; @asArray Pipeline pipeline; } CMD cmd; cmd.aggregate = m_name; static if (ARGS.length == 1 && isArray!(ARGS[0])) cmd.pipeline = pipeline[0]; else cmd.pipeline.args = pipeline; auto ret = database.runCommand(cmd); enforce(ret["ok"].get!double == 1, "Aggregate command failed."); return ret["result"]; } /// Example taken from the MongoDB documentation unittest { import vibe.db.mongo.mongo; void test() { auto db = connectMongoDB("127.0.0.1").getDatabase("test"); auto results = db["coll"].aggregate( ["$match": ["status": "A"]], ["$group": ["_id": Bson("$cust_id"), "total": Bson(["$sum": Bson("$amount")])]], ["$sort": ["total": -1]]); } } /// The same example, but using an array of arguments unittest { import vibe.db.mongo.mongo; void test() { auto db = connectMongoDB("127.0.0.1").getDatabase("test"); Bson[] args; args ~= serializeToBson(["$match": ["status": "A"]]); args ~= serializeToBson(["$group": ["_id": Bson("$cust_id"), "total": Bson(["$sum": Bson("$amount")])]]); args ~= serializeToBson(["$sort": ["total": -1]]); auto results = db["coll"].aggregate(args); } } /** Returns an input range of all unique values for a certain field for records matching the given query. Params: key = Name of the field for which to collect unique values query = The query used to select records Returns: An input range with items of type `R` (`Bson` by default) is returned. */ auto distinct(R = Bson, Q)(string key, Q query) { import std.algorithm : map; static struct CMD { string distinct; string key; Q query; } CMD cmd; cmd.distinct = m_name; cmd.key = key; cmd.query = query; auto res = m_db.runCommand(cmd); enforce(res["ok"].get!double != 0, "Distinct query failed: "~res["errmsg"].opt!string); // TODO: avoid dynamic array allocation static if (is(R == Bson)) return res["values"].get!(Bson[]); else return res["values"].get!(Bson[]).map!(b => deserializeBson!R(b)); } /// unittest { import std.algorithm : equal; import vibe.db.mongo.mongo; void test() { auto db = connectMongoDB("127.0.0.1").getDatabase("test"); auto coll = db["collection"]; coll.drop(); coll.insert(["a": "first", "b": "foo"]); coll.insert(["a": "first", "b": "bar"]); coll.insert(["a": "first", "b": "bar"]); coll.insert(["a": "second", "b": "baz"]); coll.insert(["a": "second", "b": "bam"]); auto result = coll.distinct!string("b", ["a": "first"]); assert(result.equal(["foo", "bar"])); } } /** Creates or updates an index. Note that the overload taking an associative array of field orders will be removed. Since the order of fields matters, it is only suitable for single-field indices. */ void ensureIndex(scope const(Tuple!(string, int))[] field_orders, IndexFlags flags = IndexFlags.None, Duration expire_time = 0.seconds) { // TODO: support 2d indexes auto key = Bson.emptyObject; auto indexname = appender!string(); bool first = true; foreach (fo; field_orders) { if (!first) indexname.put('_'); else first = false; indexname.put(fo[0]); indexname.put('_'); indexname.put(to!string(fo[1])); key[fo[0]] = Bson(fo[1]); } Bson[string] doc; doc["v"] = 1; doc["key"] = key; doc["ns"] = m_fullPath; doc["name"] = indexname.data; if (flags & IndexFlags.Unique) doc["unique"] = true; if (flags & IndexFlags.DropDuplicates) doc["dropDups"] = true; if (flags & IndexFlags.Background) doc["background"] = true; if (flags & IndexFlags.Sparse) doc["sparse"] = true; if (flags & IndexFlags.ExpireAfterSeconds) doc["expireAfterSeconds"] = expire_time.total!"seconds"; database["system.indexes"].insert(doc); } /// ditto deprecated("Use the overload taking an array of field_orders instead.") void ensureIndex(int[string] field_orders, IndexFlags flags = IndexFlags.None, ulong expireAfterSeconds = 0) { Tuple!(string, int)[] orders; foreach (k, v; field_orders) orders ~= tuple(k, v); ensureIndex(orders, flags, expireAfterSeconds.seconds); } void dropIndex(string name) { static struct CMD { string dropIndexes; string index; } CMD cmd; cmd.dropIndexes = m_name; cmd.index = name; auto reply = database.runCommand(cmd); enforce(reply["ok"].get!double == 1, "dropIndex command failed."); } void drop() { static struct CMD { string drop; } CMD cmd; cmd.drop = m_name; auto reply = database.runCommand(cmd); enforce(reply["ok"].get!double == 1, "drop command failed."); } } /// unittest { import vibe.data.bson; import vibe.data.json; import vibe.db.mongo.mongo; void test() { MongoClient client = connectMongoDB("127.0.0.1"); MongoCollection users = client.getCollection("myapp.users"); // canonical version using a Bson object users.insert(Bson(["name": Bson("admin"), "password": Bson("secret")])); // short version using a string[string] AA that is automatically // serialized to Bson users.insert(["name": "admin", "password": "secret"]); // BSON specific types are also serialized automatically auto uid = BsonObjectID.fromString("507f1f77bcf86cd799439011"); Bson usr = users.findOne(["_id": uid]); // JSON is another possibility Json jusr = parseJsonString(`{"name": "admin", "password": "secret"}`); users.insert(jusr); } } /// Using the type system to define a document "schema" unittest { import vibe.db.mongo.mongo; import vibe.data.serialization : name; import std.typecons : Nullable; // Nested object within a "User" document struct Address { string name; string street; int zipCode; } // The document structure of the "myapp.users" collection struct User { @name("_id") BsonObjectID id; // represented as "_id" in the database string loginName; string password; Address address; } void test() { MongoClient client = connectMongoDB("127.0.0.1"); MongoCollection users = client.getCollection("myapp.users"); // D values are automatically serialized to the internal BSON format // upon insertion - see also vibe.data.serialization User usr; usr.id = BsonObjectID.generate(); usr.loginName = "admin"; usr.password = "secret"; users.insert(usr); // find supports direct de-serialization of the returned documents foreach (usr; users.find!User()) { logInfo("User: %s", usr.loginName); } // the same goes for findOne Nullable!User qusr = users.findOne!User(["_id": usr.id]); if (!qusr.isNull) logInfo("User: %s", qusr.loginName); } } enum IndexFlags { None = 0, Unique = 1<<0, DropDuplicates = 1<<2, Background = 1<<3, Sparse = 1<<4, ExpireAfterSeconds = 1<<5 }
D
module gtkD.gdk.Device; public import gtkD.gtkc.gdktypes; private import gtkD.gtkc.gdk; private import gtkD.glib.ConstructionException; private import gtkD.glib.ListG; private import gtkD.gdk.Window; /** * Description * In addition to the normal keyboard and mouse input devices, GTK+ also * contains support for extended input devices. In * particular, this support is targeted at graphics tablets. Graphics * tablets typically return sub-pixel positioning information and possibly * information about the pressure and tilt of the stylus. Under * X, the support for extended devices is done through the * XInput extension. * Because handling extended input devices may involve considerable * overhead, they need to be turned on for each GdkWindow * individually using gdk_input_set_extension_events(). * (Or, more typically, for GtkWidgets, using gtk_widget_set_extension_events()). * As an additional complication, depending on the support from * the windowing system, its possible that a normal mouse * cursor will not be displayed for a particular extension * device. If an application does not want to deal with displaying * a cursor itself, it can ask only to get extension events * from devices that will display a cursor, by passing the * GDK_EXTENSION_EVENTS_CURSOR value to * gdk_input_set_extension_events(). Otherwise, the application * must retrieve the device information using gdk_devices_list(), * check the has_cursor field, and, * if it is FALSE, draw a cursor itself when it receives * motion events. * Each pointing device is assigned a unique integer ID; events from a * particular device can be identified by the * deviceid field in the event structure. The * events generated by pointer devices have also been extended to contain * pressure, xtilt * and ytilt fields which contain the extended * information reported as additional valuators * from the device. The pressure field is a * a double value ranging from 0.0 to 1.0, while the tilt fields are * double values ranging from -1.0 to 1.0. (With -1.0 representing the * maximum tilt to the left or up, and 1.0 representing the maximum * tilt to the right or down.) * One additional field in each event is the * source field, which contains an * enumeration value describing the type of device; this currently * can be one of GDK_SOURCE_MOUSE, GDK_SOURCE_PEN, GDK_SOURCE_ERASER, * or GDK_SOURCE_CURSOR. This field is present to allow simple * applications to (for instance) delete when they detect eraser * devices without having to keep track of complicated per-device * settings. * Various aspects of each device may be configured. The easiest way of * creating a GUI to allow the user to configure such a device * is to use the GtkInputDialog widget in GTK+. * However, even when using this widget, application writers * will need to directly query and set the configuration parameters * in order to save the state between invocations of the application. * The configuration of devices is queried using gdk_devices_list(). * Each device must be activated using gdk_device_set_mode(), which * also controls whether the device's range is mapped to the * entire screen or to a single window. The mapping of the valuators of * the device onto the predefined valuator types is set using * gdk_device_set_axis_use(). And the source type for each device * can be set with gdk_device_set_source(). * Devices may also have associated keys * or macro buttons. Such keys can be globally set to map * into normal X keyboard events. The mapping is set using * gdk_device_set_key(). * The interfaces in this section will most likely be considerably * modified in the future to accomodate devices that may have different * sets of additional valuators than the pressure xtilt * and ytilt. */ public class Device { /** the main Gtk struct */ protected GdkDevice* gdkDevice; public GdkDevice* getDeviceStruct(); /** the main Gtk struct as a void* */ protected void* getStruct(); /** * Sets our main struct and passes it to the parent class */ public this (GdkDevice* gdkDevice); /** * Obtains the motion history for a device; given a starting and * ending timestamp, return all events in the motion history for * the device in the given range of time. Some windowing systems * do not support motion history, in which case, FALSE will * be returned. (This is not distinguishable from the case where * motion history is supported and no events were found.) * Params: * window = the window with respect to which which the event coordinates will be reported * start = starting timestamp for range of events to return * stop = ending timestamp for the range of events to return * events = location to store a newly-allocated array of GdkTimeCoord, or NULL * Returns: TRUE if the windowing system supports motion history and at least one event was found. */ public int getHistory(Window window, uint start, uint stop, out GdkTimeCoord*[] events); /** */ /** * Returns the list of available input devices for the default display. * The list is statically allocated and should not be freed. * Returns: a list of GdkDevice */ public static ListG gdkDevicesList(); /** * Sets the source type for an input device. * Params: * source = the source type. */ public void setSource(GdkInputSource source); /** * Sets a the mode of an input device. The mode controls if the * device is active and whether the device's range is mapped to the * entire screen or to a single window. * Params: * mode = the input mode. * Returns:%TRUE if the mode was successfully changed. */ public int setMode(GdkInputMode mode); /** * Specifies the X key event to generate when a macro button of a device * is pressed. * Params: * index = the index of the macro button to set. * keyval = the keyval to generate. * modifiers = the modifiers to set. */ public void setKey(uint index, uint keyval, GdkModifierType modifiers); /** * Specifies how an axis of a device is used. * Params: * index = the index of the axis. * use = specifies how the axis is used. */ public void setAxisUse(uint index, GdkAxisUse use); /** * Returns the core pointer device for the default display. * Returns: the core pointer device; this is owned by the display and should not be freed. */ public static Device getCorePointer(); /** * Gets the current state of a device. * Params: * window = a GdkWindow. * axes = an array of doubles to store the values of the axes of device in, * or NULL. * mask = location to store the modifiers, or NULL. */ public void getState(Window window, double[] axes, out GdkModifierType mask); /** * Frees an array of GdkTimeCoord that was returned by gdk_device_get_history(). * Params: * events = an array of GdkTimeCoord. */ public static void freeHistory(GdkTimeCoord*[] events); /** * Interprets an array of double as axis values for a given device, * and locates the value in the array for a given axis use. * Params: * axes = pointer to an array of axes * use = the use to look for * value = location to store the found value. * Returns: TRUE if the given axis use was found, otherwise FALSE */ public int getAxis(double[] axes, GdkAxisUse use, out double value); /** * Turns extension events on or off for a particular window, * and specifies the event mask for extension events. * Params: * window = a GdkWindow. * mask = the event mask * mode = the type of extension events that are desired. */ public static void gdkInputSetExtensionEvents(Window window, int mask, GdkExtensionMode mode); }
D
/** * Defines a `Dsymbol` representing an aggregate, which is a `struct`, `union` or `class`. * * Specification: $(LINK2 https://dlang.org/spec/struct.html, Structs, Unions), * $(LINK2 https://dlang.org/spec/class.html, Class). * * 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/aggregate.d, _aggregate.d) * Documentation: https://dlang.org/phobos/dmd_aggregate.html * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/aggregate.d */ module dmd.aggregate; import core.stdc.stdio; import core.checkedint; import dmd.aliasthis; import dmd.arraytypes; import dmd.astenums; import dmd.attrib; import dmd.declaration; import dmd.dscope; import dmd.dstruct; import dmd.dsymbol; import dmd.dsymbolsem; import dmd.dtemplate; import dmd.errors; import dmd.expression; import dmd.func; import dmd.globals; import dmd.id; import dmd.identifier; import dmd.location; import dmd.mtype; import dmd.tokens; import dmd.typesem : defaultInit; import dmd.visitor; /** * The ClassKind enum is used in AggregateDeclaration AST nodes to * specify the linkage type of the struct/class/interface or if it * is an anonymous class. If the class is anonymous it is also * considered to be a D class. */ enum ClassKind : ubyte { /// the aggregate is a d(efault) class d, /// the aggregate is a C++ struct/class/interface cpp, /// the aggregate is an Objective-C class/interface objc, /// the aggregate is a C struct c, } /** * Give a nice string for a class kind for error messages * Params: * c = class kind * Returns: * 0-terminated string for `c` */ const(char)* toChars(ClassKind c) { final switch (c) { case ClassKind.d: return "D"; case ClassKind.cpp: return "C++"; case ClassKind.objc: return "Objective-C"; case ClassKind.c: return "C"; } } /** * If an aggregate has a pargma(mangle, ...) this holds the information * to mangle. */ struct MangleOverride { Dsymbol agg; // The symbol to copy template parameters from (if any) Identifier id; // the name to override the aggregate's with, defaults to agg.ident } /*********************************************************** * Abstract aggregate as a common ancestor for Class- and StructDeclaration. */ extern (C++) abstract class AggregateDeclaration : ScopeDsymbol { Type type; /// StorageClass storage_class; /// uint structsize; /// size of struct uint alignsize; /// size of struct for alignment purposes VarDeclarations fields; /// VarDeclaration fields Dsymbol deferred; /// any deferred semantic2() or semantic3() symbol /// specifies whether this is a D, C++, Objective-C or anonymous struct/class/interface ClassKind classKind; /// Specify whether to mangle the aggregate as a `class` or a `struct` /// This information is used by the MSVC mangler /// Only valid for class and struct. TODO: Merge with ClassKind ? CPPMANGLE cppmangle; /// overridden symbol with pragma(mangle, "...") if not null MangleOverride* pMangleOverride; /** * !=null if is nested * pointing to the dsymbol that directly enclosing it. * 1. The function that enclosing it (nested struct and class) * 2. The class that enclosing it (nested class only) * 3. If enclosing aggregate is template, its enclosing dsymbol. * * See AggregateDeclaraton::makeNested for the details. */ Dsymbol enclosing; VarDeclaration vthis; /// 'this' parameter if this aggregate is nested VarDeclaration vthis2; /// 'this' parameter if this aggregate is a template and is nested // Special member functions FuncDeclarations invs; /// Array of invariants FuncDeclaration inv; /// Merged invariant calling all members of invs /// CtorDeclaration or TemplateDeclaration Dsymbol ctor; /// default constructor - should have no arguments, because /// it would be stored in TypeInfo_Class.defaultConstructor CtorDeclaration defaultCtor; AliasThis aliasthis; /// forward unresolved lookups to aliasthis DtorDeclarations userDtors; /// user-defined destructors (`~this()`) - mixins can yield multiple ones DtorDeclaration aggrDtor; /// aggregate destructor calling userDtors and fieldDtor (and base class aggregate dtor for C++ classes) DtorDeclaration dtor; /// the aggregate destructor exposed as `__xdtor` alias /// (same as aggrDtor, except for C++ classes with virtual dtor on Windows) DtorDeclaration tidtor; /// aggregate destructor used in TypeInfo (must have extern(D) ABI) DtorDeclaration fieldDtor; /// function destructing (non-inherited) fields Expression getRTInfo; /// pointer to GC info generated by object.RTInfo(this) /// Visibility visibility; bool noDefaultCtor; /// no default construction bool disableNew; /// disallow allocations using `new` Sizeok sizeok = Sizeok.none; /// set when structsize contains valid data final extern (D) this(const ref Loc loc, Identifier id) { super(loc, id); visibility = Visibility(Visibility.Kind.public_); } /*************************************** * Create a new scope from sc. * semantic, semantic2 and semantic3 will use this for aggregate members. */ Scope* newScope(Scope* sc) { auto sc2 = sc.push(this); sc2.stc &= STC.flowThruAggregate; sc2.parent = this; sc2.inunion = isUnionDeclaration(); sc2.visibility = Visibility(Visibility.Kind.public_); sc2.explicitVisibility = 0; sc2.aligndecl = null; sc2.userAttribDecl = null; sc2.namespace = null; return sc2; } override final void setScope(Scope* sc) { // Might need a scope to resolve forward references. The check for // semanticRun prevents unnecessary setting of _scope during deferred // setScope phases for aggregates which already finished semantic(). // See https://issues.dlang.org/show_bug.cgi?id=16607 if (semanticRun < PASS.semanticdone) ScopeDsymbol.setScope(sc); } /*************************************** * Returns: * The total number of fields minus the number of hidden fields. */ final size_t nonHiddenFields() { return fields.length - isNested() - (vthis2 !is null); } /*************************************** * Collect all instance fields, then determine instance size. * Returns: * false if failed to determine the size. */ final bool determineSize(const ref Loc loc) { //printf("AggregateDeclaration::determineSize() %s, sizeok = %d\n", toChars(), sizeok); // The previous instance size finalizing had: if (type.ty == Terror || errors) return false; // failed already if (sizeok == Sizeok.done) return true; // succeeded if (!members) { error(loc, "unknown size"); return false; } if (_scope) dsymbolSemantic(this, null); // Determine the instance size of base class first. if (auto cd = isClassDeclaration()) { cd = cd.baseClass; if (cd && !cd.determineSize(loc)) goto Lfail; } // Determine instance fields when sizeok == Sizeok.none if (!this.determineFields()) goto Lfail; if (sizeok != Sizeok.done) finalizeSize(); // this aggregate type has: if (type.ty == Terror) return false; // marked as invalid during the finalizing. if (sizeok == Sizeok.done) return true; // succeeded to calculate instance size. Lfail: // There's unresolvable forward reference. if (type != Type.terror) error(loc, "no size because of forward reference"); // Don't cache errors from speculative semantic, might be resolvable later. // https://issues.dlang.org/show_bug.cgi?id=16574 if (!global.gag) { type = Type.terror; errors = true; } return false; } abstract void finalizeSize(); override final uinteger_t size(const ref Loc loc) { //printf("+AggregateDeclaration::size() %s, scope = %p, sizeok = %d\n", toChars(), _scope, sizeok); bool ok = determineSize(loc); //printf("-AggregateDeclaration::size() %s, scope = %p, sizeok = %d\n", toChars(), _scope, sizeok); return ok ? structsize : SIZE_INVALID; } /*************************************** * Calculate field[i].overlapped and overlapUnsafe, and check that all of explicit * field initializers have unique memory space on instance. * Returns: * true if any errors happen. */ extern (D) final bool checkOverlappedFields() { //printf("AggregateDeclaration::checkOverlappedFields() %s\n", toChars()); assert(sizeok == Sizeok.done); size_t nfields = fields.length; if (isNested()) { auto cd = isClassDeclaration(); if (!cd || !cd.baseClass || !cd.baseClass.isNested()) nfields--; if (vthis2 && !(cd && cd.baseClass && cd.baseClass.vthis2)) nfields--; } bool errors = false; // Fill in missing any elements with default initializers foreach (i; 0 .. nfields) { auto vd = fields[i]; if (vd.errors) { errors = true; continue; } const vdIsVoidInit = vd._init && vd._init.isVoidInitializer(); // Find overlapped fields with the hole [vd.offset .. vd.offset.size()]. foreach (j; 0 .. nfields) { if (i == j) continue; auto v2 = fields[j]; if (v2.errors) { errors = true; continue; } if (!vd.isOverlappedWith(v2)) continue; // vd and v2 are overlapping. vd.overlapped = true; v2.overlapped = true; if (!MODimplicitConv(vd.type.mod, v2.type.mod)) v2.overlapUnsafe = true; if (!MODimplicitConv(v2.type.mod, vd.type.mod)) vd.overlapUnsafe = true; if (i > j) continue; if (!v2._init) continue; if (v2._init.isVoidInitializer()) continue; if (vd._init && !vdIsVoidInit && v2._init) { .error(loc, "overlapping default initialization for field `%s` and `%s`", v2.toChars(), vd.toChars()); errors = true; } else if (v2._init && i < j) { .error(v2.loc, "union field `%s` with default initialization `%s` must be before field `%s`", v2.toChars(), v2._init.toChars(), vd.toChars()); errors = true; } } } return errors; } /*************************************** * Fill out remainder of elements[] with default initializers for fields[]. * Params: * loc = location * elements = explicit arguments which given to construct object. * ctorinit = true if the elements will be used for default initialization. * Returns: * false if any errors occur. * Otherwise, returns true and the missing arguments will be pushed in elements[]. */ final bool fill(const ref Loc loc, ref Expressions elements, bool ctorinit) { //printf("AggregateDeclaration::fill() %s\n", toChars()); assert(sizeok == Sizeok.done); const nfields = nonHiddenFields(); bool errors = false; size_t dim = elements.length; elements.setDim(nfields); foreach (size_t i; dim .. nfields) elements[i] = null; // Fill in missing any elements with default initializers foreach (i; 0 .. nfields) { if (elements[i]) continue; auto vd = fields[i]; auto vx = vd; if (vd._init && vd._init.isVoidInitializer()) vx = null; // Find overlapped fields with the hole [vd.offset .. vd.offset.size()]. size_t fieldi = i; foreach (j; 0 .. nfields) { if (i == j) continue; auto v2 = fields[j]; if (!vd.isOverlappedWith(v2)) continue; if (elements[j]) { vx = null; break; } if (v2._init && v2._init.isVoidInitializer()) continue; version (all) { /* Prefer first found non-void-initialized field * union U { int a; int b = 2; } * U u; // Error: overlapping initialization for field a and b */ if (!vx) { vx = v2; fieldi = j; } else if (v2._init) { .error(loc, "overlapping initialization for field `%s` and `%s`", v2.toChars(), vd.toChars()); errors = true; } } else { // fixes https://issues.dlang.org/show_bug.cgi?id=1432 by enabling this path always /* Prefer explicitly initialized field * union U { int a; int b = 2; } * U u; // OK (u.b == 2) */ if (!vx || !vx._init && v2._init) { vx = v2; fieldi = j; } else if (vx != vd && !vx.isOverlappedWith(v2)) { // Both vx and v2 fills vd, but vx and v2 does not overlap } else if (vx._init && v2._init) { .error(loc, "overlapping default initialization for field `%s` and `%s`", v2.toChars(), vd.toChars()); errors = true; } else assert(vx._init || !vx._init && !v2._init); } } if (vx) { Expression e; if (vx.type.size() == 0) { e = null; } else if (vx._init) { assert(!vx._init.isVoidInitializer()); if (vx.inuse) // https://issues.dlang.org/show_bug.cgi?id=18057 { vx.error(loc, "recursive initialization of field"); errors = true; } else e = vx.getConstInitializer(false); } else { if ((vx.storage_class & STC.nodefaultctor) && !ctorinit) { .error(loc, "field `%s.%s` must be initialized because it has no default constructor", type.toChars(), vx.toChars()); errors = true; } /* https://issues.dlang.org/show_bug.cgi?id=12509 * Get the element of static array type. */ Type telem = vx.type; if (telem.ty == Tsarray) { /* We cannot use Type::baseElemOf() here. * If the bottom of the Tsarray is an enum type, baseElemOf() * will return the base of the enum, and its default initializer * would be different from the enum's. */ TypeSArray tsa; while ((tsa = telem.toBasetype().isTypeSArray()) !is null) telem = tsa.next; if (telem.ty == Tvoid) telem = Type.tuns8.addMod(telem.mod); } if (telem.needsNested() && ctorinit) e = telem.defaultInit(loc); else e = telem.defaultInitLiteral(loc); } elements[fieldi] = e; } } foreach (e; elements) { if (e && e.op == EXP.error) return false; } return !errors; } /**************************** * Do byte or word alignment as necessary. * Align sizes of 0, as we may not know array sizes yet. * Params: * alignment = struct alignment that is in effect * memalignsize = natural alignment of field * poffset = pointer to offset to be aligned */ extern (D) static void alignmember(structalign_t alignment, uint memalignsize, uint* poffset) pure nothrow @safe { //debug printf("alignment = %u %d, size = %u, offset = %u\n", alignment.get(), alignment.isPack(), memalignsize, *poffset); uint alignvalue; if (alignment.isDefault()) { // Alignment in Target::fieldalignsize must match what the // corresponding C compiler's default alignment behavior is. alignvalue = memalignsize; } else if (alignment.isPack()) // #pragma pack semantics { alignvalue = alignment.get(); if (memalignsize < alignvalue) alignvalue = memalignsize; // align to min(memalignsize, alignment) } else if (alignment.get() > 1) { // Align on alignment boundary, which must be a positive power of 2 alignvalue = alignment.get(); } else return; assert(alignvalue > 0 && !(alignvalue & (alignvalue - 1))); *poffset = (*poffset + alignvalue - 1) & ~(alignvalue - 1); } /**************************************** * Place a field (mem) into an aggregate (agg), which can be a struct, union or class * Params: * nextoffset = location just past the end of the previous field in the aggregate. * Updated to be just past the end of this field to be placed, i.e. the future nextoffset * memsize = size of field * memalignsize = natural alignment of field * alignment = alignment in effect for this field * paggsize = size of aggregate (updated) * paggalignsize = alignment of aggregate (updated) * isunion = the aggregate is a union * Returns: * aligned offset to place field at * */ extern (D) static uint placeField(uint* nextoffset, uint memsize, uint memalignsize, structalign_t alignment, uint* paggsize, uint* paggalignsize, bool isunion) { uint ofs = *nextoffset; const uint actualAlignment = alignment.isDefault() || alignment.isPack() && memalignsize < alignment.get() ? memalignsize : alignment.get(); // Ensure no overflow bool overflow; const sz = addu(memsize, actualAlignment, overflow); addu(ofs, sz, overflow); if (overflow) assert(0); // Skip no-op for noreturn without custom aligment if (memalignsize != 0 || !alignment.isDefault()) alignmember(alignment, memalignsize, &ofs); uint memoffset = ofs; ofs += memsize; if (ofs > *paggsize) *paggsize = ofs; if (!isunion) *nextoffset = ofs; if (*paggalignsize < actualAlignment) *paggalignsize = actualAlignment; return memoffset; } override final Type getType() { /* Apply storage classes to forward references. (Issue 22254) * Note: Avoid interfaces for now. Implementing qualifiers on interface * definitions exposed some issues in their TypeInfo generation in DMD. * Related PR: https://github.com/dlang/dmd/pull/13312 */ if (semanticRun == PASS.initial && !isInterfaceDeclaration()) { auto stc = storage_class; if (_scope) stc |= _scope.stc; type = type.addSTC(stc); } return type; } // is aggregate deprecated? override final bool isDeprecated() const { return !!(this.storage_class & STC.deprecated_); } /// Flag this aggregate as deprecated final void setDeprecated() { this.storage_class |= STC.deprecated_; } /**************************************** * Returns true if there's an extra member which is the 'this' * pointer to the enclosing context (enclosing aggregate or function) */ final bool isNested() const { return enclosing !is null; } /* Append vthis field (this.tupleof[$-1]) to make this aggregate type nested. */ extern (D) final void makeNested() { if (enclosing) // if already nested return; if (sizeok == Sizeok.done) return; if (isUnionDeclaration() || isInterfaceDeclaration()) return; if (storage_class & STC.static_) return; // If nested struct, add in hidden 'this' pointer to outer scope auto s = toParentLocal(); if (!s) s = toParent2(); if (!s) return; Type t = null; if (auto fd = s.isFuncDeclaration()) { enclosing = fd; /* https://issues.dlang.org/show_bug.cgi?id=14422 * If a nested class parent is a function, its * context pointer (== `outer`) should be void* always. */ t = Type.tvoidptr; } else if (auto ad = s.isAggregateDeclaration()) { if (isClassDeclaration() && ad.isClassDeclaration()) { enclosing = ad; } else if (isStructDeclaration()) { if (auto ti = ad.parent.isTemplateInstance()) { enclosing = ti.enclosing; } } t = ad.handleType(); } if (enclosing) { //printf("makeNested %s, enclosing = %s\n", toChars(), enclosing.toChars()); assert(t); if (t.ty == Tstruct) t = Type.tvoidptr; // t should not be a ref type assert(!vthis); vthis = new ThisDeclaration(loc, t); //vthis.storage_class |= STC.ref_; // Emulate vthis.addMember() members.push(vthis); // Emulate vthis.dsymbolSemantic() vthis.storage_class |= STC.field; vthis.parent = this; vthis.visibility = Visibility(Visibility.Kind.public_); vthis.alignment = t.alignment(); vthis.semanticRun = PASS.semanticdone; if (sizeok == Sizeok.fwd) fields.push(vthis); makeNested2(); } } /* Append vthis2 field (this.tupleof[$-1]) to add a second context pointer. */ extern (D) final void makeNested2() { if (vthis2) return; if (!vthis) makeNested(); // can't add second before first if (!vthis) return; if (sizeok == Sizeok.done) return; if (isUnionDeclaration() || isInterfaceDeclaration()) return; if (storage_class & STC.static_) return; auto s0 = toParentLocal(); auto s = toParent2(); if (!s || !s0 || s == s0) return; auto cd = s.isClassDeclaration(); Type t = cd ? cd.type : Type.tvoidptr; vthis2 = new ThisDeclaration(loc, t); //vthis2.storage_class |= STC.ref_; // Emulate vthis2.addMember() members.push(vthis2); // Emulate vthis2.dsymbolSemantic() vthis2.storage_class |= STC.field; vthis2.parent = this; vthis2.visibility = Visibility(Visibility.Kind.public_); vthis2.alignment = t.alignment(); vthis2.semanticRun = PASS.semanticdone; if (sizeok == Sizeok.fwd) fields.push(vthis2); } override final bool isExport() const { return visibility.kind == Visibility.Kind.export_; } /******************************************* * Look for constructor declaration. */ final Dsymbol searchCtor() { auto s = search(Loc.initial, Id.ctor); if (s) { if (!(s.isCtorDeclaration() || s.isTemplateDeclaration() || s.isOverloadSet())) { s.error("is not a constructor; identifiers starting with `__` are reserved for the implementation"); errors = true; s = null; } } if (s && s.toParent() != this) s = null; // search() looks through ancestor classes if (s) { // Finish all constructors semantics to determine this.noDefaultCtor. static int searchCtor(Dsymbol s, void*) { auto f = s.isCtorDeclaration(); if (f && f.semanticRun == PASS.initial) f.dsymbolSemantic(null); return 0; } for (size_t i = 0; i < members.length; i++) { auto sm = (*members)[i]; sm.apply(&searchCtor, null); } } return s; } override final Visibility visible() pure nothrow @nogc @safe { return visibility; } // 'this' type final Type handleType() { return type; } // Does this class have an invariant function? final bool hasInvariant() { return invs.length != 0; } // Back end void* sinit; /// initializer symbol override final inout(AggregateDeclaration) isAggregateDeclaration() inout { return this; } override void accept(Visitor v) { v.visit(this); } } /********************************* * Iterate this dsymbol or members of this scoped dsymbol, then * call `fp` with the found symbol and `params`. * Params: * symbol = the dsymbol or parent of members to call fp on * fp = function pointer to process the iterated symbol. * If it returns nonzero, the iteration will be aborted. * ctx = context parameter passed to fp. * Returns: * nonzero if the iteration is aborted by the return value of fp, * or 0 if it's completed. */ int apply(Dsymbol symbol, int function(Dsymbol, void*) fp, void* ctx) { if (auto nd = symbol.isNspace()) { return nd.members.foreachDsymbol( (s) { return s && s.apply(fp, ctx); } ); } if (auto ad = symbol.isAttribDeclaration()) { return ad.include(ad._scope).foreachDsymbol( (s) { return s && s.apply(fp, ctx); } ); } if (auto tm = symbol.isTemplateMixin()) { if (tm._scope) // if fwd reference dsymbolSemantic(tm, null); // try to resolve it return tm.members.foreachDsymbol( (s) { return s && s.apply(fp, ctx); } ); } return fp(symbol, ctx); }
D
import std.algorithm; import std.conv; import std.datetime; import std.format; import std.range; import std.stdio; import std.string; import std.socket; import std.uni; import core.thread; import dfio; import http.parser.core; string dayAsString(DayOfWeek day) { final switch(day) with(DayOfWeek) { case mon: return "Mon"; case tue: return "Tue"; case wed: return "Wed"; case thu: return "Thu"; case fri: return "Fri"; case sat: return "Sat"; case sun: return "Sun"; } } string monthAsString(Month month){ final switch(month) with (Month) { case jan: return "Jan"; case feb: return "Feb"; case mar: return "Mar"; case apr: return "Apr"; case may: return "May"; case jun: return "Jun"; case jul: return "Jul"; case aug: return "Aug"; case sep: return "Sep"; case oct: return "Oct"; case nov: return "Nov"; case dec: return "Dec"; } } void writeDate(Output, D)(ref Output sink, D date){ string weekDay = dayAsString(date.dayOfWeek); string month = monthAsString(date.month); formattedWrite(sink, "Date: %s, %02s %s %04s %02s:%02s:%02s GMT\r\n", weekDay, date.day, month, date.year, date.hour, date.minute, date.second ); } void server_worker(Socket client) { ubyte[1024] buffer; scope(exit) { client.shutdown(SocketShutdown.BOTH); client.close(); } auto outBuf = appender!(char[]); auto bodyBuf = appender!(char[]); bool keepAlive = false; logf("Started server_worker, client = %s", client); scope parser = new HttpParser(); bool reading = true; int connection = -1; parser.onMessageComplete = (parser) { reading = false; }; parser.onHeader = (parser, HttpHeader header) { logf("Parser Header <%s> with value <%s>", header.name, header.value); if (sicmp(header.name, "connection") == 0) if (sicmp(header.value,"close") == 0) connection = 0; else connection = 1; }; do { reading = true; while(reading){ ptrdiff_t received = client.receive(buffer); if (received < 0) { logf("Error %d", received); perror("Error while reading from client"); return; } else if (received == 0) { //socket is closed (eof) connection = 0; reading = false; } else { logf("Server_worker received:\n<%s>", cast(char[])buffer[0.. received]); parser.execute(buffer[0..received]); } } HttpVersion v = parser.protocolVersion(); // if no connection header present, keep connection for 1.1 if (connection == 1) keepAlive = true; else if (connection < 0 && v.major == 1 && v.minor == 1) keepAlive = true; else keepAlive = false; logf("Protocol version = %s", v); outBuf.clear(); bodyBuf.clear(); formattedWrite(bodyBuf, "Hello, world!"); auto date = Clock.currTime!(ClockType.coarse)(UTC()); formattedWrite(outBuf, "HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: %d\r\n", bodyBuf.data.length ); writeDate(outBuf, date); if (keepAlive) { logf("Keep-alive request"); formattedWrite(outBuf, "Connection: keep-alive\r\n\r\n"); } else { logf("Non keep-alive request"); formattedWrite(outBuf, "\r\n"); } copy(bodyBuf.data, outBuf); logf("Sent <%s>", cast(char[])outBuf.data); client.send(outBuf.data); } while(keepAlive); } void server() { Socket server = new TcpSocket(); server.setOption(SocketOptionLevel.SOCKET, SocketOption.REUSEADDR, true); server.bind(new InternetAddress("0.0.0.0", 8080)); server.listen(1000); logf("Started server"); void processClient(Socket client) { spawn(() => server_worker(client)); } while(true) { try { logf("Waiting for server.accept()"); Socket client = server.accept(); logf("New client accepted %s", client); processClient(client); } catch(Exception e) { writefln("Failure to accept %s", e); } } } void main() { version(Windows) GC.disable(); // temporary for Win64 UMS threading startloop(); spawn(() => server()); runFibers(); }
D
instance Mod_1328_PSINOV_Novize_MT (Npc_Default) { //-------- primary data -------- name = Name_Novize; Npctype = Npctype_mt_sumpfnovize; guild = GIL_out; level = 3; voice = 0; id = 1328; //-------- abilities -------- attribute[ATR_STRENGTH] = 10; attribute[ATR_DEXTERITY] = 10; attribute[ATR_MANA_MAX] = 0; attribute[ATR_MANA] = 0; attribute[ATR_HITPOINTS_MAX] = 76; attribute[ATR_HITPOINTS] = 76; //-------- visuals -------- // animations Mdl_SetVisual (self,"HUMANS.MDS"); Mdl_ApplyOverlayMds (self,"Humans_Relaxed.mds"); // body mesh ,bdytex,skin,head mesh ,headtex,teethtex,ruestung Mdl_SetVisualBody (self,"hum_body_Naked0", 1, 1 ,"Hum_Head_FatBald", 31 , 1, NOV_ARMOR_L); Mdl_SetModelFatness(self,0); fight_tactic = FAI_HUMAN_COWARD; //-------- Talente -------- //-------- inventory -------- //-------------Daily Routine------------- daily_routine = Rtn_start_1328; //------------- //MISSIONs------------------ }; FUNC VOID Rtn_start_1328 () { TA_Sleep (23,50,08,10,"PSI_12_HUT_IN_BED3"); TA_Listen (08,10,23,50,"PSI_12_HUT_EX"); }; FUNC VOID Rtn_Tot_1328 () { TA_Stand_WP (08,00,20,00,"TOT"); TA_Stand_WP (20,00,08,00,"TOT"); };
D
/** * The thread module provides support for thread creation and management. * * Copyright: Copyright Sean Kelly 2005 - 2012. * License: Distributed under the * $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0). * (See accompanying file LICENSE) * Authors: Sean Kelly, Walter Bright, Alex Rønne Petersen, Martin Nowak * Source: $(DRUNTIMESRC core/_thread.d) */ module core.thread; public import core.time; // for Duration import core.exception : onOutOfMemoryError; version (OSX) version = Darwin; else version (iOS) version = Darwin; else version (TVOS) version = Darwin; else version (WatchOS) version = Darwin; private { // interface to rt.tlsgc import core.internal.traits : externDFunc; alias rt_tlsgc_init = externDFunc!("rt.tlsgc.init", void* function() nothrow @nogc); alias rt_tlsgc_destroy = externDFunc!("rt.tlsgc.destroy", void function(void*) nothrow @nogc); alias ScanDg = void delegate(void* pstart, void* pend) nothrow; alias rt_tlsgc_scan = externDFunc!("rt.tlsgc.scan", void function(void*, scope ScanDg) nothrow); alias rt_tlsgc_processGCMarks = externDFunc!("rt.tlsgc.processGCMarks", void function(void*, scope IsMarkedDg) nothrow); } version( Solaris ) { import core.sys.solaris.sys.priocntl; import core.sys.solaris.sys.types; } // this should be true for most architectures version = StackGrowsDown; /** * Returns the process ID of the calling process, which is guaranteed to be * unique on the system. This call is always successful. * * Example: * --- * writefln("Current process id: %s", getpid()); * --- */ version(Posix) { alias core.sys.posix.unistd.getpid getpid; } else version (Windows) { alias core.sys.windows.windows.GetCurrentProcessId getpid; } /////////////////////////////////////////////////////////////////////////////// // Thread and Fiber Exceptions /////////////////////////////////////////////////////////////////////////////// /** * Base class for thread exceptions. */ class ThreadException : Exception { @safe pure nothrow this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null) { super(msg, file, line, next); } @safe pure nothrow this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__) { super(msg, file, line, next); } } /** * Base class for thread errors to be used for function inside GC when allocations are unavailable. */ class ThreadError : Error { @safe pure nothrow this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null) { super(msg, file, line, next); } @safe pure nothrow this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__) { super(msg, file, line, next); } } private { import core.atomic, core.memory, core.sync.mutex; // // exposed by compiler runtime // extern (C) void rt_moduleTlsCtor(); extern (C) void rt_moduleTlsDtor(); /** * Hook for whatever EH implementation is used to save/restore some data * per stack. * * Params: * newContext = The return value of the prior call to this function * where the stack was last swapped out, or null when a fiber stack * is switched in for the first time. */ extern(C) void* _d_eh_swapContext(void* newContext) nothrow @nogc; version (DigitalMars) { version (Windows) alias _d_eh_swapContext swapContext; else { extern(C) void* _d_eh_swapContextDwarf(void* newContext) nothrow @nogc; void* swapContext(void* newContext) nothrow @nogc { /* Detect at runtime which scheme is being used. * Eventually, determine it statically. */ static int which = 0; final switch (which) { case 0: { assert(newContext == null); auto p = _d_eh_swapContext(newContext); auto pdwarf = _d_eh_swapContextDwarf(newContext); if (p) { which = 1; return p; } else if (pdwarf) { which = 2; return pdwarf; } return null; } case 1: return _d_eh_swapContext(newContext); case 2: return _d_eh_swapContextDwarf(newContext); } } } } else alias _d_eh_swapContext swapContext; } /////////////////////////////////////////////////////////////////////////////// // Thread Entry Point and Signal Handlers /////////////////////////////////////////////////////////////////////////////// version( Windows ) { private { import core.stdc.stdint : uintptr_t; // for _beginthreadex decl below import core.stdc.stdlib; // for malloc, atexit import core.sys.windows.windows; import core.sys.windows.threadaux; // for OpenThreadHandle extern (Windows) alias uint function(void*) btex_fptr; extern (C) uintptr_t _beginthreadex(void*, uint, btex_fptr, void*, uint, uint*) nothrow; // // Entry point for Windows threads // extern (Windows) uint thread_entryPoint( void* arg ) nothrow { Thread obj = cast(Thread) arg; assert( obj ); assert( obj.m_curr is &obj.m_main ); obj.m_main.bstack = getStackBottom(); obj.m_main.tstack = obj.m_main.bstack; obj.m_tlsgcdata = rt_tlsgc_init(); Thread.setThis(obj); Thread.add(obj); scope (exit) { Thread.remove(obj); } Thread.add(&obj.m_main); // NOTE: No GC allocations may occur until the stack pointers have // been set and Thread.getThis returns a valid reference to // this thread object (this latter condition is not strictly // necessary on Windows but it should be followed for the // sake of consistency). // TODO: Consider putting an auto exception object here (using // alloca) forOutOfMemoryError plus something to track // whether an exception is in-flight? void append( Throwable t ) { if( obj.m_unhandled is null ) obj.m_unhandled = t; else { Throwable last = obj.m_unhandled; while( last.next !is null ) last = last.next; last.next = t; } } version( D_InlineAsm_X86 ) { asm nothrow @nogc { fninit; } } try { rt_moduleTlsCtor(); try { obj.run(); } catch( Throwable t ) { append( t ); } rt_moduleTlsDtor(); } catch( Throwable t ) { append( t ); } return 0; } HANDLE GetCurrentThreadHandle() nothrow @nogc { const uint DUPLICATE_SAME_ACCESS = 0x00000002; HANDLE curr = GetCurrentThread(), proc = GetCurrentProcess(), hndl; DuplicateHandle( proc, curr, proc, &hndl, 0, TRUE, DUPLICATE_SAME_ACCESS ); return hndl; } } } else version( Posix ) { private { import core.stdc.errno; import core.sys.posix.semaphore; import core.sys.posix.stdlib; // for malloc, valloc, free, atexit import core.sys.posix.pthread; import core.sys.posix.signal; import core.sys.posix.time; version( Darwin ) { import core.sys.darwin.mach.thread_act; import core.sys.darwin.pthread : pthread_mach_thread_np; } version( GNU ) { import gcc.builtins; } // // Entry point for POSIX threads // extern (C) void* thread_entryPoint( void* arg ) nothrow { version (Shared) { import rt.sections; Thread obj = cast(Thread)(cast(void**)arg)[0]; auto loadedLibraries = (cast(void**)arg)[1]; .free(arg); } else { Thread obj = cast(Thread)arg; } assert( obj ); // loadedLibraries need to be inherited from parent thread // before initilizing GC for TLS (rt_tlsgc_init) version (Shared) inheritLoadedLibraries(loadedLibraries); assert( obj.m_curr is &obj.m_main ); obj.m_main.bstack = getStackBottom(); obj.m_main.tstack = obj.m_main.bstack; obj.m_tlsgcdata = rt_tlsgc_init(); atomicStore!(MemoryOrder.raw)(obj.m_isRunning, true); Thread.setThis(obj); // allocates lazy TLS (see Issue 11981) Thread.add(obj); // can only receive signals from here on scope (exit) { Thread.remove(obj); atomicStore!(MemoryOrder.raw)(obj.m_isRunning, false); } Thread.add(&obj.m_main); static extern (C) void thread_cleanupHandler( void* arg ) nothrow @nogc { Thread obj = cast(Thread) arg; assert( obj ); // NOTE: If the thread terminated abnormally, just set it as // not running and let thread_suspendAll remove it from // the thread list. This is safer and is consistent // with the Windows thread code. atomicStore!(MemoryOrder.raw)(obj.m_isRunning,false); } // NOTE: Using void to skip the initialization here relies on // knowledge of how pthread_cleanup is implemented. It may // not be appropriate for all platforms. However, it does // avoid the need to link the pthread module. If any // implementation actually requires default initialization // then pthread_cleanup should be restructured to maintain // the current lack of a link dependency. static if( __traits( compiles, pthread_cleanup ) ) { pthread_cleanup cleanup = void; cleanup.push( &thread_cleanupHandler, cast(void*) obj ); } else static if( __traits( compiles, pthread_cleanup_push ) ) { pthread_cleanup_push( &thread_cleanupHandler, cast(void*) obj ); } else { static assert( false, "Platform not supported." ); } // NOTE: No GC allocations may occur until the stack pointers have // been set and Thread.getThis returns a valid reference to // this thread object (this latter condition is not strictly // necessary on Windows but it should be followed for the // sake of consistency). // TODO: Consider putting an auto exception object here (using // alloca) forOutOfMemoryError plus something to track // whether an exception is in-flight? void append( Throwable t ) { if( obj.m_unhandled is null ) obj.m_unhandled = t; else { Throwable last = obj.m_unhandled; while( last.next !is null ) last = last.next; last.next = t; } } try { rt_moduleTlsCtor(); try { obj.run(); } catch( Throwable t ) { append( t ); } rt_moduleTlsDtor(); version (Shared) cleanupLoadedLibraries(); } catch( Throwable t ) { append( t ); } // NOTE: Normal cleanup is handled by scope(exit). static if( __traits( compiles, pthread_cleanup ) ) { cleanup.pop( 0 ); } else static if( __traits( compiles, pthread_cleanup_push ) ) { pthread_cleanup_pop( 0 ); } return null; } // // Used to track the number of suspended threads // __gshared sem_t suspendCount; extern (C) void thread_suspendHandler( int sig ) nothrow in { assert( sig == suspendSignalNumber ); } body { void op(void* sp) nothrow { // NOTE: Since registers are being pushed and popped from the // stack, any other stack data used by this function should // be gone before the stack cleanup code is called below. Thread obj = Thread.getThis(); assert(obj !is null); if( !obj.m_lock ) { obj.m_curr.tstack = getStackTop(); } sigset_t sigres = void; int status; status = sigfillset( &sigres ); assert( status == 0 ); status = sigdelset( &sigres, resumeSignalNumber ); assert( status == 0 ); version (FreeBSD) obj.m_suspendagain = false; status = sem_post( &suspendCount ); assert( status == 0 ); sigsuspend( &sigres ); if( !obj.m_lock ) { obj.m_curr.tstack = obj.m_curr.bstack; } } // avoid deadlocks on FreeBSD, see Issue 13416 version (FreeBSD) { auto obj = Thread.getThis(); if (THR_IN_CRITICAL(obj.m_addr)) { obj.m_suspendagain = true; if (sem_post(&suspendCount)) assert(0); return; } } callWithStackShell(&op); } extern (C) void thread_resumeHandler( int sig ) nothrow in { assert( sig == resumeSignalNumber ); } body { } // HACK libthr internal (thr_private.h) macro, used to // avoid deadlocks in signal handler, see Issue 13416 version (FreeBSD) bool THR_IN_CRITICAL(pthread_t p) nothrow @nogc { import core.sys.posix.config : c_long; import core.sys.posix.sys.types : lwpid_t; // If the begin of pthread would be changed in libthr (unlikely) // we'll run into undefined behavior, compare with thr_private.h. static struct pthread { c_long tid; static struct umutex { lwpid_t owner; uint flags; uint[2] ceilings; uint[4] spare; } umutex lock; uint cycle; int locklevel; int critical_count; // ... } auto priv = cast(pthread*)p; return priv.locklevel > 0 || priv.critical_count > 0; } } } else { // NOTE: This is the only place threading versions are checked. If a new // version is added, the module code will need to be searched for // places where version-specific code may be required. This can be // easily accomlished by searching for 'Windows' or 'Posix'. static assert( false, "Unknown threading implementation." ); } /////////////////////////////////////////////////////////////////////////////// // Thread /////////////////////////////////////////////////////////////////////////////// /** * This class encapsulates all threading functionality for the D * programming language. As thread manipulation is a required facility * for garbage collection, all user threads should derive from this * class, and instances of this class should never be explicitly deleted. * A new thread may be created using either derivation or composition, as * in the following example. */ class Thread { /////////////////////////////////////////////////////////////////////////// // Initialization /////////////////////////////////////////////////////////////////////////// /** * Initializes a thread object which is associated with a static * D function. * * Params: * fn = The thread function. * sz = The stack size for this thread. * * In: * fn must not be null. */ this( void function() fn, size_t sz = 0 ) @safe pure nothrow @nogc in { assert( fn ); } body { this(sz); () @trusted { m_fn = fn; }(); m_call = Call.FN; m_curr = &m_main; } /** * Initializes a thread object which is associated with a dynamic * D function. * * Params: * dg = The thread function. * sz = The stack size for this thread. * * In: * dg must not be null. */ this( void delegate() dg, size_t sz = 0 ) @safe pure nothrow @nogc in { assert( dg ); } body { this(sz); () @trusted { m_dg = dg; }(); m_call = Call.DG; m_curr = &m_main; } /** * Cleans up any remaining resources used by this object. */ ~this() nothrow @nogc { if( m_addr == m_addr.init ) { return; } version( Windows ) { m_addr = m_addr.init; CloseHandle( m_hndl ); m_hndl = m_hndl.init; } else version( Posix ) { pthread_detach( m_addr ); m_addr = m_addr.init; } version( Darwin ) { m_tmach = m_tmach.init; } rt_tlsgc_destroy( m_tlsgcdata ); m_tlsgcdata = null; } /////////////////////////////////////////////////////////////////////////// // General Actions /////////////////////////////////////////////////////////////////////////// /** * Starts the thread and invokes the function or delegate passed upon * construction. * * In: * This routine may only be called once per thread instance. * * Throws: * ThreadException if the thread fails to start. */ final Thread start() nothrow in { assert( !next && !prev ); } body { auto wasThreaded = multiThreadedFlag; multiThreadedFlag = true; scope( failure ) { if( !wasThreaded ) multiThreadedFlag = false; } version( Windows ) {} else version( Posix ) { pthread_attr_t attr; if( pthread_attr_init( &attr ) ) onThreadError( "Error initializing thread attributes" ); if( m_sz && pthread_attr_setstacksize( &attr, m_sz ) ) onThreadError( "Error initializing thread stack size" ); } version( Windows ) { // NOTE: If a thread is just executing DllMain() // while another thread is started here, it holds an OS internal // lock that serializes DllMain with CreateThread. As the code // might request a synchronization on slock (e.g. in thread_findByAddr()), // we cannot hold that lock while creating the thread without // creating a deadlock // // Solution: Create the thread in suspended state and then // add and resume it with slock acquired assert(m_sz <= uint.max, "m_sz must be less than or equal to uint.max"); m_hndl = cast(HANDLE) _beginthreadex( null, cast(uint) m_sz, &thread_entryPoint, cast(void*) this, CREATE_SUSPENDED, &m_addr ); if( cast(size_t) m_hndl == 0 ) onThreadError( "Error creating thread" ); } slock.lock_nothrow(); scope(exit) slock.unlock_nothrow(); { ++nAboutToStart; pAboutToStart = cast(Thread*)realloc(pAboutToStart, Thread.sizeof * nAboutToStart); pAboutToStart[nAboutToStart - 1] = this; version( Windows ) { if( ResumeThread( m_hndl ) == -1 ) onThreadError( "Error resuming thread" ); } else version( Posix ) { // NOTE: This is also set to true by thread_entryPoint, but set it // here as well so the calling thread will see the isRunning // state immediately. atomicStore!(MemoryOrder.raw)(m_isRunning, true); scope( failure ) atomicStore!(MemoryOrder.raw)(m_isRunning, false); version (Shared) { import rt.sections; auto libs = pinLoadedLibraries(); auto ps = cast(void**).malloc(2 * size_t.sizeof); if (ps is null) onOutOfMemoryError(); ps[0] = cast(void*)this; ps[1] = cast(void*)libs; if( pthread_create( &m_addr, &attr, &thread_entryPoint, ps ) != 0 ) { unpinLoadedLibraries(libs); .free(ps); onThreadError( "Error creating thread" ); } } else { if( pthread_create( &m_addr, &attr, &thread_entryPoint, cast(void*) this ) != 0 ) onThreadError( "Error creating thread" ); } } version( Darwin ) { m_tmach = pthread_mach_thread_np( m_addr ); if( m_tmach == m_tmach.init ) onThreadError( "Error creating thread" ); } return this; } } /** * Waits for this thread to complete. If the thread terminated as the * result of an unhandled exception, this exception will be rethrown. * * Params: * rethrow = Rethrow any unhandled exception which may have caused this * thread to terminate. * * Throws: * ThreadException if the operation fails. * Any exception not handled by the joined thread. * * Returns: * Any exception not handled by this thread if rethrow = false, null * otherwise. */ final Throwable join( bool rethrow = true ) { version( Windows ) { if( WaitForSingleObject( m_hndl, INFINITE ) != WAIT_OBJECT_0 ) throw new ThreadException( "Unable to join thread" ); // NOTE: m_addr must be cleared before m_hndl is closed to avoid // a race condition with isRunning. The operation is done // with atomicStore to prevent compiler reordering. atomicStore!(MemoryOrder.raw)(*cast(shared)&m_addr, m_addr.init); CloseHandle( m_hndl ); m_hndl = m_hndl.init; } else version( Posix ) { if( pthread_join( m_addr, null ) != 0 ) throw new ThreadException( "Unable to join thread" ); // NOTE: pthread_join acts as a substitute for pthread_detach, // which is normally called by the dtor. Setting m_addr // to zero ensures that pthread_detach will not be called // on object destruction. m_addr = m_addr.init; } if( m_unhandled ) { if( rethrow ) throw m_unhandled; return m_unhandled; } return null; } /////////////////////////////////////////////////////////////////////////// // General Properties /////////////////////////////////////////////////////////////////////////// /** * Gets the OS identifier for this thread. * * Returns: * If the thread hasn't been started yet, returns $(LREF ThreadID)$(D.init). * Otherwise, returns the result of $(D GetCurrentThreadId) on Windows, * and $(D pthread_self) on POSIX. * * The value is unique for the current process. */ final @property ThreadID id() @safe @nogc { synchronized( this ) { return m_addr; } } /** * Gets the user-readable label for this thread. * * Returns: * The name of this thread. */ final @property string name() @safe @nogc { synchronized( this ) { return m_name; } } /** * Sets the user-readable label for this thread. * * Params: * val = The new name of this thread. */ final @property void name( string val ) @safe @nogc { synchronized( this ) { m_name = val; } } /** * Gets the daemon status for this thread. While the runtime will wait for * all normal threads to complete before tearing down the process, daemon * threads are effectively ignored and thus will not prevent the process * from terminating. In effect, daemon threads will be terminated * automatically by the OS when the process exits. * * Returns: * true if this is a daemon thread. */ final @property bool isDaemon() @safe @nogc { synchronized( this ) { return m_isDaemon; } } /** * Sets the daemon status for this thread. While the runtime will wait for * all normal threads to complete before tearing down the process, daemon * threads are effectively ignored and thus will not prevent the process * from terminating. In effect, daemon threads will be terminated * automatically by the OS when the process exits. * * Params: * val = The new daemon status for this thread. */ final @property void isDaemon( bool val ) @safe @nogc { synchronized( this ) { m_isDaemon = val; } } /** * Tests whether this thread is running. * * Returns: * true if the thread is running, false if not. */ final @property bool isRunning() nothrow @nogc { if( m_addr == m_addr.init ) { return false; } version( Windows ) { uint ecode = 0; GetExitCodeThread( m_hndl, &ecode ); return ecode == STILL_ACTIVE; } else version( Posix ) { return atomicLoad(m_isRunning); } } /////////////////////////////////////////////////////////////////////////// // Thread Priority Actions /////////////////////////////////////////////////////////////////////////// /** * The minimum scheduling priority that may be set for a thread. On * systems where multiple scheduling policies are defined, this value * represents the minimum valid priority for the scheduling policy of * the process. */ __gshared const int PRIORITY_MIN; /** * The maximum scheduling priority that may be set for a thread. On * systems where multiple scheduling policies are defined, this value * represents the maximum valid priority for the scheduling policy of * the process. */ __gshared const int PRIORITY_MAX; /** * The default scheduling priority that is set for a thread. On * systems where multiple scheduling policies are defined, this value * represents the default priority for the scheduling policy of * the process. */ __gshared const int PRIORITY_DEFAULT; version(NetBSD) { //NetBSD does not support priority for default policy // and it is not possible change policy without root access int fakePriority = int.max; } /** * Gets the scheduling priority for the associated thread. * * Note: Getting the priority of a thread that already terminated * might return the default priority. * * Returns: * The scheduling priority of this thread. */ final @property int priority() { version( Windows ) { return GetThreadPriority( m_hndl ); } else version(NetBSD) { return fakePriority==int.max? PRIORITY_DEFAULT : fakePriority; } else version( Posix ) { int policy; sched_param param; if (auto err = pthread_getschedparam(m_addr, &policy, &param)) { // ignore error if thread is not running => Bugzilla 8960 if (!atomicLoad(m_isRunning)) return PRIORITY_DEFAULT; throw new ThreadException("Unable to get thread priority"); } return param.sched_priority; } } /** * Sets the scheduling priority for the associated thread. * * Note: Setting the priority of a thread that already terminated * might have no effect. * * Params: * val = The new scheduling priority of this thread. */ final @property void priority( int val ) in { assert(val >= PRIORITY_MIN); assert(val <= PRIORITY_MAX); } body { version( Windows ) { if( !SetThreadPriority( m_hndl, val ) ) throw new ThreadException( "Unable to set thread priority" ); } else version( Solaris ) { // the pthread_setschedprio(3c) and pthread_setschedparam functions // are broken for the default (TS / time sharing) scheduling class. // instead, we use priocntl(2) which gives us the desired behavior. // We hardcode the min and max priorities to the current value // so this is a no-op for RT threads. if (m_isRTClass) return; pcparms_t pcparm; pcparm.pc_cid = PC_CLNULL; if (priocntl(idtype_t.P_LWPID, P_MYID, PC_GETPARMS, &pcparm) == -1) throw new ThreadException( "Unable to get scheduling class" ); pri_t* clparms = cast(pri_t*)&pcparm.pc_clparms; // clparms is filled in by the PC_GETPARMS call, only necessary // to adjust the element that contains the thread priority clparms[1] = cast(pri_t) val; if (priocntl(idtype_t.P_LWPID, P_MYID, PC_SETPARMS, &pcparm) == -1) throw new ThreadException( "Unable to set scheduling class" ); } else version(NetBSD) { fakePriority = val; } else version( Posix ) { static if(__traits(compiles, pthread_setschedprio)) { if (auto err = pthread_setschedprio(m_addr, val)) { // ignore error if thread is not running => Bugzilla 8960 if (!atomicLoad(m_isRunning)) return; throw new ThreadException("Unable to set thread priority"); } } else { // NOTE: pthread_setschedprio is not implemented on Darwin or FreeBSD, so use // the more complicated get/set sequence below. int policy; sched_param param; if (auto err = pthread_getschedparam(m_addr, &policy, &param)) { // ignore error if thread is not running => Bugzilla 8960 if (!atomicLoad(m_isRunning)) return; throw new ThreadException("Unable to set thread priority"); } param.sched_priority = val; if (auto err = pthread_setschedparam(m_addr, policy, &param)) { // ignore error if thread is not running => Bugzilla 8960 if (!atomicLoad(m_isRunning)) return; throw new ThreadException("Unable to set thread priority"); } } } } unittest { auto thr = Thread.getThis(); immutable prio = thr.priority; scope (exit) thr.priority = prio; assert(prio == PRIORITY_DEFAULT); assert(prio >= PRIORITY_MIN && prio <= PRIORITY_MAX); thr.priority = PRIORITY_MIN; assert(thr.priority == PRIORITY_MIN); thr.priority = PRIORITY_MAX; assert(thr.priority == PRIORITY_MAX); } unittest // Bugzilla 8960 { import core.sync.semaphore; auto thr = new Thread({}); thr.start(); Thread.sleep(1.msecs); // wait a little so the thread likely has finished thr.priority = PRIORITY_MAX; // setting priority doesn't cause error auto prio = thr.priority; // getting priority doesn't cause error assert(prio >= PRIORITY_MIN && prio <= PRIORITY_MAX); } /////////////////////////////////////////////////////////////////////////// // Actions on Calling Thread /////////////////////////////////////////////////////////////////////////// /** * Suspends the calling thread for at least the supplied period. This may * result in multiple OS calls if period is greater than the maximum sleep * duration supported by the operating system. * * Params: * val = The minimum duration the calling thread should be suspended. * * In: * period must be non-negative. * * Example: * ------------------------------------------------------------------------ * * Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds * Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds * * ------------------------------------------------------------------------ */ static void sleep( Duration val ) @nogc nothrow in { assert( !val.isNegative ); } body { version( Windows ) { auto maxSleepMillis = dur!("msecs")( uint.max - 1 ); // avoid a non-zero time to be round down to 0 if( val > dur!"msecs"( 0 ) && val < dur!"msecs"( 1 ) ) val = dur!"msecs"( 1 ); // NOTE: In instances where all other threads in the process have a // lower priority than the current thread, the current thread // will not yield with a sleep time of zero. However, unlike // yield(), the user is not asking for a yield to occur but // only for execution to suspend for the requested interval. // Therefore, expected performance may not be met if a yield // is forced upon the user. while( val > maxSleepMillis ) { Sleep( cast(uint) maxSleepMillis.total!"msecs" ); val -= maxSleepMillis; } Sleep( cast(uint) val.total!"msecs" ); } else version( Posix ) { timespec tin = void; timespec tout = void; val.split!("seconds", "nsecs")(tin.tv_sec, tin.tv_nsec); if( val.total!"seconds" > tin.tv_sec.max ) tin.tv_sec = tin.tv_sec.max; while( true ) { if( !nanosleep( &tin, &tout ) ) return; if( errno != EINTR ) assert(0, "Unable to sleep for the specified duration"); tin = tout; } } } /** * Forces a context switch to occur away from the calling thread. */ static void yield() @nogc nothrow { version( Windows ) SwitchToThread(); else version( Posix ) sched_yield(); } /////////////////////////////////////////////////////////////////////////// // Thread Accessors /////////////////////////////////////////////////////////////////////////// /** * Provides a reference to the calling thread. * * Returns: * The thread object representing the calling thread. The result of * deleting this object is undefined. If the current thread is not * attached to the runtime, a null reference is returned. */ static Thread getThis() @safe nothrow @nogc { // NOTE: This function may not be called until thread_init has // completed. See thread_suspendAll for more information // on why this might occur. return sm_this; } /** * Provides a list of all threads currently being tracked by the system. * Note that threads in the returned array might no longer run (see * $(D Thread.)$(LREF isRunning)). * * Returns: * An array containing references to all threads currently being * tracked by the system. The result of deleting any contained * objects is undefined. */ static Thread[] getAll() { static void resize(ref Thread[] buf, size_t nlen) { buf.length = nlen; } return getAllImpl!resize(); } /** * Operates on all threads currently being tracked by the system. The * result of deleting any Thread object is undefined. * Note that threads passed to the callback might no longer run (see * $(D Thread.)$(LREF isRunning)). * * Params: * dg = The supplied code as a delegate. * * Returns: * Zero if all elemented are visited, nonzero if not. */ static int opApply(scope int delegate(ref Thread) dg) { import core.stdc.stdlib : free, realloc; static void resize(ref Thread[] buf, size_t nlen) { buf = (cast(Thread*)realloc(buf.ptr, nlen * Thread.sizeof))[0 .. nlen]; } auto buf = getAllImpl!resize; scope(exit) if (buf.ptr) free(buf.ptr); foreach (t; buf) { if (auto res = dg(t)) return res; } return 0; } unittest { auto t1 = new Thread({ foreach (_; 0 .. 20) Thread.getAll; }).start; auto t2 = new Thread({ foreach (_; 0 .. 20) GC.collect; }).start; t1.join(); t2.join(); } private static Thread[] getAllImpl(alias resize)() { import core.atomic; Thread[] buf; while (true) { immutable len = atomicLoad!(MemoryOrder.raw)(*cast(shared)&sm_tlen); resize(buf, len); assert(buf.length == len); synchronized (slock) { if (len == sm_tlen) { size_t pos; for (Thread t = sm_tbeg; t; t = t.next) buf[pos++] = t; return buf; } } } } /////////////////////////////////////////////////////////////////////////// // Static Initalizer /////////////////////////////////////////////////////////////////////////// /** * This initializer is used to set thread constants. All functional * initialization occurs within thread_init(). */ shared static this() { version( Windows ) { PRIORITY_MIN = THREAD_PRIORITY_IDLE; PRIORITY_DEFAULT = THREAD_PRIORITY_NORMAL; PRIORITY_MAX = THREAD_PRIORITY_TIME_CRITICAL; } else version( Solaris ) { pcparms_t pcParms; pcinfo_t pcInfo; pcParms.pc_cid = PC_CLNULL; if (priocntl(idtype_t.P_PID, P_MYID, PC_GETPARMS, &pcParms) == -1) throw new ThreadException( "Unable to get scheduling class" ); pcInfo.pc_cid = pcParms.pc_cid; // PC_GETCLINFO ignores the first two args, use dummy values if (priocntl(idtype_t.P_PID, 0, PC_GETCLINFO, &pcInfo) == -1) throw new ThreadException( "Unable to get scheduling class info" ); pri_t* clparms = cast(pri_t*)&pcParms.pc_clparms; pri_t* clinfo = cast(pri_t*)&pcInfo.pc_clinfo; if (pcInfo.pc_clname == "RT") { m_isRTClass = true; // For RT class, just assume it can't be changed PRIORITY_MAX = clparms[0]; PRIORITY_MIN = clparms[0]; PRIORITY_DEFAULT = clparms[0]; } else { m_isRTClass = false; // For all other scheduling classes, there are // two key values -- uprilim and maxupri. // maxupri is the maximum possible priority defined // for the scheduling class, and valid priorities // range are in [-maxupri, maxupri]. // // However, uprilim is an upper limit that the // current thread can set for the current scheduling // class, which can be less than maxupri. As such, // use this value for PRIORITY_MAX since this is // the effective maximum. // uprilim PRIORITY_MAX = clparms[0]; // maxupri PRIORITY_MIN = -clinfo[0]; // by definition PRIORITY_DEFAULT = 0; } } else version( Posix ) { int policy; sched_param param; pthread_t self = pthread_self(); int status = pthread_getschedparam( self, &policy, &param ); assert( status == 0 ); PRIORITY_MIN = sched_get_priority_min( policy ); assert( PRIORITY_MIN != -1 ); PRIORITY_DEFAULT = param.sched_priority; PRIORITY_MAX = sched_get_priority_max( policy ); assert( PRIORITY_MAX != -1 ); } } /////////////////////////////////////////////////////////////////////////// // Stuff That Should Go Away /////////////////////////////////////////////////////////////////////////// private: // // Initializes a thread object which has no associated executable function. // This is used for the main thread initialized in thread_init(). // this(size_t sz = 0) @safe pure nothrow @nogc { if (sz) { version (Posix) { // stack size must be a multiple of PAGESIZE sz += PAGESIZE - 1; sz -= sz % PAGESIZE; // and at least PTHREAD_STACK_MIN if (PTHREAD_STACK_MIN > sz) sz = PTHREAD_STACK_MIN; } m_sz = sz; } m_call = Call.NO; m_curr = &m_main; } // // Thread entry point. Invokes the function or delegate passed on // construction (if any). // final void run() { switch( m_call ) { case Call.FN: m_fn(); break; case Call.DG: m_dg(); break; default: break; } } private: // // The type of routine passed on thread construction. // enum Call { NO, FN, DG } // // Standard types // version( Windows ) { alias uint TLSKey; } else version( Posix ) { alias pthread_key_t TLSKey; } // // Local storage // static Thread sm_this; // // Main process thread // __gshared Thread sm_main; version (FreeBSD) { // set when suspend failed and should be retried, see Issue 13416 shared bool m_suspendagain; } // // Standard thread data // version( Windows ) { HANDLE m_hndl; } else version( Darwin ) { mach_port_t m_tmach; } ThreadID m_addr; Call m_call; string m_name; union { void function() m_fn; void delegate() m_dg; } size_t m_sz; version( Posix ) { shared bool m_isRunning; } bool m_isDaemon; bool m_isInCriticalRegion; Throwable m_unhandled; version( Solaris ) { __gshared immutable bool m_isRTClass; } private: /////////////////////////////////////////////////////////////////////////// // Storage of Active Thread /////////////////////////////////////////////////////////////////////////// // // Sets a thread-local reference to the current thread object. // static void setThis( Thread t ) nothrow @nogc { sm_this = t; } private: /////////////////////////////////////////////////////////////////////////// // Thread Context and GC Scanning Support /////////////////////////////////////////////////////////////////////////// final void pushContext( Context* c ) nothrow @nogc in { assert( !c.within ); } body { m_curr.ehContext = swapContext(c.ehContext); c.within = m_curr; m_curr = c; } final void popContext() nothrow @nogc in { assert( m_curr && m_curr.within ); } body { Context* c = m_curr; m_curr = c.within; c.ehContext = swapContext(m_curr.ehContext); c.within = null; } final Context* topContext() nothrow @nogc in { assert( m_curr ); } body { return m_curr; } static struct Context { void* bstack, tstack; /// Slot for the EH implementation to keep some state for each stack /// (will be necessary for exception chaining, etc.). Opaque as far as /// we are concerned here. void* ehContext; Context* within; Context* next, prev; } Context m_main; Context* m_curr; bool m_lock; void* m_tlsgcdata; version( Windows ) { version( X86 ) { uint[8] m_reg; // edi,esi,ebp,esp,ebx,edx,ecx,eax } else version( X86_64 ) { ulong[16] m_reg; // rdi,rsi,rbp,rsp,rbx,rdx,rcx,rax // r8,r9,r10,r11,r12,r13,r14,r15 } else { static assert(false, "Architecture not supported." ); } } else version( Darwin ) { version( X86 ) { uint[8] m_reg; // edi,esi,ebp,esp,ebx,edx,ecx,eax } else version( X86_64 ) { ulong[16] m_reg; // rdi,rsi,rbp,rsp,rbx,rdx,rcx,rax // r8,r9,r10,r11,r12,r13,r14,r15 } else { static assert(false, "Architecture not supported." ); } } private: /////////////////////////////////////////////////////////////////////////// // GC Scanning Support /////////////////////////////////////////////////////////////////////////// // NOTE: The GC scanning process works like so: // // 1. Suspend all threads. // 2. Scan the stacks of all suspended threads for roots. // 3. Resume all threads. // // Step 1 and 3 require a list of all threads in the system, while // step 2 requires a list of all thread stacks (each represented by // a Context struct). Traditionally, there was one stack per thread // and the Context structs were not necessary. However, Fibers have // changed things so that each thread has its own 'main' stack plus // an arbitrary number of nested stacks (normally referenced via // m_curr). Also, there may be 'free-floating' stacks in the system, // which are Fibers that are not currently executing on any specific // thread but are still being processed and still contain valid // roots. // // To support all of this, the Context struct has been created to // represent a stack range, and a global list of Context structs has // been added to enable scanning of these stack ranges. The lifetime // (and presence in the Context list) of a thread's 'main' stack will // be equivalent to the thread's lifetime. So the Ccontext will be // added to the list on thread entry, and removed from the list on // thread exit (which is essentially the same as the presence of a // Thread object in its own global list). The lifetime of a Fiber's // context, however, will be tied to the lifetime of the Fiber object // itself, and Fibers are expected to add/remove their Context struct // on construction/deletion. // // All use of the global thread lists/array should synchronize on this lock. // // Careful as the GC acquires this lock after the GC lock to suspend all // threads any GC usage with slock held can result in a deadlock through // lock order inversion. @property static Mutex slock() nothrow @nogc { return cast(Mutex)_locks[0].ptr; } @property static Mutex criticalRegionLock() nothrow @nogc { return cast(Mutex)_locks[1].ptr; } __gshared void[__traits(classInstanceSize, Mutex)][2] _locks; static void initLocks() { foreach (ref lock; _locks) { lock[] = typeid(Mutex).initializer[]; (cast(Mutex)lock.ptr).__ctor(); } } static void termLocks() { foreach (ref lock; _locks) (cast(Mutex)lock.ptr).__dtor(); } __gshared Context* sm_cbeg; __gshared Thread sm_tbeg; __gshared size_t sm_tlen; // can't use rt.util.array in public code __gshared Thread* pAboutToStart; __gshared size_t nAboutToStart; // // Used for ordering threads in the global thread list. // Thread prev; Thread next; /////////////////////////////////////////////////////////////////////////// // Global Context List Operations /////////////////////////////////////////////////////////////////////////// // // Add a context to the global context list. // static void add( Context* c ) nothrow @nogc in { assert( c ); assert( !c.next && !c.prev ); } body { slock.lock_nothrow(); scope(exit) slock.unlock_nothrow(); assert(!suspendDepth); // must be 0 b/c it's only set with slock held if (sm_cbeg) { c.next = sm_cbeg; sm_cbeg.prev = c; } sm_cbeg = c; } // // Remove a context from the global context list. // // This assumes slock being acquired. This isn't done here to // avoid double locking when called from remove(Thread) static void remove( Context* c ) nothrow @nogc in { assert( c ); assert( c.next || c.prev ); } body { if( c.prev ) c.prev.next = c.next; if( c.next ) c.next.prev = c.prev; if( sm_cbeg == c ) sm_cbeg = c.next; // NOTE: Don't null out c.next or c.prev because opApply currently // follows c.next after removing a node. This could be easily // addressed by simply returning the next node from this // function, however, a context should never be re-added to the // list anyway and having next and prev be non-null is a good way // to ensure that. } /////////////////////////////////////////////////////////////////////////// // Global Thread List Operations /////////////////////////////////////////////////////////////////////////// // // Add a thread to the global thread list. // static void add( Thread t, bool rmAboutToStart = true ) nothrow @nogc in { assert( t ); assert( !t.next && !t.prev ); } body { slock.lock_nothrow(); scope(exit) slock.unlock_nothrow(); assert(t.isRunning); // check this with slock to ensure pthread_create already returned assert(!suspendDepth); // must be 0 b/c it's only set with slock held if (rmAboutToStart) { size_t idx = -1; foreach (i, thr; pAboutToStart[0 .. nAboutToStart]) { if (thr is t) { idx = i; break; } } assert(idx != -1); import core.stdc.string : memmove; memmove(pAboutToStart + idx, pAboutToStart + idx + 1, Thread.sizeof * (nAboutToStart - idx - 1)); pAboutToStart = cast(Thread*)realloc(pAboutToStart, Thread.sizeof * --nAboutToStart); } if (sm_tbeg) { t.next = sm_tbeg; sm_tbeg.prev = t; } sm_tbeg = t; ++sm_tlen; } // // Remove a thread from the global thread list. // static void remove( Thread t ) nothrow @nogc in { assert( t ); } body { // Thread was already removed earlier, might happen b/c of thread_detachInstance if (!t.next && !t.prev) return; slock.lock_nothrow(); { // NOTE: When a thread is removed from the global thread list its // main context is invalid and should be removed as well. // It is possible that t.m_curr could reference more // than just the main context if the thread exited abnormally // (if it was terminated), but we must assume that the user // retains a reference to them and that they may be re-used // elsewhere. Therefore, it is the responsibility of any // object that creates contexts to clean them up properly // when it is done with them. remove( &t.m_main ); if( t.prev ) t.prev.next = t.next; if( t.next ) t.next.prev = t.prev; if( sm_tbeg is t ) sm_tbeg = t.next; t.prev = t.next = null; --sm_tlen; } // NOTE: Don't null out t.next or t.prev because opApply currently // follows t.next after removing a node. This could be easily // addressed by simply returning the next node from this // function, however, a thread should never be re-added to the // list anyway and having next and prev be non-null is a good way // to ensure that. slock.unlock_nothrow(); } } /// unittest { class DerivedThread : Thread { this() { super(&run); } private: void run() { // Derived thread running. } } void threadFunc() { // Composed thread running. } // create and start instances of each type auto derived = new DerivedThread().start(); auto composed = new Thread(&threadFunc).start(); new Thread({ // Codes to run in the newly created thread. }).start(); } unittest { int x = 0; new Thread( { x++; }).start().join(); assert( x == 1 ); } unittest { enum MSG = "Test message."; string caughtMsg; try { new Thread( { throw new Exception( MSG ); }).start().join(); assert( false, "Expected rethrown exception." ); } catch( Throwable t ) { assert( t.msg == MSG ); } } /////////////////////////////////////////////////////////////////////////////// // GC Support Routines /////////////////////////////////////////////////////////////////////////////// version( CoreDdoc ) { /** * Instruct the thread module, when initialized, to use a different set of * signals besides SIGUSR1 and SIGUSR2 for suspension and resumption of threads. * This function should be called at most once, prior to thread_init(). * This function is Posix-only. */ extern (C) void thread_setGCSignals(int suspendSignalNo, int resumeSignalNo) nothrow @nogc { } } else version( Posix ) { extern (C) void thread_setGCSignals(int suspendSignalNo, int resumeSignalNo) nothrow @nogc in { assert(suspendSignalNumber == 0); assert(resumeSignalNumber == 0); assert(suspendSignalNo != 0); assert(resumeSignalNo != 0); } out { assert(suspendSignalNumber != 0); assert(resumeSignalNumber != 0); } body { suspendSignalNumber = suspendSignalNo; resumeSignalNumber = resumeSignalNo; } } version( Posix ) { __gshared int suspendSignalNumber; __gshared int resumeSignalNumber; } /** * Initializes the thread module. This function must be called by the * garbage collector on startup and before any other thread routines * are called. */ extern (C) void thread_init() { // NOTE: If thread_init itself performs any allocations then the thread // routines reserved for garbage collector use may be called while // thread_init is being processed. However, since no memory should // exist to be scanned at this point, it is sufficient for these // functions to detect the condition and return immediately. Thread.initLocks(); // The Android VM runtime intercepts SIGUSR1 and apparently doesn't allow // its signal handler to run, so swap the two signals on Android, since // thread_resumeHandler does nothing. version( Android ) thread_setGCSignals(SIGUSR2, SIGUSR1); version( Darwin ) { } else version( Posix ) { if( suspendSignalNumber == 0 ) { suspendSignalNumber = SIGUSR1; } if( resumeSignalNumber == 0 ) { resumeSignalNumber = SIGUSR2; } int status; sigaction_t sigusr1 = void; sigaction_t sigusr2 = void; // This is a quick way to zero-initialize the structs without using // memset or creating a link dependency on their static initializer. (cast(byte*) &sigusr1)[0 .. sigaction_t.sizeof] = 0; (cast(byte*) &sigusr2)[0 .. sigaction_t.sizeof] = 0; // NOTE: SA_RESTART indicates that system calls should restart if they // are interrupted by a signal, but this is not available on all // Posix systems, even those that support multithreading. static if( __traits( compiles, SA_RESTART ) ) sigusr1.sa_flags = SA_RESTART; else sigusr1.sa_flags = 0; sigusr1.sa_handler = &thread_suspendHandler; // NOTE: We want to ignore all signals while in this handler, so fill // sa_mask to indicate this. status = sigfillset( &sigusr1.sa_mask ); assert( status == 0 ); // NOTE: Since resumeSignalNumber should only be issued for threads within the // suspend handler, we don't want this signal to trigger a // restart. sigusr2.sa_flags = 0; sigusr2.sa_handler = &thread_resumeHandler; // NOTE: We want to ignore all signals while in this handler, so fill // sa_mask to indicate this. status = sigfillset( &sigusr2.sa_mask ); assert( status == 0 ); status = sigaction( suspendSignalNumber, &sigusr1, null ); assert( status == 0 ); status = sigaction( resumeSignalNumber, &sigusr2, null ); assert( status == 0 ); status = sem_init( &suspendCount, 0, 0 ); assert( status == 0 ); } Thread.sm_main = thread_attachThis(); } /** * Terminates the thread module. No other thread routine may be called * afterwards. */ extern (C) void thread_term() { assert(Thread.sm_tbeg && Thread.sm_tlen == 1); assert(!Thread.nAboutToStart); if (Thread.pAboutToStart) // in case realloc(p, 0) doesn't return null { free(Thread.pAboutToStart); Thread.pAboutToStart = null; } Thread.termLocks(); } /** * */ extern (C) bool thread_isMainThread() nothrow @nogc { return Thread.getThis() is Thread.sm_main; } /** * Registers the calling thread for use with the D Runtime. If this routine * is called for a thread which is already registered, no action is performed. * * NOTE: This routine does not run thread-local static constructors when called. * If full functionality as a D thread is desired, the following function * must be called after thread_attachThis: * * extern (C) void rt_moduleTlsCtor(); */ extern (C) Thread thread_attachThis() { GC.disable(); scope(exit) GC.enable(); if (auto t = Thread.getThis()) return t; Thread thisThread = new Thread(); Thread.Context* thisContext = &thisThread.m_main; assert( thisContext == thisThread.m_curr ); version( Windows ) { thisThread.m_addr = GetCurrentThreadId(); thisThread.m_hndl = GetCurrentThreadHandle(); thisContext.bstack = getStackBottom(); thisContext.tstack = thisContext.bstack; } else version( Posix ) { thisThread.m_addr = pthread_self(); thisContext.bstack = getStackBottom(); thisContext.tstack = thisContext.bstack; atomicStore!(MemoryOrder.raw)(thisThread.m_isRunning, true); } thisThread.m_isDaemon = true; thisThread.m_tlsgcdata = rt_tlsgc_init(); Thread.setThis( thisThread ); version( Darwin ) { thisThread.m_tmach = pthread_mach_thread_np( thisThread.m_addr ); assert( thisThread.m_tmach != thisThread.m_tmach.init ); } Thread.add( thisThread, false ); Thread.add( thisContext ); if( Thread.sm_main !is null ) multiThreadedFlag = true; return thisThread; } version( Windows ) { // NOTE: These calls are not safe on Posix systems that use signals to // perform garbage collection. The suspendHandler uses getThis() // to get the thread handle so getThis() must be a simple call. // Mutexes can't safely be acquired inside signal handlers, and // even if they could, the mutex needed (Thread.slock) is held by // thread_suspendAll(). So in short, these routines will remain // Windows-specific. If they are truly needed elsewhere, the // suspendHandler will need a way to call a version of getThis() // that only does the TLS lookup without the fancy fallback stuff. /// ditto extern (C) Thread thread_attachByAddr( ThreadID addr ) { return thread_attachByAddrB( addr, getThreadStackBottom( addr ) ); } /// ditto extern (C) Thread thread_attachByAddrB( ThreadID addr, void* bstack ) { GC.disable(); scope(exit) GC.enable(); if (auto t = thread_findByAddr(addr)) return t; Thread thisThread = new Thread(); Thread.Context* thisContext = &thisThread.m_main; assert( thisContext == thisThread.m_curr ); thisThread.m_addr = addr; thisContext.bstack = bstack; thisContext.tstack = thisContext.bstack; thisThread.m_isDaemon = true; if( addr == GetCurrentThreadId() ) { thisThread.m_hndl = GetCurrentThreadHandle(); thisThread.m_tlsgcdata = rt_tlsgc_init(); Thread.setThis( thisThread ); } else { thisThread.m_hndl = OpenThreadHandle( addr ); impersonate_thread(addr, { thisThread.m_tlsgcdata = rt_tlsgc_init(); Thread.setThis( thisThread ); }); } Thread.add( thisThread, false ); Thread.add( thisContext ); if( Thread.sm_main !is null ) multiThreadedFlag = true; return thisThread; } } /** * Deregisters the calling thread from use with the runtime. If this routine * is called for a thread which is not registered, the result is undefined. * * NOTE: This routine does not run thread-local static destructors when called. * If full functionality as a D thread is desired, the following function * must be called after thread_detachThis, particularly if the thread is * being detached at some indeterminate time before program termination: * * $(D extern(C) void rt_moduleTlsDtor();) */ extern (C) void thread_detachThis() nothrow @nogc { if (auto t = Thread.getThis()) Thread.remove(t); } /** * Deregisters the given thread from use with the runtime. If this routine * is called for a thread which is not registered, the result is undefined. * * NOTE: This routine does not run thread-local static destructors when called. * If full functionality as a D thread is desired, the following function * must be called by the detached thread, particularly if the thread is * being detached at some indeterminate time before program termination: * * $(D extern(C) void rt_moduleTlsDtor();) */ extern (C) void thread_detachByAddr( ThreadID addr ) { if( auto t = thread_findByAddr( addr ) ) Thread.remove( t ); } /// ditto extern (C) void thread_detachInstance( Thread t ) nothrow @nogc { Thread.remove( t ); } unittest { import core.sync.semaphore; auto sem = new Semaphore(); auto t = new Thread( { sem.notify(); Thread.sleep(100.msecs); }).start(); sem.wait(); // thread cannot be detached while being started thread_detachInstance(t); foreach (t2; Thread) assert(t !is t2); t.join(); } /** * Search the list of all threads for a thread with the given thread identifier. * * Params: * addr = The thread identifier to search for. * Returns: * The thread object associated with the thread identifier, null if not found. */ static Thread thread_findByAddr( ThreadID addr ) { Thread.slock.lock_nothrow(); scope(exit) Thread.slock.unlock_nothrow(); // also return just spawned thread so that // DLL_THREAD_ATTACH knows it's a D thread foreach (t; Thread.pAboutToStart[0 .. Thread.nAboutToStart]) if (t.m_addr == addr) return t; foreach (t; Thread) if (t.m_addr == addr) return t; return null; } /** * Sets the current thread to a specific reference. Only to be used * when dealing with externally-created threads (in e.g. C code). * The primary use of this function is when Thread.getThis() must * return a sensible value in, for example, TLS destructors. In * other words, don't touch this unless you know what you're doing. * * Params: * t = A reference to the current thread. May be null. */ extern (C) void thread_setThis(Thread t) nothrow @nogc { Thread.setThis(t); } /** * Joins all non-daemon threads that are currently running. This is done by * performing successive scans through the thread list until a scan consists * of only daemon threads. */ extern (C) void thread_joinAll() { Lagain: Thread.slock.lock_nothrow(); // wait for just spawned threads if (Thread.nAboutToStart) { Thread.slock.unlock_nothrow(); Thread.yield(); goto Lagain; } // join all non-daemon threads, the main thread is also a daemon auto t = Thread.sm_tbeg; while (t) { if (!t.isRunning) { auto tn = t.next; Thread.remove(t); t = tn; } else if (t.isDaemon) { t = t.next; } else { Thread.slock.unlock_nothrow(); t.join(); // might rethrow goto Lagain; // must restart iteration b/c of unlock } } Thread.slock.unlock_nothrow(); } /** * Performs intermediate shutdown of the thread module. */ shared static ~this() { // NOTE: The functionality related to garbage collection must be minimally // operable after this dtor completes. Therefore, only minimal // cleanup may occur. auto t = Thread.sm_tbeg; while (t) { auto tn = t.next; if (!t.isRunning) Thread.remove(t); t = tn; } } // Used for needLock below. private __gshared bool multiThreadedFlag = false; version (PPC64) version = ExternStackShell; version (ExternStackShell) { extern(D) public void callWithStackShell(scope void delegate(void* sp) nothrow fn) nothrow; } else { // Calls the given delegate, passing the current thread's stack pointer to it. private void callWithStackShell(scope void delegate(void* sp) nothrow fn) nothrow in { assert(fn); } body { // The purpose of the 'shell' is to ensure all the registers get // put on the stack so they'll be scanned. We only need to push // the callee-save registers. void *sp = void; version (GNU) { __builtin_unwind_init(); sp = &sp; } else version (AsmX86_Posix) { size_t[3] regs = void; asm pure nothrow @nogc { mov [regs + 0 * 4], EBX; mov [regs + 1 * 4], ESI; mov [regs + 2 * 4], EDI; mov sp[EBP], ESP; } } else version (AsmX86_Windows) { size_t[3] regs = void; asm pure nothrow @nogc { mov [regs + 0 * 4], EBX; mov [regs + 1 * 4], ESI; mov [regs + 2 * 4], EDI; mov sp[EBP], ESP; } } else version (AsmX86_64_Posix) { size_t[5] regs = void; asm pure nothrow @nogc { mov [regs + 0 * 8], RBX; mov [regs + 1 * 8], R12; mov [regs + 2 * 8], R13; mov [regs + 3 * 8], R14; mov [regs + 4 * 8], R15; mov sp[RBP], RSP; } } else version (AsmX86_64_Windows) { size_t[7] regs = void; asm pure nothrow @nogc { mov [regs + 0 * 8], RBX; mov [regs + 1 * 8], RSI; mov [regs + 2 * 8], RDI; mov [regs + 3 * 8], R12; mov [regs + 4 * 8], R13; mov [regs + 5 * 8], R14; mov [regs + 6 * 8], R15; mov sp[RBP], RSP; } } else { static assert(false, "Architecture not supported."); } fn(sp); } } // Used for suspendAll/resumeAll below. private __gshared uint suspendDepth = 0; /** * Suspend the specified thread and load stack and register information for * use by thread_scanAll. If the supplied thread is the calling thread, * stack and register information will be loaded but the thread will not * be suspended. If the suspend operation fails and the thread is not * running then it will be removed from the global thread list, otherwise * an exception will be thrown. * * Params: * t = The thread to suspend. * * Throws: * ThreadError if the suspend operation fails for a running thread. * Returns: * Whether the thread is now suspended (true) or terminated (false). */ private bool suspend( Thread t ) nothrow { Duration waittime = dur!"usecs"(10); Lagain: if (!t.isRunning) { Thread.remove(t); return false; } else if (t.m_isInCriticalRegion) { Thread.criticalRegionLock.unlock_nothrow(); Thread.sleep(waittime); if (waittime < dur!"msecs"(10)) waittime *= 2; Thread.criticalRegionLock.lock_nothrow(); goto Lagain; } version( Windows ) { if( t.m_addr != GetCurrentThreadId() && SuspendThread( t.m_hndl ) == 0xFFFFFFFF ) { if( !t.isRunning ) { Thread.remove( t ); return false; } onThreadError( "Unable to suspend thread" ); } CONTEXT context = void; context.ContextFlags = CONTEXT_INTEGER | CONTEXT_CONTROL; if( !GetThreadContext( t.m_hndl, &context ) ) onThreadError( "Unable to load thread context" ); version( X86 ) { if( !t.m_lock ) t.m_curr.tstack = cast(void*) context.Esp; // eax,ebx,ecx,edx,edi,esi,ebp,esp t.m_reg[0] = context.Eax; t.m_reg[1] = context.Ebx; t.m_reg[2] = context.Ecx; t.m_reg[3] = context.Edx; t.m_reg[4] = context.Edi; t.m_reg[5] = context.Esi; t.m_reg[6] = context.Ebp; t.m_reg[7] = context.Esp; } else version( X86_64 ) { if( !t.m_lock ) t.m_curr.tstack = cast(void*) context.Rsp; // rax,rbx,rcx,rdx,rdi,rsi,rbp,rsp t.m_reg[0] = context.Rax; t.m_reg[1] = context.Rbx; t.m_reg[2] = context.Rcx; t.m_reg[3] = context.Rdx; t.m_reg[4] = context.Rdi; t.m_reg[5] = context.Rsi; t.m_reg[6] = context.Rbp; t.m_reg[7] = context.Rsp; // r8,r9,r10,r11,r12,r13,r14,r15 t.m_reg[8] = context.R8; t.m_reg[9] = context.R9; t.m_reg[10] = context.R10; t.m_reg[11] = context.R11; t.m_reg[12] = context.R12; t.m_reg[13] = context.R13; t.m_reg[14] = context.R14; t.m_reg[15] = context.R15; } else { static assert(false, "Architecture not supported." ); } } else version( Darwin ) { if( t.m_addr != pthread_self() && thread_suspend( t.m_tmach ) != KERN_SUCCESS ) { if( !t.isRunning ) { Thread.remove( t ); return false; } onThreadError( "Unable to suspend thread" ); } version( X86 ) { x86_thread_state32_t state = void; mach_msg_type_number_t count = x86_THREAD_STATE32_COUNT; if( thread_get_state( t.m_tmach, x86_THREAD_STATE32, &state, &count ) != KERN_SUCCESS ) onThreadError( "Unable to load thread state" ); if( !t.m_lock ) t.m_curr.tstack = cast(void*) state.esp; // eax,ebx,ecx,edx,edi,esi,ebp,esp t.m_reg[0] = state.eax; t.m_reg[1] = state.ebx; t.m_reg[2] = state.ecx; t.m_reg[3] = state.edx; t.m_reg[4] = state.edi; t.m_reg[5] = state.esi; t.m_reg[6] = state.ebp; t.m_reg[7] = state.esp; } else version( X86_64 ) { x86_thread_state64_t state = void; mach_msg_type_number_t count = x86_THREAD_STATE64_COUNT; if( thread_get_state( t.m_tmach, x86_THREAD_STATE64, &state, &count ) != KERN_SUCCESS ) onThreadError( "Unable to load thread state" ); if( !t.m_lock ) t.m_curr.tstack = cast(void*) state.rsp; // rax,rbx,rcx,rdx,rdi,rsi,rbp,rsp t.m_reg[0] = state.rax; t.m_reg[1] = state.rbx; t.m_reg[2] = state.rcx; t.m_reg[3] = state.rdx; t.m_reg[4] = state.rdi; t.m_reg[5] = state.rsi; t.m_reg[6] = state.rbp; t.m_reg[7] = state.rsp; // r8,r9,r10,r11,r12,r13,r14,r15 t.m_reg[8] = state.r8; t.m_reg[9] = state.r9; t.m_reg[10] = state.r10; t.m_reg[11] = state.r11; t.m_reg[12] = state.r12; t.m_reg[13] = state.r13; t.m_reg[14] = state.r14; t.m_reg[15] = state.r15; } else { static assert(false, "Architecture not supported." ); } } else version( Posix ) { if( t.m_addr != pthread_self() ) { if( pthread_kill( t.m_addr, suspendSignalNumber ) != 0 ) { if( !t.isRunning ) { Thread.remove( t ); return false; } onThreadError( "Unable to suspend thread" ); } } else if( !t.m_lock ) { t.m_curr.tstack = getStackTop(); } } return true; } /** * Suspend all threads but the calling thread for "stop the world" garbage * collection runs. This function may be called multiple times, and must * be followed by a matching number of calls to thread_resumeAll before * processing is resumed. * * Throws: * ThreadError if the suspend operation fails for a running thread. */ extern (C) void thread_suspendAll() nothrow { // NOTE: We've got an odd chicken & egg problem here, because while the GC // is required to call thread_init before calling any other thread // routines, thread_init may allocate memory which could in turn // trigger a collection. Thus, thread_suspendAll, thread_scanAll, // and thread_resumeAll must be callable before thread_init // completes, with the assumption that no other GC memory has yet // been allocated by the system, and thus there is no risk of losing // data if the global thread list is empty. The check of // Thread.sm_tbeg below is done to ensure thread_init has completed, // and therefore that calling Thread.getThis will not result in an // error. For the short time when Thread.sm_tbeg is null, there is // no reason not to simply call the multithreaded code below, with // the expectation that the foreach loop will never be entered. if( !multiThreadedFlag && Thread.sm_tbeg ) { if( ++suspendDepth == 1 ) suspend( Thread.getThis() ); return; } Thread.slock.lock_nothrow(); { if( ++suspendDepth > 1 ) return; Thread.criticalRegionLock.lock_nothrow(); scope (exit) Thread.criticalRegionLock.unlock_nothrow(); size_t cnt; auto t = Thread.sm_tbeg; while (t) { auto tn = t.next; if (suspend(t)) ++cnt; t = tn; } version (Darwin) {} else version (Posix) { // subtract own thread assert(cnt >= 1); --cnt; Lagain: // wait for semaphore notifications for (; cnt; --cnt) { while (sem_wait(&suspendCount) != 0) { if (errno != EINTR) onThreadError("Unable to wait for semaphore"); errno = 0; } } version (FreeBSD) { // avoid deadlocks, see Issue 13416 t = Thread.sm_tbeg; while (t) { auto tn = t.next; if (t.m_suspendagain && suspend(t)) ++cnt; t = tn; } if (cnt) goto Lagain; } } } } /** * Resume the specified thread and unload stack and register information. * If the supplied thread is the calling thread, stack and register * information will be unloaded but the thread will not be resumed. If * the resume operation fails and the thread is not running then it will * be removed from the global thread list, otherwise an exception will be * thrown. * * Params: * t = The thread to resume. * * Throws: * ThreadError if the resume fails for a running thread. */ private void resume( Thread t ) nothrow { version( Windows ) { if( t.m_addr != GetCurrentThreadId() && ResumeThread( t.m_hndl ) == 0xFFFFFFFF ) { if( !t.isRunning ) { Thread.remove( t ); return; } onThreadError( "Unable to resume thread" ); } if( !t.m_lock ) t.m_curr.tstack = t.m_curr.bstack; t.m_reg[0 .. $] = 0; } else version( Darwin ) { if( t.m_addr != pthread_self() && thread_resume( t.m_tmach ) != KERN_SUCCESS ) { if( !t.isRunning ) { Thread.remove( t ); return; } onThreadError( "Unable to resume thread" ); } if( !t.m_lock ) t.m_curr.tstack = t.m_curr.bstack; t.m_reg[0 .. $] = 0; } else version( Posix ) { if( t.m_addr != pthread_self() ) { if( pthread_kill( t.m_addr, resumeSignalNumber ) != 0 ) { if( !t.isRunning ) { Thread.remove( t ); return; } onThreadError( "Unable to resume thread" ); } } else if( !t.m_lock ) { t.m_curr.tstack = t.m_curr.bstack; } } } /** * Resume all threads but the calling thread for "stop the world" garbage * collection runs. This function must be called once for each preceding * call to thread_suspendAll before the threads are actually resumed. * * In: * This routine must be preceded by a call to thread_suspendAll. * * Throws: * ThreadError if the resume operation fails for a running thread. */ extern (C) void thread_resumeAll() nothrow in { assert( suspendDepth > 0 ); } body { // NOTE: See thread_suspendAll for the logic behind this. if( !multiThreadedFlag && Thread.sm_tbeg ) { if( --suspendDepth == 0 ) resume( Thread.getThis() ); return; } scope(exit) Thread.slock.unlock_nothrow(); { if( --suspendDepth > 0 ) return; for( Thread t = Thread.sm_tbeg; t; t = t.next ) { // NOTE: We do not need to care about critical regions at all // here. thread_suspendAll takes care of everything. resume( t ); } } } /** * Indicates the kind of scan being performed by $(D thread_scanAllType). */ enum ScanType { stack, /// The stack and/or registers are being scanned. tls, /// TLS data is being scanned. } alias void delegate(void*, void*) nothrow ScanAllThreadsFn; /// The scanning function. alias void delegate(ScanType, void*, void*) nothrow ScanAllThreadsTypeFn; /// ditto /** * The main entry point for garbage collection. The supplied delegate * will be passed ranges representing both stack and register values. * * Params: * scan = The scanner function. It should scan from p1 through p2 - 1. * * In: * This routine must be preceded by a call to thread_suspendAll. */ extern (C) void thread_scanAllType( scope ScanAllThreadsTypeFn scan ) nothrow in { assert( suspendDepth > 0 ); } body { callWithStackShell(sp => scanAllTypeImpl(scan, sp)); } private void scanAllTypeImpl( scope ScanAllThreadsTypeFn scan, void* curStackTop ) nothrow { Thread thisThread = null; void* oldStackTop = null; if( Thread.sm_tbeg ) { thisThread = Thread.getThis(); if( !thisThread.m_lock ) { oldStackTop = thisThread.m_curr.tstack; thisThread.m_curr.tstack = curStackTop; } } scope( exit ) { if( Thread.sm_tbeg ) { if( !thisThread.m_lock ) { thisThread.m_curr.tstack = oldStackTop; } } } // NOTE: Synchronizing on Thread.slock is not needed because this // function may only be called after all other threads have // been suspended from within the same lock. if (Thread.nAboutToStart) scan(ScanType.stack, Thread.pAboutToStart, Thread.pAboutToStart + Thread.nAboutToStart); for( Thread.Context* c = Thread.sm_cbeg; c; c = c.next ) { version( StackGrowsDown ) { // NOTE: We can't index past the bottom of the stack // so don't do the "+1" for StackGrowsDown. if( c.tstack && c.tstack < c.bstack ) scan( ScanType.stack, c.tstack, c.bstack ); } else { if( c.bstack && c.bstack < c.tstack ) scan( ScanType.stack, c.bstack, c.tstack + 1 ); } } for( Thread t = Thread.sm_tbeg; t; t = t.next ) { version( Windows ) { // Ideally, we'd pass ScanType.regs or something like that, but this // would make portability annoying because it only makes sense on Windows. scan( ScanType.stack, t.m_reg.ptr, t.m_reg.ptr + t.m_reg.length ); } if (t.m_tlsgcdata !is null) rt_tlsgc_scan(t.m_tlsgcdata, (p1, p2) => scan(ScanType.tls, p1, p2)); } } /** * The main entry point for garbage collection. The supplied delegate * will be passed ranges representing both stack and register values. * * Params: * scan = The scanner function. It should scan from p1 through p2 - 1. * * In: * This routine must be preceded by a call to thread_suspendAll. */ extern (C) void thread_scanAll( scope ScanAllThreadsFn scan ) nothrow { thread_scanAllType((type, p1, p2) => scan(p1, p2)); } /** * Signals that the code following this call is a critical region. Any code in * this region must finish running before the calling thread can be suspended * by a call to thread_suspendAll. * * This function is, in particular, meant to help maintain garbage collector * invariants when a lock is not used. * * A critical region is exited with thread_exitCriticalRegion. * * $(RED Warning): * Using critical regions is extremely error-prone. For instance, using locks * inside a critical region can easily result in a deadlock when another thread * holding the lock already got suspended. * * The term and concept of a 'critical region' comes from * $(LINK2 https://github.com/mono/mono/blob/521f4a198e442573c400835ef19bbb36b60b0ebb/mono/metadata/sgen-gc.h#L925 Mono's SGen garbage collector). * * In: * The calling thread must be attached to the runtime. */ extern (C) void thread_enterCriticalRegion() @nogc in { assert(Thread.getThis()); } body { synchronized (Thread.criticalRegionLock) Thread.getThis().m_isInCriticalRegion = true; } /** * Signals that the calling thread is no longer in a critical region. Following * a call to this function, the thread can once again be suspended. * * In: * The calling thread must be attached to the runtime. */ extern (C) void thread_exitCriticalRegion() @nogc in { assert(Thread.getThis()); } body { synchronized (Thread.criticalRegionLock) Thread.getThis().m_isInCriticalRegion = false; } /** * Returns true if the current thread is in a critical region; otherwise, false. * * In: * The calling thread must be attached to the runtime. */ extern (C) bool thread_inCriticalRegion() @nogc in { assert(Thread.getThis()); } body { synchronized (Thread.criticalRegionLock) return Thread.getThis().m_isInCriticalRegion; } /** * A callback for thread errors in D during collections. Since an allocation is not possible * a preallocated ThreadError will be used as the Error instance * * Throws: * ThreadError. */ private void onThreadError(string msg = null, Throwable next = null) nothrow { __gshared ThreadError error = new ThreadError(null); error.msg = msg; error.next = next; import core.exception : SuppressTraceInfo; error.info = SuppressTraceInfo.instance; throw error; } unittest { assert(!thread_inCriticalRegion()); { thread_enterCriticalRegion(); scope (exit) thread_exitCriticalRegion(); assert(thread_inCriticalRegion()); } assert(!thread_inCriticalRegion()); } unittest { // NOTE: This entire test is based on the assumption that no // memory is allocated after the child thread is // started. If an allocation happens, a collection could // trigger, which would cause the synchronization below // to cause a deadlock. // NOTE: DO NOT USE LOCKS IN CRITICAL REGIONS IN NORMAL CODE. import core.sync.semaphore; auto sema = new Semaphore(), semb = new Semaphore(); auto thr = new Thread( { thread_enterCriticalRegion(); assert(thread_inCriticalRegion()); sema.notify(); semb.wait(); assert(thread_inCriticalRegion()); thread_exitCriticalRegion(); assert(!thread_inCriticalRegion()); sema.notify(); semb.wait(); assert(!thread_inCriticalRegion()); }); thr.start(); sema.wait(); synchronized (Thread.criticalRegionLock) assert(thr.m_isInCriticalRegion); semb.notify(); sema.wait(); synchronized (Thread.criticalRegionLock) assert(!thr.m_isInCriticalRegion); semb.notify(); thr.join(); } unittest { import core.sync.semaphore; shared bool inCriticalRegion; auto sema = new Semaphore(), semb = new Semaphore(); auto thr = new Thread( { thread_enterCriticalRegion(); inCriticalRegion = true; sema.notify(); semb.wait(); Thread.sleep(dur!"msecs"(1)); inCriticalRegion = false; thread_exitCriticalRegion(); }); thr.start(); sema.wait(); assert(inCriticalRegion); semb.notify(); thread_suspendAll(); assert(!inCriticalRegion); thread_resumeAll(); } /** * Indicates whether an address has been marked by the GC. */ enum IsMarked : int { no, /// Address is not marked. yes, /// Address is marked. unknown, /// Address is not managed by the GC. } alias int delegate( void* addr ) nothrow IsMarkedDg; /// The isMarked callback function. /** * This routine allows the runtime to process any special per-thread handling * for the GC. This is needed for taking into account any memory that is * referenced by non-scanned pointers but is about to be freed. That currently * means the array append cache. * * Params: * isMarked = The function used to check if $(D addr) is marked. * * In: * This routine must be called just prior to resuming all threads. */ extern(C) void thread_processGCMarks( scope IsMarkedDg isMarked ) nothrow { for( Thread t = Thread.sm_tbeg; t; t = t.next ) { /* Can be null if collection was triggered between adding a * thread and calling rt_tlsgc_init. */ if (t.m_tlsgcdata !is null) rt_tlsgc_processGCMarks(t.m_tlsgcdata, isMarked); } } extern (C) @nogc nothrow { version (CRuntime_Glibc) int pthread_getattr_np(pthread_t thread, pthread_attr_t* attr); version (FreeBSD) int pthread_attr_get_np(pthread_t thread, pthread_attr_t* attr); version (NetBSD) int pthread_attr_get_np(pthread_t thread, pthread_attr_t* attr); version (Solaris) int thr_stksegment(stack_t* stk); version (CRuntime_Bionic) int pthread_getattr_np(pthread_t thid, pthread_attr_t* attr); } private void* getStackTop() nothrow @nogc { version (D_InlineAsm_X86) asm pure nothrow @nogc { naked; mov EAX, ESP; ret; } else version (D_InlineAsm_X86_64) asm pure nothrow @nogc { naked; mov RAX, RSP; ret; } else version (GNU) return __builtin_frame_address(0); else static assert(false, "Architecture not supported."); } private void* getStackBottom() nothrow @nogc { version (Windows) { version (D_InlineAsm_X86) asm pure nothrow @nogc { naked; mov EAX, FS:4; ret; } else version(D_InlineAsm_X86_64) asm pure nothrow @nogc { naked; mov RAX, 8; mov RAX, GS:[RAX]; ret; } else static assert(false, "Architecture not supported."); } else version (Darwin) { import core.sys.darwin.pthread; return pthread_get_stackaddr_np(pthread_self()); } else version (CRuntime_Glibc) { pthread_attr_t attr; void* addr; size_t size; pthread_getattr_np(pthread_self(), &attr); pthread_attr_getstack(&attr, &addr, &size); pthread_attr_destroy(&attr); return addr + size; } else version (FreeBSD) { pthread_attr_t attr; void* addr; size_t size; pthread_attr_init(&attr); pthread_attr_get_np(pthread_self(), &attr); pthread_attr_getstack(&attr, &addr, &size); pthread_attr_destroy(&attr); return addr + size; } else version (NetBSD) { pthread_attr_t attr; void* addr; size_t size; pthread_attr_init(&attr); pthread_attr_get_np(pthread_self(), &attr); pthread_attr_getstack(&attr, &addr, &size); pthread_attr_destroy(&attr); return addr + size; } else version (Solaris) { stack_t stk; thr_stksegment(&stk); return stk.ss_sp; } else version (CRuntime_Bionic) { pthread_attr_t attr; void* addr; size_t size; pthread_getattr_np(pthread_self(), &attr); pthread_attr_getstack(&attr, &addr, &size); pthread_attr_destroy(&attr); return addr + size; } else static assert(false, "Platform not supported."); } /** * Returns the stack top of the currently active stack within the calling * thread. * * In: * The calling thread must be attached to the runtime. * * Returns: * The address of the stack top. */ extern (C) void* thread_stackTop() nothrow @nogc in { // Not strictly required, but it gives us more flexibility. assert(Thread.getThis()); } body { return getStackTop(); } /** * Returns the stack bottom of the currently active stack within the calling * thread. * * In: * The calling thread must be attached to the runtime. * * Returns: * The address of the stack bottom. */ extern (C) void* thread_stackBottom() nothrow @nogc in { assert(Thread.getThis()); } body { return Thread.getThis().topContext().bstack; } /////////////////////////////////////////////////////////////////////////////// // Thread Group /////////////////////////////////////////////////////////////////////////////// /** * This class is intended to simplify certain common programming techniques. */ class ThreadGroup { /** * Creates and starts a new Thread object that executes fn and adds it to * the list of tracked threads. * * Params: * fn = The thread function. * * Returns: * A reference to the newly created thread. */ final Thread create( void function() fn ) { Thread t = new Thread( fn ).start(); synchronized( this ) { m_all[t] = t; } return t; } /** * Creates and starts a new Thread object that executes dg and adds it to * the list of tracked threads. * * Params: * dg = The thread function. * * Returns: * A reference to the newly created thread. */ final Thread create( void delegate() dg ) { Thread t = new Thread( dg ).start(); synchronized( this ) { m_all[t] = t; } return t; } /** * Add t to the list of tracked threads if it is not already being tracked. * * Params: * t = The thread to add. * * In: * t must not be null. */ final void add( Thread t ) in { assert( t ); } body { synchronized( this ) { m_all[t] = t; } } /** * Removes t from the list of tracked threads. No operation will be * performed if t is not currently being tracked by this object. * * Params: * t = The thread to remove. * * In: * t must not be null. */ final void remove( Thread t ) in { assert( t ); } body { synchronized( this ) { m_all.remove( t ); } } /** * Operates on all threads currently tracked by this object. */ final int opApply( scope int delegate( ref Thread ) dg ) { synchronized( this ) { int ret = 0; // NOTE: This loop relies on the knowledge that m_all uses the // Thread object for both the key and the mapped value. foreach( Thread t; m_all.keys ) { ret = dg( t ); if( ret ) break; } return ret; } } /** * Iteratively joins all tracked threads. This function will block add, * remove, and opApply until it completes. * * Params: * rethrow = Rethrow any unhandled exception which may have caused the * current thread to terminate. * * Throws: * Any exception not handled by the joined threads. */ final void joinAll( bool rethrow = true ) { synchronized( this ) { // NOTE: This loop relies on the knowledge that m_all uses the // Thread object for both the key and the mapped value. foreach( Thread t; m_all.keys ) { t.join( rethrow ); } } } private: Thread[Thread] m_all; } /////////////////////////////////////////////////////////////////////////////// // Fiber Platform Detection and Memory Allocation /////////////////////////////////////////////////////////////////////////////// private { version( D_InlineAsm_X86 ) { version( Windows ) version = AsmX86_Windows; else version( Posix ) version = AsmX86_Posix; version( Darwin ) version = AlignFiberStackTo16Byte; } else version( D_InlineAsm_X86_64 ) { version( Windows ) { version = AsmX86_64_Windows; version = AlignFiberStackTo16Byte; } else version( Posix ) { version = AsmX86_64_Posix; version = AlignFiberStackTo16Byte; } } else version( PPC ) { version( Posix ) { version = AsmPPC_Posix; version = AsmExternal; } } else version( PPC64 ) { version( Posix ) { version = AlignFiberStackTo16Byte; } } else version( MIPS_O32 ) { version( Posix ) { version = AsmMIPS_O32_Posix; version = AsmExternal; } } else version( ARM ) { version( Posix ) { version = AsmARM_Posix; version = AsmExternal; } } version( Posix ) { import core.sys.posix.unistd; // for sysconf version( AsmX86_Windows ) {} else version( AsmX86_Posix ) {} else version( AsmX86_64_Windows ) {} else version( AsmX86_64_Posix ) {} else version( AsmExternal ) {} else { // NOTE: The ucontext implementation requires architecture specific // data definitions to operate so testing for it must be done // by checking for the existence of ucontext_t rather than by // a version identifier. Please note that this is considered // an obsolescent feature according to the POSIX spec, so a // custom solution is still preferred. import core.sys.posix.ucontext; } } static immutable size_t PAGESIZE; version (Posix) static immutable size_t PTHREAD_STACK_MIN; } shared static this() { version (Windows) { SYSTEM_INFO info; GetSystemInfo(&info); PAGESIZE = info.dwPageSize; assert(PAGESIZE < int.max); } else version (Posix) { PAGESIZE = cast(size_t)sysconf(_SC_PAGESIZE); PTHREAD_STACK_MIN = cast(size_t)sysconf(_SC_THREAD_STACK_MIN); } else { static assert(0, "unimplemented"); } } /////////////////////////////////////////////////////////////////////////////// // Fiber Entry Point and Context Switch /////////////////////////////////////////////////////////////////////////////// private { extern (C) void fiber_entryPoint() nothrow { Fiber obj = Fiber.getThis(); assert( obj ); assert( Thread.getThis().m_curr is obj.m_ctxt ); atomicStore!(MemoryOrder.raw)(*cast(shared)&Thread.getThis().m_lock, false); obj.m_ctxt.tstack = obj.m_ctxt.bstack; obj.m_state = Fiber.State.EXEC; try { obj.run(); } catch( Throwable t ) { obj.m_unhandled = t; } static if( __traits( compiles, ucontext_t ) ) obj.m_ucur = &obj.m_utxt; obj.m_state = Fiber.State.TERM; obj.switchOut(); } // Look above the definition of 'class Fiber' for some information about the implementation of this routine version( AsmExternal ) extern (C) void fiber_switchContext( void** oldp, void* newp ) nothrow @nogc; else extern (C) void fiber_switchContext( void** oldp, void* newp ) nothrow @nogc { // NOTE: The data pushed and popped in this routine must match the // default stack created by Fiber.initStack or the initial // switch into a new context will fail. version( AsmX86_Windows ) { asm pure nothrow @nogc { naked; // save current stack state push EBP; mov EBP, ESP; push EDI; push ESI; push EBX; push dword ptr FS:[0]; push dword ptr FS:[4]; push dword ptr FS:[8]; push EAX; // store oldp again with more accurate address mov EAX, dword ptr 8[EBP]; mov [EAX], ESP; // load newp to begin context switch mov ESP, dword ptr 12[EBP]; // load saved state from new stack pop EAX; pop dword ptr FS:[8]; pop dword ptr FS:[4]; pop dword ptr FS:[0]; pop EBX; pop ESI; pop EDI; pop EBP; // 'return' to complete switch pop ECX; jmp ECX; } } else version( AsmX86_64_Windows ) { asm pure nothrow @nogc { naked; // save current stack state // NOTE: When changing the layout of registers on the stack, // make sure that the XMM registers are still aligned. // On function entry, the stack is guaranteed to not // be aligned to 16 bytes because of the return address // on the stack. push RBP; mov RBP, RSP; push R12; push R13; push R14; push R15; push RDI; push RSI; // 7 registers = 56 bytes; stack is now aligned to 16 bytes sub RSP, 160; movdqa [RSP + 144], XMM6; movdqa [RSP + 128], XMM7; movdqa [RSP + 112], XMM8; movdqa [RSP + 96], XMM9; movdqa [RSP + 80], XMM10; movdqa [RSP + 64], XMM11; movdqa [RSP + 48], XMM12; movdqa [RSP + 32], XMM13; movdqa [RSP + 16], XMM14; movdqa [RSP], XMM15; push RBX; xor RAX,RAX; push qword ptr GS:[RAX]; push qword ptr GS:8[RAX]; push qword ptr GS:16[RAX]; // store oldp mov [RCX], RSP; // load newp to begin context switch mov RSP, RDX; // load saved state from new stack pop qword ptr GS:16[RAX]; pop qword ptr GS:8[RAX]; pop qword ptr GS:[RAX]; pop RBX; movdqa XMM15, [RSP]; movdqa XMM14, [RSP + 16]; movdqa XMM13, [RSP + 32]; movdqa XMM12, [RSP + 48]; movdqa XMM11, [RSP + 64]; movdqa XMM10, [RSP + 80]; movdqa XMM9, [RSP + 96]; movdqa XMM8, [RSP + 112]; movdqa XMM7, [RSP + 128]; movdqa XMM6, [RSP + 144]; add RSP, 160; pop RSI; pop RDI; pop R15; pop R14; pop R13; pop R12; pop RBP; // 'return' to complete switch pop RCX; jmp RCX; } } else version( AsmX86_Posix ) { asm pure nothrow @nogc { naked; // save current stack state push EBP; mov EBP, ESP; push EDI; push ESI; push EBX; push EAX; // store oldp again with more accurate address mov EAX, dword ptr 8[EBP]; mov [EAX], ESP; // load newp to begin context switch mov ESP, dword ptr 12[EBP]; // load saved state from new stack pop EAX; pop EBX; pop ESI; pop EDI; pop EBP; // 'return' to complete switch pop ECX; jmp ECX; } } else version( AsmX86_64_Posix ) { asm pure nothrow @nogc { naked; // save current stack state push RBP; mov RBP, RSP; push RBX; push R12; push R13; push R14; push R15; // store oldp mov [RDI], RSP; // load newp to begin context switch mov RSP, RSI; // load saved state from new stack pop R15; pop R14; pop R13; pop R12; pop RBX; pop RBP; // 'return' to complete switch pop RCX; jmp RCX; } } else static if( __traits( compiles, ucontext_t ) ) { Fiber cfib = Fiber.getThis(); void* ucur = cfib.m_ucur; *oldp = &ucur; swapcontext( **(cast(ucontext_t***) oldp), *(cast(ucontext_t**) newp) ); } else static assert(0, "Not implemented"); } } /////////////////////////////////////////////////////////////////////////////// // Fiber /////////////////////////////////////////////////////////////////////////////// /* * Documentation of Fiber internals: * * The main routines to implement when porting Fibers to new architectures are * fiber_switchContext and initStack. Some version constants have to be defined * for the new platform as well, search for "Fiber Platform Detection and Memory Allocation". * * Fibers are based on a concept called 'Context'. A Context describes the execution * state of a Fiber or main thread which is fully described by the stack, some * registers and a return address at which the Fiber/Thread should continue executing. * Please note that not only each Fiber has a Context, but each thread also has got a * Context which describes the threads stack and state. If you call Fiber fib; fib.call * the first time in a thread you switch from Threads Context into the Fibers Context. * If you call fib.yield in that Fiber you switch out of the Fibers context and back * into the Thread Context. (However, this is not always the case. You can call a Fiber * from within another Fiber, then you switch Contexts between the Fibers and the Thread * Context is not involved) * * In all current implementations the registers and the return address are actually * saved on a Contexts stack. * * The fiber_switchContext routine has got two parameters: * void** a: This is the _location_ where we have to store the current stack pointer, * the stack pointer of the currently executing Context (Fiber or Thread). * void* b: This is the pointer to the stack of the Context which we want to switch into. * Note that we get the same pointer here as the one we stored into the void** a * in a previous call to fiber_switchContext. * * In the simplest case, a fiber_switchContext rountine looks like this: * fiber_switchContext: * push {return Address} * push {registers} * copy {stack pointer} into {location pointed to by a} * //We have now switch to the stack of a different Context! * copy {b} into {stack pointer} * pop {registers} * pop {return Address} * jump to {return Address} * * The GC uses the value returned in parameter a to scan the Fibers stack. It scans from * the stack base to that value. As the GC dislikes false pointers we can actually optimize * this a little: By storing registers which can not contain references to memory managed * by the GC outside of the region marked by the stack base pointer and the stack pointer * saved in fiber_switchContext we can prevent the GC from scanning them. * Such registers are usually floating point registers and the return address. In order to * implement this, we return a modified stack pointer from fiber_switchContext. However, * we have to remember that when we restore the registers from the stack! * * --------------------------- <= Stack Base * | Frame | <= Many other stack frames * | Frame | * |-------------------------| <= The last stack frame. This one is created by fiber_switchContext * | registers with pointers | * | | <= Stack pointer. GC stops scanning here * | return address | * |floating point registers | * --------------------------- <= Real Stack End * * fiber_switchContext: * push {registers with pointers} * copy {stack pointer} into {location pointed to by a} * push {return Address} * push {Floating point registers} * //We have now switch to the stack of a different Context! * copy {b} into {stack pointer} * //We now have to adjust the stack pointer to point to 'Real Stack End' so we can pop * //the FP registers * //+ or - depends on if your stack grows downwards or upwards * {stack pointer} = {stack pointer} +- ({FPRegisters}.sizeof + {return address}.sizeof} * pop {Floating point registers} * pop {return Address} * pop {registers with pointers} * jump to {return Address} * * So the question now is which registers need to be saved? This depends on the specific * architecture ABI of course, but here are some general guidelines: * - If a register is callee-save (if the callee modifies the register it must saved and * restored by the callee) it needs to be saved/restored in switchContext * - If a register is caller-save it needn't be saved/restored. (Calling fiber_switchContext * is a function call and the compiler therefore already must save these registers before * calling fiber_switchContext) * - Argument registers used for passing parameters to functions needn't be saved/restored * - The return register needn't be saved/restored (fiber_switchContext hasn't got a return type) * - All scratch registers needn't be saved/restored * - The link register usually needn't be saved/restored (but sometimes it must be cleared - * see below for details) * - The frame pointer register - if it exists - is usually callee-save * - All current implementations do not save control registers * * What happens on the first switch into a Fiber? We never saved a state for this fiber before, * but the initial state is prepared in the initStack routine. (This routine will also be called * when a Fiber is being resetted). initStack must produce exactly the same stack layout as the * part of fiber_switchContext which saves the registers. Pay special attention to set the stack * pointer correctly if you use the GC optimization mentioned before. the return Address saved in * initStack must be the address of fiber_entrypoint. * * There's now a small but important difference between the first context switch into a fiber and * further context switches. On the first switch, Fiber.call is used and the returnAddress in * fiber_switchContext will point to fiber_entrypoint. The important thing here is that this jump * is a _function call_, we call fiber_entrypoint by jumping before it's function prologue. On later * calls, the user used yield() in a function, and therefore the return address points into a user * function, after the yield call. So here the jump in fiber_switchContext is a _function return_, * not a function call! * * The most important result of this is that on entering a function, i.e. fiber_entrypoint, we * would have to provide a return address / set the link register once fiber_entrypoint * returns. Now fiber_entrypoint does never return and therefore the actual value of the return * address / link register is never read/used and therefore doesn't matter. When fiber_switchContext * performs a _function return_ the value in the link register doesn't matter either. * However, the link register will still be saved to the stack in fiber_entrypoint and some * exception handling / stack unwinding code might read it from this stack location and crash. * The exact solution depends on your architecture, but see the ARM implementation for a way * to deal with this issue. * * The ARM implementation is meant to be used as a kind of documented example implementation. * Look there for a concrete example. * * FIXME: fiber_entrypoint might benefit from a @noreturn attribute, but D doesn't have one. */ /** * This class provides a cooperative concurrency mechanism integrated with the * threading and garbage collection functionality. Calling a fiber may be * considered a blocking operation that returns when the fiber yields (via * Fiber.yield()). Execution occurs within the context of the calling thread * so synchronization is not necessary to guarantee memory visibility so long * as the same thread calls the fiber each time. Please note that there is no * requirement that a fiber be bound to one specific thread. Rather, fibers * may be freely passed between threads so long as they are not currently * executing. Like threads, a new fiber thread may be created using either * derivation or composition, as in the following example. * * Warning: * Status registers are not saved by the current implementations. This means * floating point exception status bits (overflow, divide by 0), rounding mode * and similar stuff is set per-thread, not per Fiber! * * Warning: * On ARM FPU registers are not saved if druntime was compiled as ARM_SoftFloat. * If such a build is used on a ARM_SoftFP system which actually has got a FPU * and other libraries are using the FPU registers (other code is compiled * as ARM_SoftFP) this can cause problems. Druntime must be compiled as * ARM_SoftFP in this case. * * Example: * ---------------------------------------------------------------------- * * class DerivedFiber : Fiber * { * this() * { * super( &run ); * } * * private : * void run() * { * printf( "Derived fiber running.\n" ); * } * } * * void fiberFunc() * { * printf( "Composed fiber running.\n" ); * Fiber.yield(); * printf( "Composed fiber running.\n" ); * } * * // create instances of each type * Fiber derived = new DerivedFiber(); * Fiber composed = new Fiber( &fiberFunc ); * * // call both fibers once * derived.call(); * composed.call(); * printf( "Execution returned to calling context.\n" ); * composed.call(); * * // since each fiber has run to completion, each should have state TERM * assert( derived.state == Fiber.State.TERM ); * assert( composed.state == Fiber.State.TERM ); * * ---------------------------------------------------------------------- * * Authors: Based on a design by Mikola Lysenko. */ class Fiber { /////////////////////////////////////////////////////////////////////////// // Initialization /////////////////////////////////////////////////////////////////////////// /** * Initializes a fiber object which is associated with a static * D function. * * Params: * fn = The fiber function. * sz = The stack size for this fiber. * guardPageSize = size of the guard page to trap fiber's stack * overflows * * In: * fn must not be null. */ this( void function() fn, size_t sz = PAGESIZE*4, size_t guardPageSize = PAGESIZE ) nothrow in { assert( fn ); } body { allocStack( sz, guardPageSize ); reset( fn ); } /** * Initializes a fiber object which is associated with a dynamic * D function. * * Params: * dg = The fiber function. * sz = The stack size for this fiber. * guardPageSize = size of the guard page to trap fiber's stack * overflows * * In: * dg must not be null. */ this( void delegate() dg, size_t sz = PAGESIZE*4, size_t guardPageSize = PAGESIZE ) nothrow in { assert( dg ); } body { allocStack( sz, guardPageSize); reset( dg ); } /** * Cleans up any remaining resources used by this object. */ ~this() nothrow @nogc { // NOTE: A live reference to this object will exist on its associated // stack from the first time its call() method has been called // until its execution completes with State.TERM. Thus, the only // times this dtor should be called are either if the fiber has // terminated (and therefore has no active stack) or if the user // explicitly deletes this object. The latter case is an error // but is not easily tested for, since State.HOLD may imply that // the fiber was just created but has never been run. There is // not a compelling case to create a State.INIT just to offer a // means of ensuring the user isn't violating this object's // contract, so for now this requirement will be enforced by // documentation only. freeStack(); } /////////////////////////////////////////////////////////////////////////// // General Actions /////////////////////////////////////////////////////////////////////////// /** * Transfers execution to this fiber object. The calling context will be * suspended until the fiber calls Fiber.yield() or until it terminates * via an unhandled exception. * * Params: * rethrow = Rethrow any unhandled exception which may have caused this * fiber to terminate. * * In: * This fiber must be in state HOLD. * * Throws: * Any exception not handled by the joined thread. * * Returns: * Any exception not handled by this fiber if rethrow = false, null * otherwise. */ // Not marked with any attributes, even though `nothrow @nogc` works // because it calls arbitrary user code. Most of the implementation // is already `@nogc nothrow`, but in order for `Fiber.call` to // propagate the attributes of the user's function, the Fiber // class needs to be templated. final Throwable call( Rethrow rethrow = Rethrow.yes ) { return rethrow ? call!(Rethrow.yes)() : call!(Rethrow.no); } /// ditto final Throwable call( Rethrow rethrow )() { callImpl(); if( m_unhandled ) { Throwable t = m_unhandled; m_unhandled = null; static if( rethrow ) throw t; else return t; } return null; } /// ditto deprecated("Please pass Fiber.Rethrow.yes or .no instead of a boolean.") final Throwable call( bool rethrow ) { return rethrow ? call!(Rethrow.yes)() : call!(Rethrow.no); } private void callImpl() nothrow @nogc in { assert( m_state == State.HOLD ); } body { Fiber cur = getThis(); static if( __traits( compiles, ucontext_t ) ) m_ucur = cur ? &cur.m_utxt : &Fiber.sm_utxt; setThis( this ); this.switchIn(); setThis( cur ); static if( __traits( compiles, ucontext_t ) ) m_ucur = null; // NOTE: If the fiber has terminated then the stack pointers must be // reset. This ensures that the stack for this fiber is not // scanned if the fiber has terminated. This is necessary to // prevent any references lingering on the stack from delaying // the collection of otherwise dead objects. The most notable // being the current object, which is referenced at the top of // fiber_entryPoint. if( m_state == State.TERM ) { m_ctxt.tstack = m_ctxt.bstack; } } /// Flag to control rethrow behavior of $(D $(LREF call)) enum Rethrow : bool { no, yes } /** * Resets this fiber so that it may be re-used, optionally with a * new function/delegate. This routine should only be called for * fibers that have terminated, as doing otherwise could result in * scope-dependent functionality that is not executed. * Stack-based classes, for example, may not be cleaned up * properly if a fiber is reset before it has terminated. * * In: * This fiber must be in state TERM or HOLD. */ final void reset() nothrow @nogc in { assert( m_state == State.TERM || m_state == State.HOLD ); } body { m_ctxt.tstack = m_ctxt.bstack; m_state = State.HOLD; initStack(); m_unhandled = null; } /// ditto final void reset( void function() fn ) nothrow @nogc { reset(); m_fn = fn; m_call = Call.FN; } /// ditto final void reset( void delegate() dg ) nothrow @nogc { reset(); m_dg = dg; m_call = Call.DG; } /////////////////////////////////////////////////////////////////////////// // General Properties /////////////////////////////////////////////////////////////////////////// /** * A fiber may occupy one of three states: HOLD, EXEC, and TERM. The HOLD * state applies to any fiber that is suspended and ready to be called. * The EXEC state will be set for any fiber that is currently executing. * And the TERM state is set when a fiber terminates. Once a fiber * terminates, it must be reset before it may be called again. */ enum State { HOLD, /// EXEC, /// TERM /// } /** * Gets the current state of this fiber. * * Returns: * The state of this fiber as an enumerated value. */ final @property State state() const @safe pure nothrow @nogc { return m_state; } /////////////////////////////////////////////////////////////////////////// // Actions on Calling Fiber /////////////////////////////////////////////////////////////////////////// /** * Forces a context switch to occur away from the calling fiber. */ static void yield() nothrow @nogc { Fiber cur = getThis(); assert( cur, "Fiber.yield() called with no active fiber" ); assert( cur.m_state == State.EXEC ); static if( __traits( compiles, ucontext_t ) ) cur.m_ucur = &cur.m_utxt; cur.m_state = State.HOLD; cur.switchOut(); cur.m_state = State.EXEC; } /** * Forces a context switch to occur away from the calling fiber and then * throws obj in the calling fiber. * * Params: * t = The object to throw. * * In: * t must not be null. */ static void yieldAndThrow( Throwable t ) nothrow @nogc in { assert( t ); } body { Fiber cur = getThis(); assert( cur, "Fiber.yield() called with no active fiber" ); assert( cur.m_state == State.EXEC ); static if( __traits( compiles, ucontext_t ) ) cur.m_ucur = &cur.m_utxt; cur.m_unhandled = t; cur.m_state = State.HOLD; cur.switchOut(); cur.m_state = State.EXEC; } /////////////////////////////////////////////////////////////////////////// // Fiber Accessors /////////////////////////////////////////////////////////////////////////// /** * Provides a reference to the calling fiber or null if no fiber is * currently active. * * Returns: * The fiber object representing the calling fiber or null if no fiber * is currently active within this thread. The result of deleting this object is undefined. */ static Fiber getThis() @safe nothrow @nogc { return sm_this; } /////////////////////////////////////////////////////////////////////////// // Static Initialization /////////////////////////////////////////////////////////////////////////// version( Posix ) { static this() { static if( __traits( compiles, ucontext_t ) ) { int status = getcontext( &sm_utxt ); assert( status == 0 ); } } } private: // // Initializes a fiber object which has no associated executable function. // this() @safe pure nothrow @nogc { m_call = Call.NO; } // // Fiber entry point. Invokes the function or delegate passed on // construction (if any). // final void run() { switch( m_call ) { case Call.FN: m_fn(); break; case Call.DG: m_dg(); break; default: break; } } private: // // The type of routine passed on fiber construction. // enum Call { NO, FN, DG } // // Standard fiber data // Call m_call; union { void function() m_fn; void delegate() m_dg; } bool m_isRunning; Throwable m_unhandled; State m_state; private: /////////////////////////////////////////////////////////////////////////// // Stack Management /////////////////////////////////////////////////////////////////////////// // // Allocate a new stack for this fiber. // final void allocStack( size_t sz, size_t guardPageSize ) nothrow in { assert( !m_pmem && !m_ctxt ); } body { // adjust alloc size to a multiple of PAGESIZE sz += PAGESIZE - 1; sz -= sz % PAGESIZE; // NOTE: This instance of Thread.Context is dynamic so Fiber objects // can be collected by the GC so long as no user level references // to the object exist. If m_ctxt were not dynamic then its // presence in the global context list would be enough to keep // this object alive indefinitely. An alternative to allocating // room for this struct explicitly would be to mash it into the // base of the stack being allocated below. However, doing so // requires too much special logic to be worthwhile. m_ctxt = new Thread.Context; static if( __traits( compiles, VirtualAlloc ) ) { // reserve memory for stack m_pmem = VirtualAlloc( null, sz + guardPageSize, MEM_RESERVE, PAGE_NOACCESS ); if( !m_pmem ) onOutOfMemoryError(); version( StackGrowsDown ) { void* stack = m_pmem + guardPageSize; void* guard = m_pmem; void* pbase = stack + sz; } else { void* stack = m_pmem; void* guard = m_pmem + sz; void* pbase = stack; } // allocate reserved stack segment stack = VirtualAlloc( stack, sz, MEM_COMMIT, PAGE_READWRITE ); if( !stack ) onOutOfMemoryError(); if (guardPageSize) { // allocate reserved guard page guard = VirtualAlloc( guard, guardPageSize, MEM_COMMIT, PAGE_READWRITE | PAGE_GUARD ); if( !guard ) onOutOfMemoryError(); } m_ctxt.bstack = pbase; m_ctxt.tstack = pbase; m_size = sz; } else { version (Posix) import core.sys.posix.sys.mman; // mmap version (FreeBSD) import core.sys.freebsd.sys.mman : MAP_ANON; version (NetBSD) import core.sys.netbsd.sys.mman : MAP_ANON; version (CRuntime_Glibc) import core.sys.linux.sys.mman : MAP_ANON; version (Darwin) import core.sys.darwin.sys.mman : MAP_ANON; static if( __traits( compiles, mmap ) ) { // Allocate more for the memory guard sz += guardPageSize; m_pmem = mmap( null, sz, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0 ); if( m_pmem == MAP_FAILED ) m_pmem = null; } else static if( __traits( compiles, valloc ) ) { m_pmem = valloc( sz ); } else static if( __traits( compiles, malloc ) ) { m_pmem = malloc( sz ); } else { m_pmem = null; } if( !m_pmem ) onOutOfMemoryError(); version( StackGrowsDown ) { m_ctxt.bstack = m_pmem + sz; m_ctxt.tstack = m_pmem + sz; void* guard = m_pmem; } else { m_ctxt.bstack = m_pmem; m_ctxt.tstack = m_pmem; void* guard = m_pmem + sz - guardPageSize; } m_size = sz; static if( __traits( compiles, mmap ) ) { if (guardPageSize) { // protect end of stack if ( mprotect(guard, guardPageSize, PROT_NONE) == -1 ) abort(); } } else { // Supported only for mmap allocated memory - results are // undefined if applied to memory not obtained by mmap } } Thread.add( m_ctxt ); } // // Free this fiber's stack. // final void freeStack() nothrow @nogc in { assert( m_pmem && m_ctxt ); } body { // NOTE: m_ctxt is guaranteed to be alive because it is held in the // global context list. Thread.slock.lock_nothrow(); scope(exit) Thread.slock.unlock_nothrow(); Thread.remove( m_ctxt ); static if( __traits( compiles, VirtualAlloc ) ) { VirtualFree( m_pmem, 0, MEM_RELEASE ); } else { import core.sys.posix.sys.mman; // munmap static if( __traits( compiles, mmap ) ) { munmap( m_pmem, m_size ); } else static if( __traits( compiles, valloc ) ) { free( m_pmem ); } else static if( __traits( compiles, malloc ) ) { free( m_pmem ); } } m_pmem = null; m_ctxt = null; } // // Initialize the allocated stack. // Look above the definition of 'class Fiber' for some information about the implementation of this routine // final void initStack() nothrow @nogc in { assert( m_ctxt.tstack && m_ctxt.tstack == m_ctxt.bstack ); assert( cast(size_t) m_ctxt.bstack % (void*).sizeof == 0 ); } body { void* pstack = m_ctxt.tstack; scope( exit ) m_ctxt.tstack = pstack; void push( size_t val ) nothrow { version( StackGrowsDown ) { pstack -= size_t.sizeof; *(cast(size_t*) pstack) = val; } else { pstack += size_t.sizeof; *(cast(size_t*) pstack) = val; } } // NOTE: On OS X the stack must be 16-byte aligned according // to the IA-32 call spec. For x86_64 the stack also needs to // be aligned to 16-byte according to SysV AMD64 ABI. version( AlignFiberStackTo16Byte ) { version( StackGrowsDown ) { pstack = cast(void*)(cast(size_t)(pstack) - (cast(size_t)(pstack) & 0x0F)); } else { pstack = cast(void*)(cast(size_t)(pstack) + (cast(size_t)(pstack) & 0x0F)); } } version( AsmX86_Windows ) { version( StackGrowsDown ) {} else static assert( false ); // On Windows Server 2008 and 2008 R2, an exploit mitigation // technique known as SEHOP is activated by default. To avoid // hijacking of the exception handler chain, the presence of a // Windows-internal handler (ntdll.dll!FinalExceptionHandler) at // its end is tested by RaiseException. If it is not present, all // handlers are disregarded, and the program is thus aborted // (see http://blogs.technet.com/b/srd/archive/2009/02/02/ // preventing-the-exploitation-of-seh-overwrites-with-sehop.aspx). // For new threads, this handler is installed by Windows immediately // after creation. To make exception handling work in fibers, we // have to insert it for our new stacks manually as well. // // To do this, we first determine the handler by traversing the SEH // chain of the current thread until its end, and then construct a // registration block for the last handler on the newly created // thread. We then continue to push all the initial register values // for the first context switch as for the other implementations. // // Note that this handler is never actually invoked, as we install // our own one on top of it in the fiber entry point function. // Thus, it should not have any effects on OSes not implementing // exception chain verification. alias void function() fp_t; // Actual signature not relevant. static struct EXCEPTION_REGISTRATION { EXCEPTION_REGISTRATION* next; // sehChainEnd if last one. fp_t handler; } enum sehChainEnd = cast(EXCEPTION_REGISTRATION*) 0xFFFFFFFF; __gshared static fp_t finalHandler = null; if ( finalHandler is null ) { static EXCEPTION_REGISTRATION* fs0() nothrow { asm pure nothrow @nogc { naked; mov EAX, FS:[0]; ret; } } auto reg = fs0(); while ( reg.next != sehChainEnd ) reg = reg.next; // Benign races are okay here, just to avoid re-lookup on every // fiber creation. finalHandler = reg.handler; } // When linking with /safeseh (supported by LDC, but not DMD) // the exception chain must not extend to the very top // of the stack, otherwise the exception chain is also considered // invalid. Reserving additional 4 bytes at the top of the stack will // keep the EXCEPTION_REGISTRATION below that limit size_t reserve = EXCEPTION_REGISTRATION.sizeof + 4; pstack -= reserve; *(cast(EXCEPTION_REGISTRATION*)pstack) = EXCEPTION_REGISTRATION( sehChainEnd, finalHandler ); push( cast(size_t) &fiber_entryPoint ); // EIP push( cast(size_t) m_ctxt.bstack - reserve ); // EBP push( 0x00000000 ); // EDI push( 0x00000000 ); // ESI push( 0x00000000 ); // EBX push( cast(size_t) m_ctxt.bstack - reserve ); // FS:[0] push( cast(size_t) m_ctxt.bstack ); // FS:[4] push( cast(size_t) m_ctxt.bstack - m_size ); // FS:[8] push( 0x00000000 ); // EAX } else version( AsmX86_64_Windows ) { // Using this trampoline instead of the raw fiber_entryPoint // ensures that during context switches, source and destination // stacks have the same alignment. Otherwise, the stack would need // to be shifted by 8 bytes for the first call, as fiber_entryPoint // is an actual function expecting a stack which is not aligned // to 16 bytes. static void trampoline() { asm pure nothrow @nogc { naked; sub RSP, 32; // Shadow space (Win64 calling convention) call fiber_entryPoint; xor RCX, RCX; // This should never be reached, as jmp RCX; // fiber_entryPoint must never return. } } push( cast(size_t) &trampoline ); // RIP push( 0x00000000_00000000 ); // RBP push( 0x00000000_00000000 ); // R12 push( 0x00000000_00000000 ); // R13 push( 0x00000000_00000000 ); // R14 push( 0x00000000_00000000 ); // R15 push( 0x00000000_00000000 ); // RDI push( 0x00000000_00000000 ); // RSI push( 0x00000000_00000000 ); // XMM6 (high) push( 0x00000000_00000000 ); // XMM6 (low) push( 0x00000000_00000000 ); // XMM7 (high) push( 0x00000000_00000000 ); // XMM7 (low) push( 0x00000000_00000000 ); // XMM8 (high) push( 0x00000000_00000000 ); // XMM8 (low) push( 0x00000000_00000000 ); // XMM9 (high) push( 0x00000000_00000000 ); // XMM9 (low) push( 0x00000000_00000000 ); // XMM10 (high) push( 0x00000000_00000000 ); // XMM10 (low) push( 0x00000000_00000000 ); // XMM11 (high) push( 0x00000000_00000000 ); // XMM11 (low) push( 0x00000000_00000000 ); // XMM12 (high) push( 0x00000000_00000000 ); // XMM12 (low) push( 0x00000000_00000000 ); // XMM13 (high) push( 0x00000000_00000000 ); // XMM13 (low) push( 0x00000000_00000000 ); // XMM14 (high) push( 0x00000000_00000000 ); // XMM14 (low) push( 0x00000000_00000000 ); // XMM15 (high) push( 0x00000000_00000000 ); // XMM15 (low) push( 0x00000000_00000000 ); // RBX push( 0xFFFFFFFF_FFFFFFFF ); // GS:[0] version( StackGrowsDown ) { push( cast(size_t) m_ctxt.bstack ); // GS:[8] push( cast(size_t) m_ctxt.bstack - m_size ); // GS:[16] } else { push( cast(size_t) m_ctxt.bstack ); // GS:[8] push( cast(size_t) m_ctxt.bstack + m_size ); // GS:[16] } } else version( AsmX86_Posix ) { push( 0x00000000 ); // Return address of fiber_entryPoint call push( cast(size_t) &fiber_entryPoint ); // EIP push( cast(size_t) m_ctxt.bstack ); // EBP push( 0x00000000 ); // EDI push( 0x00000000 ); // ESI push( 0x00000000 ); // EBX push( 0x00000000 ); // EAX } else version( AsmX86_64_Posix ) { push( 0x00000000_00000000 ); // Return address of fiber_entryPoint call push( cast(size_t) &fiber_entryPoint ); // RIP push( cast(size_t) m_ctxt.bstack ); // RBP push( 0x00000000_00000000 ); // RBX push( 0x00000000_00000000 ); // R12 push( 0x00000000_00000000 ); // R13 push( 0x00000000_00000000 ); // R14 push( 0x00000000_00000000 ); // R15 } else version( AsmPPC_Posix ) { version( StackGrowsDown ) { pstack -= int.sizeof * 5; } else { pstack += int.sizeof * 5; } push( cast(size_t) &fiber_entryPoint ); // link register push( 0x00000000 ); // control register push( 0x00000000 ); // old stack pointer // GPR values version( StackGrowsDown ) { pstack -= int.sizeof * 20; } else { pstack += int.sizeof * 20; } assert( (cast(size_t) pstack & 0x0f) == 0 ); } else version( AsmMIPS_O32_Posix ) { version (StackGrowsDown) {} else static assert(0); /* We keep the FP registers and the return address below * the stack pointer, so they don't get scanned by the * GC. The last frame before swapping the stack pointer is * organized like the following. * * |-----------|<= frame pointer * | $gp | * | $s0-8 | * |-----------|<= stack pointer * | $ra | * | align(8) | * | $f20-30 | * |-----------| * */ enum SZ_GP = 10 * size_t.sizeof; // $gp + $s0-8 enum SZ_RA = size_t.sizeof; // $ra version (MIPS_HardFloat) { enum SZ_FP = 6 * 8; // $f20-30 enum ALIGN = -(SZ_FP + SZ_RA) & (8 - 1); } else { enum SZ_FP = 0; enum ALIGN = 0; } enum BELOW = SZ_FP + ALIGN + SZ_RA; enum ABOVE = SZ_GP; enum SZ = BELOW + ABOVE; (cast(ubyte*)pstack - SZ)[0 .. SZ] = 0; pstack -= ABOVE; *cast(size_t*)(pstack - SZ_RA) = cast(size_t)&fiber_entryPoint; } else version( AsmARM_Posix ) { /* We keep the FP registers and the return address below * the stack pointer, so they don't get scanned by the * GC. The last frame before swapping the stack pointer is * organized like the following. * * | |-----------|<= 'frame starts here' * | | fp | (the actual frame pointer, r11 isn't * | | r10-r4 | updated and still points to the previous frame) * | |-----------|<= stack pointer * | | lr | * | | 4byte pad | * | | d15-d8 |(if FP supported) * | |-----------| * Y * stack grows down: The pointer value here is smaller than some lines above */ // frame pointer can be zero, r10-r4 also zero initialized version( StackGrowsDown ) pstack -= int.sizeof * 8; else static assert(false, "Only full descending stacks supported on ARM"); // link register push( cast(size_t) &fiber_entryPoint ); /* * We do not push padding and d15-d8 as those are zero initialized anyway * Position the stack pointer above the lr register */ pstack += int.sizeof * 1; } else static if( __traits( compiles, ucontext_t ) ) { getcontext( &m_utxt ); m_utxt.uc_stack.ss_sp = m_pmem; m_utxt.uc_stack.ss_size = m_size; makecontext( &m_utxt, &fiber_entryPoint, 0 ); // NOTE: If ucontext is being used then the top of the stack will // be a pointer to the ucontext_t struct for that fiber. push( cast(size_t) &m_utxt ); } else static assert(0, "Not implemented"); } Thread.Context* m_ctxt; size_t m_size; void* m_pmem; static if( __traits( compiles, ucontext_t ) ) { // NOTE: The static ucontext instance is used to represent the context // of the executing thread. static ucontext_t sm_utxt = void; ucontext_t m_utxt = void; ucontext_t* m_ucur = null; } private: /////////////////////////////////////////////////////////////////////////// // Storage of Active Fiber /////////////////////////////////////////////////////////////////////////// // // Sets a thread-local reference to the current fiber object. // static void setThis( Fiber f ) nothrow @nogc { sm_this = f; } static Fiber sm_this; private: /////////////////////////////////////////////////////////////////////////// // Context Switching /////////////////////////////////////////////////////////////////////////// // // Switches into the stack held by this fiber. // final void switchIn() nothrow @nogc { Thread tobj = Thread.getThis(); void** oldp = &tobj.m_curr.tstack; void* newp = m_ctxt.tstack; // NOTE: The order of operations here is very important. The current // stack top must be stored before m_lock is set, and pushContext // must not be called until after m_lock is set. This process // is intended to prevent a race condition with the suspend // mechanism used for garbage collection. If it is not followed, // a badly timed collection could cause the GC to scan from the // bottom of one stack to the top of another, or to miss scanning // a stack that still contains valid data. The old stack pointer // oldp will be set again before the context switch to guarantee // that it points to exactly the correct stack location so the // successive pop operations will succeed. *oldp = getStackTop(); atomicStore!(MemoryOrder.raw)(*cast(shared)&tobj.m_lock, true); tobj.pushContext( m_ctxt ); fiber_switchContext( oldp, newp ); // NOTE: As above, these operations must be performed in a strict order // to prevent Bad Things from happening. tobj.popContext(); atomicStore!(MemoryOrder.raw)(*cast(shared)&tobj.m_lock, false); tobj.m_curr.tstack = tobj.m_curr.bstack; } // // Switches out of the current stack and into the enclosing stack. // final void switchOut() nothrow @nogc { Thread tobj = Thread.getThis(); void** oldp = &m_ctxt.tstack; void* newp = tobj.m_curr.within.tstack; // NOTE: The order of operations here is very important. The current // stack top must be stored before m_lock is set, and pushContext // must not be called until after m_lock is set. This process // is intended to prevent a race condition with the suspend // mechanism used for garbage collection. If it is not followed, // a badly timed collection could cause the GC to scan from the // bottom of one stack to the top of another, or to miss scanning // a stack that still contains valid data. The old stack pointer // oldp will be set again before the context switch to guarantee // that it points to exactly the correct stack location so the // successive pop operations will succeed. *oldp = getStackTop(); atomicStore!(MemoryOrder.raw)(*cast(shared)&tobj.m_lock, true); fiber_switchContext( oldp, newp ); // NOTE: As above, these operations must be performed in a strict order // to prevent Bad Things from happening. // NOTE: If use of this fiber is multiplexed across threads, the thread // executing here may be different from the one above, so get the // current thread handle before unlocking, etc. tobj = Thread.getThis(); atomicStore!(MemoryOrder.raw)(*cast(shared)&tobj.m_lock, false); tobj.m_curr.tstack = tobj.m_curr.bstack; } } version( unittest ) { class TestFiber : Fiber { this() { super(&run); } void run() { foreach(i; 0 .. 1000) { sum += i; Fiber.yield(); } } enum expSum = 1000 * 999 / 2; size_t sum; } void runTen() { TestFiber[10] fibs; foreach(ref fib; fibs) fib = new TestFiber(); bool cont; do { cont = false; foreach(fib; fibs) { if (fib.state == Fiber.State.HOLD) { fib.call(); cont |= fib.state != Fiber.State.TERM; } } } while (cont); foreach(fib; fibs) { assert(fib.sum == TestFiber.expSum); } } } // Single thread running separate fibers unittest { runTen(); } // Multiple threads running separate fibers unittest { auto group = new ThreadGroup(); foreach(_; 0 .. 4) { group.create(&runTen); } group.joinAll(); } // Multiple threads running shared fibers unittest { shared bool[10] locks; TestFiber[10] fibs; void runShared() { bool cont; do { cont = false; foreach(idx; 0 .. 10) { if (cas(&locks[idx], false, true)) { if (fibs[idx].state == Fiber.State.HOLD) { fibs[idx].call(); cont |= fibs[idx].state != Fiber.State.TERM; } locks[idx] = false; } else { cont = true; } } } while (cont); } foreach(ref fib; fibs) { fib = new TestFiber(); } auto group = new ThreadGroup(); foreach(_; 0 .. 4) { group.create(&runShared); } group.joinAll(); foreach(fib; fibs) { assert(fib.sum == TestFiber.expSum); } } // Test exception handling inside fibers. version (Win32) { // broken on win32 under windows server 2012: bug 13821 } else unittest { enum MSG = "Test message."; string caughtMsg; (new Fiber({ try { throw new Exception(MSG); } catch (Exception e) { caughtMsg = e.msg; } })).call(); assert(caughtMsg == MSG); } unittest { int x = 0; (new Fiber({ x++; })).call(); assert( x == 1 ); } nothrow unittest { new Fiber({}).call!(Fiber.Rethrow.no)(); } unittest { new Fiber({}).call(Fiber.Rethrow.yes); new Fiber({}).call(Fiber.Rethrow.no); } deprecated unittest { new Fiber({}).call(true); new Fiber({}).call(false); } version (Win32) { // broken on win32 under windows server 2012: bug 13821 } else unittest { enum MSG = "Test message."; try { (new Fiber({ throw new Exception( MSG ); })).call(); assert( false, "Expected rethrown exception." ); } catch( Throwable t ) { assert( t.msg == MSG ); } } // Test exception chaining when switching contexts in finally blocks. unittest { static void throwAndYield(string msg) { try { throw new Exception(msg); } finally { Fiber.yield(); } } static void fiber(string name) { try { try { throwAndYield(name ~ ".1"); } finally { throwAndYield(name ~ ".2"); } } catch (Exception e) { assert(e.msg == name ~ ".1"); assert(e.next); assert(e.next.msg == name ~ ".2"); assert(!e.next.next); } } auto first = new Fiber(() => fiber("first")); auto second = new Fiber(() => fiber("second")); first.call(); second.call(); first.call(); second.call(); first.call(); second.call(); assert(first.state == Fiber.State.TERM); assert(second.state == Fiber.State.TERM); } // Test Fiber resetting unittest { static string method; static void foo() { method = "foo"; } void bar() { method = "bar"; } static void expect(Fiber fib, string s) { assert(fib.state == Fiber.State.HOLD); fib.call(); assert(fib.state == Fiber.State.TERM); assert(method == s); method = null; } auto fib = new Fiber(&foo); expect(fib, "foo"); fib.reset(); expect(fib, "foo"); fib.reset(&foo); expect(fib, "foo"); fib.reset(&bar); expect(fib, "bar"); fib.reset(function void(){method = "function";}); expect(fib, "function"); fib.reset(delegate void(){method = "delegate";}); expect(fib, "delegate"); } // Test unsafe reset in hold state unittest { auto fib = new Fiber(function {ubyte[2048] buf = void; Fiber.yield();}, 4096); foreach (_; 0 .. 10) { fib.call(); assert(fib.state == Fiber.State.HOLD); fib.reset(); } } // stress testing GC stack scanning unittest { import core.memory; static void unreferencedThreadObject() { static void sleep() { Thread.sleep(dur!"msecs"(100)); } auto thread = new Thread(&sleep).start(); } unreferencedThreadObject(); GC.collect(); static class Foo { this(int value) { _value = value; } int bar() { return _value; } int _value; } static void collect() { auto foo = new Foo(2); assert(foo.bar() == 2); GC.collect(); Fiber.yield(); GC.collect(); assert(foo.bar() == 2); } auto fiber = new Fiber(&collect); fiber.call(); GC.collect(); fiber.call(); // thread reference auto foo = new Foo(2); void collect2() { assert(foo.bar() == 2); GC.collect(); Fiber.yield(); GC.collect(); assert(foo.bar() == 2); } fiber = new Fiber(&collect2); fiber.call(); GC.collect(); fiber.call(); static void recurse(size_t cnt) { --cnt; Fiber.yield(); if (cnt) { auto fib = new Fiber(() { recurse(cnt); }); fib.call(); GC.collect(); fib.call(); } } fiber = new Fiber(() { recurse(20); }); fiber.call(); } version( AsmX86_64_Windows ) { // Test Windows x64 calling convention unittest { void testNonvolatileRegister(alias REG)() { auto zeroRegister = new Fiber(() { mixin("asm pure nothrow @nogc { naked; xor "~REG~", "~REG~"; ret; }"); }); long after; mixin("asm pure nothrow @nogc { mov "~REG~", 0xFFFFFFFFFFFFFFFF; }"); zeroRegister.call(); mixin("asm pure nothrow @nogc { mov after, "~REG~"; }"); assert(after == -1); } void testNonvolatileRegisterSSE(alias REG)() { auto zeroRegister = new Fiber(() { mixin("asm pure nothrow @nogc { naked; xorpd "~REG~", "~REG~"; ret; }"); }); long[2] before = [0xFFFFFFFF_FFFFFFFF, 0xFFFFFFFF_FFFFFFFF], after; mixin("asm pure nothrow @nogc { movdqu "~REG~", before; }"); zeroRegister.call(); mixin("asm pure nothrow @nogc { movdqu after, "~REG~"; }"); assert(before == after); } testNonvolatileRegister!("R12")(); testNonvolatileRegister!("R13")(); testNonvolatileRegister!("R14")(); testNonvolatileRegister!("R15")(); testNonvolatileRegister!("RDI")(); testNonvolatileRegister!("RSI")(); testNonvolatileRegister!("RBX")(); testNonvolatileRegisterSSE!("XMM6")(); testNonvolatileRegisterSSE!("XMM7")(); testNonvolatileRegisterSSE!("XMM8")(); testNonvolatileRegisterSSE!("XMM9")(); testNonvolatileRegisterSSE!("XMM10")(); testNonvolatileRegisterSSE!("XMM11")(); testNonvolatileRegisterSSE!("XMM12")(); testNonvolatileRegisterSSE!("XMM13")(); testNonvolatileRegisterSSE!("XMM14")(); testNonvolatileRegisterSSE!("XMM15")(); } } version( D_InlineAsm_X86_64 ) { unittest { void testStackAlignment() { void* pRSP; asm pure nothrow @nogc { mov pRSP, RSP; } assert((cast(size_t)pRSP & 0xF) == 0); } auto fib = new Fiber(&testStackAlignment); fib.call(); } } // regression test for Issue 13416 version (FreeBSD) unittest { static void loop() { pthread_attr_t attr; pthread_attr_init(&attr); auto thr = pthread_self(); foreach (i; 0 .. 50) pthread_attr_get_np(thr, &attr); pthread_attr_destroy(&attr); } auto thr = new Thread(&loop).start(); foreach (i; 0 .. 50) { thread_suspendAll(); thread_resumeAll(); } thr.join(); } unittest { // use >PAGESIZE to avoid stack overflow (e.g. in an syscall) auto thr = new Thread(function{}, 4096 + 1).start(); thr.join(); } /** * Represents the ID of a thread, as returned by $(D Thread.)$(LREF id). * The exact type varies from platform to platform. */ version (Windows) alias ThreadID = uint; else version (Posix) alias ThreadID = pthread_t;
D
/Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/MySQL.build/Field+Variant.swift.o : /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Bind+Node.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Bind.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Binds.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Connection.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Database.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Error.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Field+Variant.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Field.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Fields.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/MySQL+Date.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/MySQL+Node.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.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/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/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/libc.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/JSON.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/Jay.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/Node.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/PathIndexable.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/Polymorphic.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/MySQL.build/Field+Variant~partial.swiftmodule : /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Bind+Node.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Bind.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Binds.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Connection.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Database.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Error.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Field+Variant.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Field.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Fields.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/MySQL+Date.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/MySQL+Node.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.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/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/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/libc.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/JSON.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/Jay.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/Node.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/PathIndexable.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/Polymorphic.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/MySQL.build/Field+Variant~partial.swiftdoc : /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Bind+Node.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Bind.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Binds.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Connection.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Database.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Error.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Field+Variant.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Field.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/Fields.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/MySQL+Date.swift /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/Packages/MySQL-1.1.2/Sources/MySQL/MySQL+Node.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.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/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/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/libc.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/JSON.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/Jay.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/Node.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/PathIndexable.swiftmodule /Users/okasho/serverProject/tryswift/get_post_patch_and_delate/swift/.build/debug/Polymorphic.swiftmodule
D
/home/naufil/Desktop/rust_github/hello/target/debug/deps/hello-4b7e670e43d5b4cf: src/main.rs /home/naufil/Desktop/rust_github/hello/target/debug/deps/hello-4b7e670e43d5b4cf.d: src/main.rs src/main.rs:
D
module discord.w.data; import discord.w.types; import discord.w.cache; import std.array; import std.algorithm; import std.typecons; struct GuildUserCache { Snowflake[2] guildUserID; Snowflake[] roles; Nullable!Activity game; SafeTime joinDate; PresenceUpdate.Status status; bool deaf, mute; string nick; Role[] resolveRoles() @safe { return guild.roles.filter!(a => roles.canFind(a.id)).array; } Guild guild() @safe @property { return gGuildCache.get(guildUserID[0]); } User user() @safe @property { return gUserCache.get(guildUserID[1]); } string effectiveNick() @safe @property { return nick.length ? nick : user.username; } } struct ChannelUserCache { Snowflake[2] channelUserID; SafeTime typing; } struct VoiceStateCache { VoiceState state; ref Snowflake[3] id() @property @trusted { static assert(is(typeof(VoiceState.tupleof[0]) == Snowflake)); static assert(is(typeof(VoiceState.tupleof[1]) == Snowflake)); static assert(is(typeof(VoiceState.tupleof[2]) == Snowflake)); return (cast(Snowflake*)&state)[0 .. 3]; } } __gshared auto _gUserCache = new SimpleCache!User(); __gshared auto _gGuildUserCache = new SimpleCache!(GuildUserCache, "guildUserID")(); __gshared auto _gChannelUserCache = new SimpleCache!(ChannelUserCache, "channelUserID")(); __gshared auto _gVoiceStateCache = new SimpleCache!VoiceStateCache(); __gshared auto _gChannelCache = new SimpleCache!Channel(); __gshared auto _gGuildCache = new SimpleCache!Guild(); __gshared auto _gMessageCache = new SimpleCache!(Message, "id", 16 * 1024 * 1024)(); auto gUserCache() @trusted { return _gUserCache; } auto gGuildUserCache() @trusted { return _gGuildUserCache; } auto gChannelUserCache() @trusted { return _gChannelUserCache; } auto gVoiceStateCache() @trusted { return _gVoiceStateCache; } auto gChannelCache() @trusted { return _gChannelCache; } auto gGuildCache() @trusted { return _gGuildCache; } auto gMessageCache() @trusted { return _gMessageCache; } Snowflake getGuildByChannel(Snowflake channel) @safe { return gChannelCache.get(channel).guild_id; } Permissions getUserPermissions(Snowflake guild, Snowflake channel, Snowflake user) @safe { // TODO: implement channel overwrites auto guildMember = gGuildUserCache.get([guild, user]); auto roles = guildMember.resolveRoles; Permissions ret; foreach (role; roles) ret |= cast(Permissions) role.permissions; return ret; } bool hasPermission(Permissions src, Permissions check) @safe { if (src & Permissions.ADMINISTRATOR) return true; return (src & check) != 0; }
D
/** * Windows is a registered trademark of Microsoft Corporation in the United * States and other countries. * * Copyright: Copyright Digital Mars 2000 - 2009. * License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>. * Authors: Walter Bright, Sean Kelly, Alex Rønne Petersen */ /* Copyright Digital Mars 2000 - 2009. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at * http://www.boost.org/LICENSE_1_0.txt) */ module core.sys.windows.windows; version (Windows): extern (Windows): nothrow: alias uint ULONG; alias ULONG *PULONG; alias ushort USHORT; alias USHORT *PUSHORT; alias ubyte UCHAR; alias UCHAR *PUCHAR; alias char *PSZ; alias void VOID; alias char CHAR; alias short SHORT; alias int LONG; alias long LONGLONG; alias ulong ULONGLONG; alias CHAR* LPCH, LPSTR, PCH, PSTR; alias const(CHAR)* LPCCH, LPCSTR, PCCH, PCSTR; alias wchar WCHAR; alias WCHAR* LPWCH, LPWSTR, PWCH, PWSTR; alias const(WCHAR)* LPCWCH, LPCWSTR, PCWCH, PCWSTR; alias CHAR* LPTCH, LPTSTR, PTCH, PTSTR; alias const(CHAR)* LPCTCH, LPCTSTR, PCTCH, PCTSTR; alias uint DWORD; alias ulong DWORD64; alias int BOOL; alias ubyte BYTE; alias ushort WORD; alias float FLOAT; alias FLOAT* PFLOAT; alias BOOL* LPBOOL, PBOOL; alias BYTE* LPBYTE, PBYTE; alias int* LPINT, PINT; alias WORD* LPWORD, PWORD; alias int* LPLONG; alias DWORD* LPDWORD, PDWORD; alias void* LPVOID; alias const(void)* LPCVOID; alias int INT; alias uint UINT; alias uint* PUINT; alias size_t SIZE_T; // ULONG_PTR must be able to store a pointer as an integral type version (Win64) { alias long INT_PTR; alias ulong UINT_PTR; alias long LONG_PTR; alias ulong ULONG_PTR; alias long * PINT_PTR; alias ulong * PUINT_PTR; alias long * PLONG_PTR; alias ulong * PULONG_PTR; } else // Win32 { alias int INT_PTR; alias uint UINT_PTR; alias int LONG_PTR; alias uint ULONG_PTR; alias int * PINT_PTR; alias uint * PUINT_PTR; alias int * PLONG_PTR; alias uint * PULONG_PTR; } alias ULONG_PTR DWORD_PTR; alias void *HANDLE; alias void *PVOID; alias HANDLE HGLOBAL; alias HANDLE HLOCAL; alias LONG HRESULT; alias LONG SCODE; alias HANDLE HINSTANCE; alias HINSTANCE HMODULE; alias HANDLE HWND; alias HANDLE* PHANDLE; alias HANDLE HGDIOBJ; alias HANDLE HACCEL; alias HANDLE HBITMAP; alias HANDLE HBRUSH; alias HANDLE HCOLORSPACE; alias HANDLE HDC; alias HANDLE HGLRC; alias HANDLE HDESK; alias HANDLE HENHMETAFILE; alias HANDLE HFONT; alias HANDLE HICON; alias HANDLE HMENU; alias HANDLE HMETAFILE; alias HANDLE HPALETTE; alias HANDLE HPEN; alias HANDLE HRGN; alias HANDLE HRSRC; alias HANDLE HSTR; alias HANDLE HTASK; alias HANDLE HWINSTA; alias HANDLE HKL; alias HICON HCURSOR; alias HANDLE HKEY; alias HKEY *PHKEY; alias DWORD ACCESS_MASK; alias ACCESS_MASK *PACCESS_MASK; alias ACCESS_MASK REGSAM; alias int function() FARPROC; alias UINT WPARAM; alias LONG LPARAM; alias LONG LRESULT; alias DWORD COLORREF; alias DWORD *LPCOLORREF; alias WORD ATOM; version (all) { // Properly prototyped versions alias BOOL function(HWND, UINT, WPARAM, LPARAM) DLGPROC; alias VOID function(HWND, UINT, UINT_PTR, DWORD) TIMERPROC; alias BOOL function(HDC, LPARAM, int) GRAYSTRINGPROC; alias BOOL function(HWND, LPARAM) WNDENUMPROC; alias LRESULT function(int code, WPARAM wParam, LPARAM lParam) HOOKPROC; alias VOID function(HWND, UINT, DWORD, LRESULT) SENDASYNCPROC; alias BOOL function(HWND, LPCSTR, HANDLE) PROPENUMPROCA; alias BOOL function(HWND, LPCWSTR, HANDLE) PROPENUMPROCW; alias BOOL function(HWND, LPSTR, HANDLE, DWORD) PROPENUMPROCEXA; alias BOOL function(HWND, LPWSTR, HANDLE, DWORD) PROPENUMPROCEXW; alias int function(LPSTR lpch, int ichCurrent, int cch, int code) EDITWORDBREAKPROCA; alias int function(LPWSTR lpch, int ichCurrent, int cch, int code) EDITWORDBREAKPROCW; alias BOOL function(HDC hdc, LPARAM lData, WPARAM wData, int cx, int cy) DRAWSTATEPROC; } else { alias FARPROC DLGPROC; alias FARPROC TIMERPROC; alias FARPROC GRAYSTRINGPROC; alias FARPROC WNDENUMPROC; alias FARPROC HOOKPROC; alias FARPROC SENDASYNCPROC; alias FARPROC EDITWORDBREAKPROCA; alias FARPROC EDITWORDBREAKPROCW; alias FARPROC PROPENUMPROCA; alias FARPROC PROPENUMPROCW; alias FARPROC PROPENUMPROCEXA; alias FARPROC PROPENUMPROCEXW; alias FARPROC DRAWSTATEPROC; } extern (D) pure { WORD HIWORD(int l) { return cast(WORD)((l >> 16) & 0xFFFF); } WORD LOWORD(int l) { return cast(WORD)l; } bool FAILED(int status) { return status < 0; } bool SUCCEEDED(int Status) { return Status >= 0; } } enum : int { FALSE = 0, TRUE = 1, } enum : uint { MAX_PATH = 260, HINSTANCE_ERROR = 32, } enum { ERROR_SUCCESS = 0, ERROR_INVALID_FUNCTION = 1, ERROR_FILE_NOT_FOUND = 2, ERROR_PATH_NOT_FOUND = 3, ERROR_TOO_MANY_OPEN_FILES = 4, ERROR_ACCESS_DENIED = 5, ERROR_INVALID_HANDLE = 6, ERROR_NO_MORE_FILES = 18, ERROR_MORE_DATA = 234, ERROR_NO_MORE_ITEMS = 259, } enum { DLL_PROCESS_ATTACH = 1, DLL_THREAD_ATTACH = 2, DLL_THREAD_DETACH = 3, DLL_PROCESS_DETACH = 0, } enum { FILE_BEGIN = 0, FILE_CURRENT = 1, FILE_END = 2, } enum : uint { DELETE = 0x00010000, READ_CONTROL = 0x00020000, WRITE_DAC = 0x00040000, WRITE_OWNER = 0x00080000, SYNCHRONIZE = 0x00100000, STANDARD_RIGHTS_REQUIRED = 0x000F0000, STANDARD_RIGHTS_READ = READ_CONTROL, STANDARD_RIGHTS_WRITE = READ_CONTROL, STANDARD_RIGHTS_EXECUTE = READ_CONTROL, STANDARD_RIGHTS_ALL = 0x001F0000, SPECIFIC_RIGHTS_ALL = 0x0000FFFF, ACCESS_SYSTEM_SECURITY = 0x01000000, MAXIMUM_ALLOWED = 0x02000000, GENERIC_READ = 0x80000000, GENERIC_WRITE = 0x40000000, GENERIC_EXECUTE = 0x20000000, GENERIC_ALL = 0x10000000, } enum { FILE_SHARE_READ = 0x00000001, FILE_SHARE_WRITE = 0x00000002, FILE_SHARE_DELETE = 0x00000004, FILE_ATTRIBUTE_READONLY = 0x00000001, FILE_ATTRIBUTE_HIDDEN = 0x00000002, FILE_ATTRIBUTE_SYSTEM = 0x00000004, FILE_ATTRIBUTE_DIRECTORY = 0x00000010, FILE_ATTRIBUTE_ARCHIVE = 0x00000020, FILE_ATTRIBUTE_NORMAL = 0x00000080, FILE_ATTRIBUTE_TEMPORARY = 0x00000100, FILE_ATTRIBUTE_COMPRESSED = 0x00000800, FILE_ATTRIBUTE_OFFLINE = 0x00001000, FILE_NOTIFY_CHANGE_FILE_NAME = 0x00000001, FILE_NOTIFY_CHANGE_DIR_NAME = 0x00000002, FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x00000004, FILE_NOTIFY_CHANGE_SIZE = 0x00000008, FILE_NOTIFY_CHANGE_LAST_WRITE = 0x00000010, FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x00000020, FILE_NOTIFY_CHANGE_CREATION = 0x00000040, FILE_NOTIFY_CHANGE_SECURITY = 0x00000100, FILE_ACTION_ADDED = 0x00000001, FILE_ACTION_REMOVED = 0x00000002, FILE_ACTION_MODIFIED = 0x00000003, FILE_ACTION_RENAMED_OLD_NAME = 0x00000004, FILE_ACTION_RENAMED_NEW_NAME = 0x00000005, FILE_CASE_SENSITIVE_SEARCH = 0x00000001, FILE_CASE_PRESERVED_NAMES = 0x00000002, FILE_UNICODE_ON_DISK = 0x00000004, FILE_PERSISTENT_ACLS = 0x00000008, FILE_FILE_COMPRESSION = 0x00000010, FILE_VOLUME_IS_COMPRESSED = 0x00008000, } enum : DWORD { MAILSLOT_NO_MESSAGE = cast(DWORD)-1, MAILSLOT_WAIT_FOREVER = cast(DWORD)-1, } enum : uint { FILE_FLAG_WRITE_THROUGH = 0x80000000, FILE_FLAG_OVERLAPPED = 0x40000000, FILE_FLAG_NO_BUFFERING = 0x20000000, FILE_FLAG_RANDOM_ACCESS = 0x10000000, FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000, FILE_FLAG_DELETE_ON_CLOSE = 0x04000000, FILE_FLAG_BACKUP_SEMANTICS = 0x02000000, FILE_FLAG_POSIX_SEMANTICS = 0x01000000, } enum { CREATE_NEW = 1, CREATE_ALWAYS = 2, OPEN_EXISTING = 3, OPEN_ALWAYS = 4, TRUNCATE_EXISTING = 5, } enum { HANDLE INVALID_HANDLE_VALUE = cast(HANDLE)-1, DWORD INVALID_SET_FILE_POINTER = cast(DWORD)-1, DWORD INVALID_FILE_SIZE = cast(DWORD)0xFFFFFFFF, } union LARGE_INTEGER { struct { uint LowPart; int HighPart; } long QuadPart; } alias LARGE_INTEGER* PLARGE_INTEGER; union ULARGE_INTEGER { struct { uint LowPart; uint HighPart; } ulong QuadPart; } alias ULARGE_INTEGER* PULARGE_INTEGER; struct OVERLAPPED { ULONG_PTR Internal; ULONG_PTR InternalHigh; union { struct { DWORD Offset; DWORD OffsetHigh; } void* Pointer; } HANDLE hEvent; } struct SECURITY_ATTRIBUTES { DWORD nLength; void *lpSecurityDescriptor; BOOL bInheritHandle; } alias SECURITY_ATTRIBUTES* PSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES; struct FILETIME { DWORD dwLowDateTime; DWORD dwHighDateTime; } alias FILETIME* PFILETIME, LPFILETIME; struct WIN32_FIND_DATA { DWORD dwFileAttributes; FILETIME ftCreationTime; FILETIME ftLastAccessTime; FILETIME ftLastWriteTime; DWORD nFileSizeHigh; DWORD nFileSizeLow; DWORD dwReserved0; DWORD dwReserved1; char cFileName[MAX_PATH]; char cAlternateFileName[ 14 ]; } struct WIN32_FIND_DATAW { DWORD dwFileAttributes; FILETIME ftCreationTime; FILETIME ftLastAccessTime; FILETIME ftLastWriteTime; DWORD nFileSizeHigh; DWORD nFileSizeLow; DWORD dwReserved0; DWORD dwReserved1; wchar cFileName[ 260 ]; wchar cAlternateFileName[ 14 ]; } // Critical Section struct _LIST_ENTRY { _LIST_ENTRY *Flink; _LIST_ENTRY *Blink; } alias _LIST_ENTRY LIST_ENTRY; struct _RTL_CRITICAL_SECTION_DEBUG { WORD Type; WORD CreatorBackTraceIndex; _RTL_CRITICAL_SECTION *CriticalSection; LIST_ENTRY ProcessLocksList; DWORD EntryCount; DWORD ContentionCount; DWORD Spare[ 2 ]; } alias _RTL_CRITICAL_SECTION_DEBUG RTL_CRITICAL_SECTION_DEBUG; struct _RTL_CRITICAL_SECTION { RTL_CRITICAL_SECTION_DEBUG * DebugInfo; // // The following three fields control entering and exiting the critical // section for the resource // LONG LockCount; LONG RecursionCount; HANDLE OwningThread; // from the thread's ClientId->UniqueThread HANDLE LockSemaphore; ULONG_PTR SpinCount; // force size on 64-bit systems when packed } alias _RTL_CRITICAL_SECTION CRITICAL_SECTION; enum { STD_INPUT_HANDLE = cast(DWORD)-10, STD_OUTPUT_HANDLE = cast(DWORD)-11, STD_ERROR_HANDLE = cast(DWORD)-12, } enum GET_FILEEX_INFO_LEVELS { GetFileExInfoStandard, GetFileExMaxInfoLevel } struct WIN32_FILE_ATTRIBUTE_DATA { DWORD dwFileAttributes; FILETIME ftCreationTime; FILETIME ftLastAccessTime; FILETIME ftLastWriteTime; DWORD nFileSizeHigh; DWORD nFileSizeLow; } alias WIN32_FILE_ATTRIBUTE_DATA* LPWIN32_FILE_ATTRIBUTE_DATA; export { BOOL SetCurrentDirectoryA(LPCSTR lpPathName); BOOL SetCurrentDirectoryW(LPCWSTR lpPathName); UINT GetSystemDirectoryA(LPSTR lpBuffer, UINT uSize); UINT GetSystemDirectoryW(LPWSTR lpBuffer, UINT uSize); DWORD GetCurrentDirectoryA(DWORD nBufferLength, LPSTR lpBuffer); DWORD GetCurrentDirectoryW(DWORD nBufferLength, LPWSTR lpBuffer); BOOL CreateDirectoryA(LPCSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes); BOOL CreateDirectoryW(LPCWSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes); BOOL CreateDirectoryExA(LPCSTR lpTemplateDirectory, LPCSTR lpNewDirectory, LPSECURITY_ATTRIBUTES lpSecurityAttributes); BOOL CreateDirectoryExW(LPCWSTR lpTemplateDirectory, LPCWSTR lpNewDirectory, LPSECURITY_ATTRIBUTES lpSecurityAttributes); BOOL RemoveDirectoryA(LPCSTR lpPathName); BOOL RemoveDirectoryW(LPCWSTR lpPathName); BOOL CloseHandle(HANDLE hObject); HANDLE CreateFileA(in char* lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, SECURITY_ATTRIBUTES *lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile); HANDLE CreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, SECURITY_ATTRIBUTES *lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile); BOOL DeleteFileA(in char *lpFileName); BOOL DeleteFileW(LPCWSTR lpFileName); BOOL FindClose(HANDLE hFindFile); HANDLE FindFirstFileA(in char *lpFileName, WIN32_FIND_DATA* lpFindFileData); HANDLE FindFirstFileW(in LPCWSTR lpFileName, WIN32_FIND_DATAW* lpFindFileData); BOOL FindNextFileA(HANDLE hFindFile, WIN32_FIND_DATA* lpFindFileData); BOOL FindNextFileW(HANDLE hFindFile, WIN32_FIND_DATAW* lpFindFileData); BOOL GetExitCodeThread(HANDLE hThread, DWORD *lpExitCode); BOOL GetExitCodeProcess(HANDLE hProcess, DWORD *lpExitCode); DWORD GetLastError(); DWORD GetFileAttributesA(in char *lpFileName); DWORD GetFileAttributesW(in wchar *lpFileName); BOOL GetFileAttributesExA(LPCSTR, GET_FILEEX_INFO_LEVELS, PVOID); BOOL GetFileAttributesExW(LPCWSTR, GET_FILEEX_INFO_LEVELS, PVOID); DWORD GetFileSize(HANDLE hFile, DWORD *lpFileSizeHigh); BOOL CopyFileA(LPCSTR lpExistingFileName, LPCSTR lpNewFileName, BOOL bFailIfExists); BOOL CopyFileW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName, BOOL bFailIfExists); BOOL MoveFileA(in char *from, in char *to); BOOL MoveFileW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName); BOOL ReadFile(HANDLE hFile, void *lpBuffer, DWORD nNumberOfBytesToRead, DWORD *lpNumberOfBytesRead, OVERLAPPED *lpOverlapped); DWORD SetFilePointer(HANDLE hFile, LONG lDistanceToMove, LONG *lpDistanceToMoveHigh, DWORD dwMoveMethod); BOOL WriteFile(HANDLE hFile, in void *lpBuffer, DWORD nNumberOfBytesToWrite, DWORD *lpNumberOfBytesWritten, OVERLAPPED *lpOverlapped); DWORD GetModuleFileNameA(HMODULE hModule, LPSTR lpFilename, DWORD nSize); DWORD GetModuleFileNameW(HMODULE hModule, LPWSTR lpFilename, DWORD nSize); HANDLE GetStdHandle(DWORD nStdHandle); BOOL SetStdHandle(DWORD nStdHandle, HANDLE hHandle); } struct MEMORYSTATUS { DWORD dwLength; DWORD dwMemoryLoad; DWORD dwTotalPhys; DWORD dwAvailPhys; DWORD dwTotalPageFile; DWORD dwAvailPageFile; DWORD dwTotalVirtual; DWORD dwAvailVirtual; }; alias MEMORYSTATUS *LPMEMORYSTATUS; HMODULE LoadLibraryA(LPCSTR lpLibFileName); HMODULE LoadLibraryW(LPCWSTR lpLibFileName); FARPROC GetProcAddress(HMODULE hModule, LPCSTR lpProcName); DWORD GetVersion(); BOOL FreeLibrary(HMODULE hLibModule); void FreeLibraryAndExitThread(HMODULE hLibModule, DWORD dwExitCode); BOOL DisableThreadLibraryCalls(HMODULE hLibModule); // // Registry Specific Access Rights. // enum { KEY_QUERY_VALUE = 0x0001, KEY_SET_VALUE = 0x0002, KEY_CREATE_SUB_KEY = 0x0004, KEY_ENUMERATE_SUB_KEYS = 0x0008, KEY_NOTIFY = 0x0010, KEY_CREATE_LINK = 0x0020, KEY_READ = cast(int)((STANDARD_RIGHTS_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY) & ~SYNCHRONIZE), KEY_WRITE = cast(int)((STANDARD_RIGHTS_WRITE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY) & ~SYNCHRONIZE), KEY_EXECUTE = cast(int)(KEY_READ & ~SYNCHRONIZE), KEY_ALL_ACCESS = cast(int)((STANDARD_RIGHTS_ALL | KEY_QUERY_VALUE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY | KEY_CREATE_LINK) & ~SYNCHRONIZE), } // // Key creation/open disposition // enum : int { REG_CREATED_NEW_KEY = 0x00000001, // New Registry Key created REG_OPENED_EXISTING_KEY = 0x00000002, // Existing Key opened } // // // Predefined Value Types. // enum { REG_NONE = 0, // No value type REG_SZ = 1, // Unicode nul terminated string REG_EXPAND_SZ = 2, // Unicode nul terminated string // (with environment variable references) REG_BINARY = 3, // Free form binary REG_DWORD = 4, // 32-bit number REG_DWORD_LITTLE_ENDIAN = 4, // 32-bit number (same as REG_DWORD) REG_DWORD_BIG_ENDIAN = 5, // 32-bit number REG_LINK = 6, // Symbolic Link (unicode) REG_MULTI_SZ = 7, // Multiple Unicode strings REG_RESOURCE_LIST = 8, // Resource list in the resource map REG_FULL_RESOURCE_DESCRIPTOR = 9, // Resource list in the hardware description REG_RESOURCE_REQUIREMENTS_LIST = 10, REG_QWORD = 11, REG_QWORD_LITTLE_ENDIAN = 11, } /* * MessageBox() Flags */ enum { MB_OK = 0x00000000, MB_OKCANCEL = 0x00000001, MB_ABORTRETRYIGNORE = 0x00000002, MB_YESNOCANCEL = 0x00000003, MB_YESNO = 0x00000004, MB_RETRYCANCEL = 0x00000005, MB_ICONHAND = 0x00000010, MB_ICONQUESTION = 0x00000020, MB_ICONEXCLAMATION = 0x00000030, MB_ICONASTERISK = 0x00000040, MB_USERICON = 0x00000080, MB_ICONWARNING = MB_ICONEXCLAMATION, MB_ICONERROR = MB_ICONHAND, MB_ICONINFORMATION = MB_ICONASTERISK, MB_ICONSTOP = MB_ICONHAND, MB_DEFBUTTON1 = 0x00000000, MB_DEFBUTTON2 = 0x00000100, MB_DEFBUTTON3 = 0x00000200, MB_DEFBUTTON4 = 0x00000300, MB_APPLMODAL = 0x00000000, MB_SYSTEMMODAL = 0x00001000, MB_TASKMODAL = 0x00002000, MB_HELP = 0x00004000, // Help Button MB_NOFOCUS = 0x00008000, MB_SETFOREGROUND = 0x00010000, MB_DEFAULT_DESKTOP_ONLY = 0x00020000, MB_TOPMOST = 0x00040000, MB_RIGHT = 0x00080000, MB_RTLREADING = 0x00100000, MB_TYPEMASK = 0x0000000F, MB_ICONMASK = 0x000000F0, MB_DEFMASK = 0x00000F00, MB_MODEMASK = 0x00003000, MB_MISCMASK = 0x0000C000, } int MessageBoxA(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType); int MessageBoxW(HWND hWnd, LPCWSTR lpText, LPCWSTR lpCaption, UINT uType); int MessageBoxExA(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType, WORD wLanguageId); int MessageBoxExW(HWND hWnd, LPCWSTR lpText, LPCWSTR lpCaption, UINT uType, WORD wLanguageId); enum : HKEY { HKEY_CLASSES_ROOT = cast(HKEY)(0x80000000), HKEY_CURRENT_USER = cast(HKEY)(0x80000001), HKEY_LOCAL_MACHINE = cast(HKEY)(0x80000002), HKEY_USERS = cast(HKEY)(0x80000003), HKEY_PERFORMANCE_DATA = cast(HKEY)(0x80000004), HKEY_PERFORMANCE_TEXT = cast(HKEY)(0x80000050), HKEY_PERFORMANCE_NLSTEXT = cast(HKEY)(0x80000060), HKEY_CURRENT_CONFIG = cast(HKEY)(0x80000005), HKEY_DYN_DATA = cast(HKEY)(0x80000006), } enum { REG_OPTION_RESERVED = (0x00000000), // Parameter is reserved REG_OPTION_NON_VOLATILE = (0x00000000), // Key is preserved // when system is rebooted REG_OPTION_VOLATILE = (0x00000001), // Key is not preserved // when system is rebooted REG_OPTION_CREATE_LINK = (0x00000002), // Created key is a // symbolic link REG_OPTION_BACKUP_RESTORE = (0x00000004), // open for backup or restore // special access rules // privilege required REG_OPTION_OPEN_LINK = (0x00000008), // Open symbolic link REG_LEGAL_OPTION = (REG_OPTION_RESERVED | REG_OPTION_NON_VOLATILE | REG_OPTION_VOLATILE | REG_OPTION_CREATE_LINK | REG_OPTION_BACKUP_RESTORE | REG_OPTION_OPEN_LINK), } export LONG RegDeleteKeyA(in HKEY hKey, LPCSTR lpSubKey); export LONG RegDeleteKeyW(in HKEY hKey, LPCWSTR lpSubKey); export LONG RegDeleteValueA(in HKEY hKey, LPCSTR lpValueName); export LONG RegDeleteValueW(in HKEY hKey, LPCWSTR lpValueName); export LONG RegEnumKeyExA(in HKEY hKey, DWORD dwIndex, LPSTR lpName, LPDWORD lpcbName, LPDWORD lpReserved, LPSTR lpClass, LPDWORD lpcbClass, FILETIME* lpftLastWriteTime); export LONG RegEnumKeyExW(in HKEY hKey, DWORD dwIndex, LPWSTR lpName, LPDWORD lpcbName, LPDWORD lpReserved, LPWSTR lpClass, LPDWORD lpcbClass, FILETIME* lpftLastWriteTime); export LONG RegEnumValueA(in HKEY hKey, DWORD dwIndex, LPSTR lpValueName, LPDWORD lpcbValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData); export LONG RegEnumValueW(in HKEY hKey, DWORD dwIndex, LPWSTR lpValueName, LPDWORD lpcbValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData); export LONG RegCloseKey(in HKEY hKey); export LONG RegFlushKey(in HKEY hKey); export LONG RegOpenKeyA(in HKEY hKey, LPCSTR lpSubKey, PHKEY phkResult); export LONG RegOpenKeyW(in HKEY hKey, LPCWSTR lpSubKey, PHKEY phkResult); export LONG RegOpenKeyExA(in HKEY hKey, LPCSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult); export LONG RegOpenKeyExW(in HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult); export LONG RegQueryInfoKeyA(in HKEY hKey, LPSTR lpClass, LPDWORD lpcbClass, LPDWORD lpReserved, LPDWORD lpcSubKeys, LPDWORD lpcbMaxSubKeyLen, LPDWORD lpcbMaxClassLen, LPDWORD lpcValues, LPDWORD lpcbMaxValueNameLen, LPDWORD lpcbMaxValueLen, LPDWORD lpcbSecurityDescriptor, PFILETIME lpftLastWriteTime); export LONG RegQueryInfoKeyW(in HKEY hKey, LPWSTR lpClass, LPDWORD lpcbClass, LPDWORD lpReserved, LPDWORD lpcSubKeys, LPDWORD lpcbMaxSubKeyLen, LPDWORD lpcbMaxClassLen, LPDWORD lpcValues, LPDWORD lpcbMaxValueNameLen, LPDWORD lpcbMaxValueLen, LPDWORD lpcbSecurityDescriptor, PFILETIME lpftLastWriteTime); export LONG RegQueryValueA(in HKEY hKey, LPCSTR lpSubKey, LPSTR lpValue, LPLONG lpcbValue); export LONG RegQueryValueW(in HKEY hKey, LPCWSTR lpSubKey, LPWSTR lpValue, LPLONG lpcbValue); export LONG RegQueryValueExA(in HKEY hKey, LPCSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPVOID lpData, LPDWORD lpcbData); export LONG RegQueryValueExW(in HKEY hKey, LPCWSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPVOID lpData, LPDWORD lpcbData); export LONG RegCreateKeyExA(in HKEY hKey, LPCSTR lpSubKey, DWORD Reserved, LPSTR lpClass, DWORD dwOptions, REGSAM samDesired, SECURITY_ATTRIBUTES* lpSecurityAttributes, PHKEY phkResult, LPDWORD lpdwDisposition); export LONG RegCreateKeyExW(in HKEY hKey, LPCWSTR lpSubKey, DWORD Reserved, LPWSTR lpClass, DWORD dwOptions, REGSAM samDesired, SECURITY_ATTRIBUTES* lpSecurityAttributes, PHKEY phkResult, LPDWORD lpdwDisposition); export LONG RegSetValueExA(in HKEY hKey, LPCSTR lpValueName, DWORD Reserved, DWORD dwType, BYTE* lpData, DWORD cbData); export LONG RegSetValueExW(in HKEY hKey, LPCWSTR lpValueName, DWORD Reserved, DWORD dwType, BYTE* lpData, DWORD cbData); export LONG RegOpenCurrentUser(REGSAM samDesired, PHKEY phkResult); export LONG RegConnectRegistryA(LPCSTR lpMachineName, HKEY hKey, PHKEY phkResult); export LONG RegConnectRegistryW(LPCWSTR lpMachineName, HKEY hKey, PHKEY phkResult); struct MEMORY_BASIC_INFORMATION { PVOID BaseAddress; PVOID AllocationBase; DWORD AllocationProtect; DWORD RegionSize; DWORD State; DWORD Protect; DWORD Type; } alias MEMORY_BASIC_INFORMATION* PMEMORY_BASIC_INFORMATION; enum { SECTION_QUERY = 0x0001, SECTION_MAP_WRITE = 0x0002, SECTION_MAP_READ = 0x0004, SECTION_MAP_EXECUTE = 0x0008, SECTION_EXTEND_SIZE = 0x0010, SECTION_ALL_ACCESS = cast(int)(STANDARD_RIGHTS_REQUIRED|SECTION_QUERY| SECTION_MAP_WRITE | SECTION_MAP_READ | SECTION_MAP_EXECUTE | SECTION_EXTEND_SIZE), PAGE_NOACCESS = 0x01, PAGE_READONLY = 0x02, PAGE_READWRITE = 0x04, PAGE_WRITECOPY = 0x08, PAGE_EXECUTE = 0x10, PAGE_EXECUTE_READ = 0x20, PAGE_EXECUTE_READWRITE = 0x40, PAGE_EXECUTE_WRITECOPY = 0x80, PAGE_GUARD = 0x100, PAGE_NOCACHE = 0x200, MEM_COMMIT = 0x1000, MEM_RESERVE = 0x2000, MEM_DECOMMIT = 0x4000, MEM_RELEASE = 0x8000, MEM_FREE = 0x10000, MEM_PRIVATE = 0x20000, MEM_MAPPED = 0x40000, MEM_RESET = 0x80000, MEM_TOP_DOWN = 0x100000, SEC_FILE = 0x800000, SEC_IMAGE = 0x1000000, SEC_RESERVE = 0x4000000, SEC_COMMIT = 0x8000000, SEC_NOCACHE = 0x10000000, MEM_IMAGE = SEC_IMAGE, } enum { FILE_MAP_COPY = SECTION_QUERY, FILE_MAP_WRITE = SECTION_MAP_WRITE, FILE_MAP_READ = SECTION_MAP_READ, FILE_MAP_ALL_ACCESS = SECTION_ALL_ACCESS, } // // Define access rights to files and directories // // // The FILE_READ_DATA and FILE_WRITE_DATA constants are also defined in // devioctl.h as FILE_READ_ACCESS and FILE_WRITE_ACCESS. The values for these // constants *MUST* always be in sync. // The values are redefined in devioctl.h because they must be available to // both DOS and NT. // enum { FILE_READ_DATA = ( 0x0001 ), // file & pipe FILE_LIST_DIRECTORY = ( 0x0001 ), // directory FILE_WRITE_DATA = ( 0x0002 ), // file & pipe FILE_ADD_FILE = ( 0x0002 ), // directory FILE_APPEND_DATA = ( 0x0004 ), // file FILE_ADD_SUBDIRECTORY = ( 0x0004 ), // directory FILE_CREATE_PIPE_INSTANCE = ( 0x0004 ), // named pipe FILE_READ_EA = ( 0x0008 ), // file & directory FILE_WRITE_EA = ( 0x0010 ), // file & directory FILE_EXECUTE = ( 0x0020 ), // file FILE_TRAVERSE = ( 0x0020 ), // directory FILE_DELETE_CHILD = ( 0x0040 ), // directory FILE_READ_ATTRIBUTES = ( 0x0080 ), // all FILE_WRITE_ATTRIBUTES = ( 0x0100 ), // all FILE_ALL_ACCESS = cast(int)(STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1FF), FILE_GENERIC_READ = cast(int)(STANDARD_RIGHTS_READ | FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE), FILE_GENERIC_WRITE = cast(int)(STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE), FILE_GENERIC_EXECUTE = cast(int)(STANDARD_RIGHTS_EXECUTE | FILE_READ_ATTRIBUTES | FILE_EXECUTE | SYNCHRONIZE), } export { BOOL FreeResource(HGLOBAL hResData); LPVOID LockResource(HGLOBAL hResData); BOOL GlobalUnlock(HGLOBAL hMem); HGLOBAL GlobalFree(HGLOBAL hMem); UINT GlobalCompact(DWORD dwMinFree); void GlobalFix(HGLOBAL hMem); void GlobalUnfix(HGLOBAL hMem); LPVOID GlobalWire(HGLOBAL hMem); BOOL GlobalUnWire(HGLOBAL hMem); void GlobalMemoryStatus(LPMEMORYSTATUS lpBuffer); HLOCAL LocalAlloc(UINT uFlags, UINT uBytes); HLOCAL LocalReAlloc(HLOCAL hMem, UINT uBytes, UINT uFlags); LPVOID LocalLock(HLOCAL hMem); HLOCAL LocalHandle(LPCVOID pMem); BOOL LocalUnlock(HLOCAL hMem); UINT LocalSize(HLOCAL hMem); UINT LocalFlags(HLOCAL hMem); HLOCAL LocalFree(HLOCAL hMem); UINT LocalShrink(HLOCAL hMem, UINT cbNewSize); UINT LocalCompact(UINT uMinFree); BOOL FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, DWORD dwSize); LPVOID VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); BOOL VirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType); BOOL VirtualProtect(LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect); SIZE_T VirtualQuery(LPCVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwLength); LPVOID VirtualAllocEx(HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); BOOL VirtualFreeEx(HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType); BOOL VirtualProtectEx(HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect); SIZE_T VirtualQueryEx(HANDLE hProcess, LPCVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwLength); } struct SYSTEMTIME { WORD wYear; WORD wMonth; WORD wDayOfWeek; WORD wDay; WORD wHour; WORD wMinute; WORD wSecond; WORD wMilliseconds; } struct TIME_ZONE_INFORMATION { LONG Bias; WCHAR StandardName[ 32 ]; SYSTEMTIME StandardDate; LONG StandardBias; WCHAR DaylightName[ 32 ]; SYSTEMTIME DaylightDate; LONG DaylightBias; } struct REG_TZI_FORMAT { LONG Bias; LONG StandardBias; LONG DaylightBias; SYSTEMTIME StandardDate; SYSTEMTIME DaylightDate; } enum { TIME_ZONE_ID_UNKNOWN = 0, TIME_ZONE_ID_STANDARD = 1, TIME_ZONE_ID_DAYLIGHT = 2, } export void GetSystemTime(SYSTEMTIME* lpSystemTime); export BOOL GetFileTime(HANDLE hFile, FILETIME *lpCreationTime, FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime); export void GetSystemTimeAsFileTime(FILETIME* lpSystemTimeAsFileTime); export BOOL SetSystemTime(SYSTEMTIME* lpSystemTime); export BOOL SetFileTime(HANDLE hFile, in FILETIME *lpCreationTime, in FILETIME *lpLastAccessTime, in FILETIME *lpLastWriteTime); export void GetLocalTime(SYSTEMTIME* lpSystemTime); export BOOL SetLocalTime(SYSTEMTIME* lpSystemTime); export BOOL SystemTimeToTzSpecificLocalTime(TIME_ZONE_INFORMATION* lpTimeZoneInformation, SYSTEMTIME* lpUniversalTime, SYSTEMTIME* lpLocalTime); export BOOL TzSpecificLocalTimeToSystemTime(TIME_ZONE_INFORMATION* lpTimeZoneInformation, SYSTEMTIME* lpLocalTime, SYSTEMTIME* lpUniversalTime); export DWORD GetTimeZoneInformation(TIME_ZONE_INFORMATION* lpTimeZoneInformation); export BOOL SetTimeZoneInformation(TIME_ZONE_INFORMATION* lpTimeZoneInformation); export BOOL SystemTimeToFileTime(in SYSTEMTIME *lpSystemTime, FILETIME* lpFileTime); export BOOL FileTimeToLocalFileTime(in FILETIME *lpFileTime, FILETIME* lpLocalFileTime); export BOOL LocalFileTimeToFileTime(in FILETIME *lpLocalFileTime, FILETIME* lpFileTime); export BOOL FileTimeToSystemTime(in FILETIME *lpFileTime, SYSTEMTIME* lpSystemTime); export LONG CompareFileTime(in FILETIME *lpFileTime1, in FILETIME *lpFileTime2); export BOOL FileTimeToDosDateTime(in FILETIME *lpFileTime, WORD* lpFatDate, WORD* lpFatTime); export BOOL DosDateTimeToFileTime(WORD wFatDate, WORD wFatTime, FILETIME* lpFileTime); export DWORD GetTickCount(); export BOOL SetSystemTimeAdjustment(DWORD dwTimeAdjustment, BOOL bTimeAdjustmentDisabled); export BOOL GetSystemTimeAdjustment(DWORD* lpTimeAdjustment, DWORD* lpTimeIncrement, BOOL* lpTimeAdjustmentDisabled); export DWORD FormatMessageA(DWORD dwFlags, LPCVOID lpSource, DWORD dwMessageId, DWORD dwLanguageId, LPSTR lpBuffer, DWORD nSize, void* *Arguments); export DWORD FormatMessageW(DWORD dwFlags, LPCVOID lpSource, DWORD dwMessageId, DWORD dwLanguageId, LPWSTR lpBuffer, DWORD nSize, void* *Arguments); enum { FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100, FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200, FORMAT_MESSAGE_FROM_STRING = 0x00000400, FORMAT_MESSAGE_FROM_HMODULE = 0x00000800, FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000, FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000, FORMAT_MESSAGE_MAX_WIDTH_MASK = 0x000000FF, }; // // Language IDs. // // The following two combinations of primary language ID and // sublanguage ID have special semantics: // // Primary Language ID Sublanguage ID Result // ------------------- --------------- ------------------------ // LANG_NEUTRAL SUBLANG_NEUTRAL Language neutral // LANG_NEUTRAL SUBLANG_DEFAULT User default language // LANG_NEUTRAL SUBLANG_SYS_DEFAULT System default language // // // Primary language IDs. // enum { LANG_NEUTRAL = 0x00, LANG_AFRIKAANS = 0x36, LANG_ALBANIAN = 0x1c, LANG_ARABIC = 0x01, LANG_BASQUE = 0x2d, LANG_BELARUSIAN = 0x23, LANG_BULGARIAN = 0x02, LANG_CATALAN = 0x03, LANG_CHINESE = 0x04, LANG_CROATIAN = 0x1a, LANG_CZECH = 0x05, LANG_DANISH = 0x06, LANG_DUTCH = 0x13, LANG_ENGLISH = 0x09, LANG_ESTONIAN = 0x25, LANG_FAEROESE = 0x38, LANG_FARSI = 0x29, LANG_FINNISH = 0x0b, LANG_FRENCH = 0x0c, LANG_GERMAN = 0x07, LANG_GREEK = 0x08, LANG_HEBREW = 0x0d, LANG_HUNGARIAN = 0x0e, LANG_ICELANDIC = 0x0f, LANG_INDONESIAN = 0x21, LANG_ITALIAN = 0x10, LANG_JAPANESE = 0x11, LANG_KOREAN = 0x12, LANG_LATVIAN = 0x26, LANG_LITHUANIAN = 0x27, LANG_NORWEGIAN = 0x14, LANG_POLISH = 0x15, LANG_PORTUGUESE = 0x16, LANG_ROMANIAN = 0x18, LANG_RUSSIAN = 0x19, LANG_SERBIAN = 0x1a, LANG_SLOVAK = 0x1b, LANG_SLOVENIAN = 0x24, LANG_SPANISH = 0x0a, LANG_SWEDISH = 0x1d, LANG_THAI = 0x1e, LANG_TURKISH = 0x1f, LANG_UKRAINIAN = 0x22, LANG_VIETNAMESE = 0x2a, } // // Sublanguage IDs. // // The name immediately following SUBLANG_ dictates which primary // language ID that sublanguage ID can be combined with to form a // valid language ID. // enum { SUBLANG_NEUTRAL = 0x00, // language neutral SUBLANG_DEFAULT = 0x01, // user default SUBLANG_SYS_DEFAULT = 0x02, // system default SUBLANG_ARABIC_SAUDI_ARABIA = 0x01, // Arabic (Saudi Arabia) SUBLANG_ARABIC_IRAQ = 0x02, // Arabic (Iraq) SUBLANG_ARABIC_EGYPT = 0x03, // Arabic (Egypt) SUBLANG_ARABIC_LIBYA = 0x04, // Arabic (Libya) SUBLANG_ARABIC_ALGERIA = 0x05, // Arabic (Algeria) SUBLANG_ARABIC_MOROCCO = 0x06, // Arabic (Morocco) SUBLANG_ARABIC_TUNISIA = 0x07, // Arabic (Tunisia) SUBLANG_ARABIC_OMAN = 0x08, // Arabic (Oman) SUBLANG_ARABIC_YEMEN = 0x09, // Arabic (Yemen) SUBLANG_ARABIC_SYRIA = 0x0a, // Arabic (Syria) SUBLANG_ARABIC_JORDAN = 0x0b, // Arabic (Jordan) SUBLANG_ARABIC_LEBANON = 0x0c, // Arabic (Lebanon) SUBLANG_ARABIC_KUWAIT = 0x0d, // Arabic (Kuwait) SUBLANG_ARABIC_UAE = 0x0e, // Arabic (U.A.E) SUBLANG_ARABIC_BAHRAIN = 0x0f, // Arabic (Bahrain) SUBLANG_ARABIC_QATAR = 0x10, // Arabic (Qatar) SUBLANG_CHINESE_TRADITIONAL = 0x01, // Chinese (Taiwan) SUBLANG_CHINESE_SIMPLIFIED = 0x02, // Chinese (PR China) SUBLANG_CHINESE_HONGKONG = 0x03, // Chinese (Hong Kong) SUBLANG_CHINESE_SINGAPORE = 0x04, // Chinese (Singapore) SUBLANG_DUTCH = 0x01, // Dutch SUBLANG_DUTCH_BELGIAN = 0x02, // Dutch (Belgian) SUBLANG_ENGLISH_US = 0x01, // English (USA) SUBLANG_ENGLISH_UK = 0x02, // English (UK) SUBLANG_ENGLISH_AUS = 0x03, // English (Australian) SUBLANG_ENGLISH_CAN = 0x04, // English (Canadian) SUBLANG_ENGLISH_NZ = 0x05, // English (New Zealand) SUBLANG_ENGLISH_EIRE = 0x06, // English (Irish) SUBLANG_ENGLISH_SOUTH_AFRICA = 0x07, // English (South Africa) SUBLANG_ENGLISH_JAMAICA = 0x08, // English (Jamaica) SUBLANG_ENGLISH_CARIBBEAN = 0x09, // English (Caribbean) SUBLANG_ENGLISH_BELIZE = 0x0a, // English (Belize) SUBLANG_ENGLISH_TRINIDAD = 0x0b, // English (Trinidad) SUBLANG_FRENCH = 0x01, // French SUBLANG_FRENCH_BELGIAN = 0x02, // French (Belgian) SUBLANG_FRENCH_CANADIAN = 0x03, // French (Canadian) SUBLANG_FRENCH_SWISS = 0x04, // French (Swiss) SUBLANG_FRENCH_LUXEMBOURG = 0x05, // French (Luxembourg) SUBLANG_GERMAN = 0x01, // German SUBLANG_GERMAN_SWISS = 0x02, // German (Swiss) SUBLANG_GERMAN_AUSTRIAN = 0x03, // German (Austrian) SUBLANG_GERMAN_LUXEMBOURG = 0x04, // German (Luxembourg) SUBLANG_GERMAN_LIECHTENSTEIN = 0x05, // German (Liechtenstein) SUBLANG_ITALIAN = 0x01, // Italian SUBLANG_ITALIAN_SWISS = 0x02, // Italian (Swiss) SUBLANG_KOREAN = 0x01, // Korean (Extended Wansung) SUBLANG_KOREAN_JOHAB = 0x02, // Korean (Johab) SUBLANG_NORWEGIAN_BOKMAL = 0x01, // Norwegian (Bokmal) SUBLANG_NORWEGIAN_NYNORSK = 0x02, // Norwegian (Nynorsk) SUBLANG_PORTUGUESE = 0x02, // Portuguese SUBLANG_PORTUGUESE_BRAZILIAN = 0x01, // Portuguese (Brazilian) SUBLANG_SERBIAN_LATIN = 0x02, // Serbian (Latin) SUBLANG_SERBIAN_CYRILLIC = 0x03, // Serbian (Cyrillic) SUBLANG_SPANISH = 0x01, // Spanish (Castilian) SUBLANG_SPANISH_MEXICAN = 0x02, // Spanish (Mexican) SUBLANG_SPANISH_MODERN = 0x03, // Spanish (Modern) SUBLANG_SPANISH_GUATEMALA = 0x04, // Spanish (Guatemala) SUBLANG_SPANISH_COSTA_RICA = 0x05, // Spanish (Costa Rica) SUBLANG_SPANISH_PANAMA = 0x06, // Spanish (Panama) SUBLANG_SPANISH_DOMINICAN_REPUBLIC = 0x07, // Spanish (Dominican Republic) SUBLANG_SPANISH_VENEZUELA = 0x08, // Spanish (Venezuela) SUBLANG_SPANISH_COLOMBIA = 0x09, // Spanish (Colombia) SUBLANG_SPANISH_PERU = 0x0a, // Spanish (Peru) SUBLANG_SPANISH_ARGENTINA = 0x0b, // Spanish (Argentina) SUBLANG_SPANISH_ECUADOR = 0x0c, // Spanish (Ecuador) SUBLANG_SPANISH_CHILE = 0x0d, // Spanish (Chile) SUBLANG_SPANISH_URUGUAY = 0x0e, // Spanish (Uruguay) SUBLANG_SPANISH_PARAGUAY = 0x0f, // Spanish (Paraguay) SUBLANG_SPANISH_BOLIVIA = 0x10, // Spanish (Bolivia) SUBLANG_SPANISH_EL_SALVADOR = 0x11, // Spanish (El Salvador) SUBLANG_SPANISH_HONDURAS = 0x12, // Spanish (Honduras) SUBLANG_SPANISH_NICARAGUA = 0x13, // Spanish (Nicaragua) SUBLANG_SPANISH_PUERTO_RICO = 0x14, // Spanish (Puerto Rico) SUBLANG_SWEDISH = 0x01, // Swedish SUBLANG_SWEDISH_FINLAND = 0x02, // Swedish (Finland) } // // Sorting IDs. // enum { SORT_DEFAULT = 0x0, // sorting default SORT_JAPANESE_XJIS = 0x0, // Japanese XJIS order SORT_JAPANESE_UNICODE = 0x1, // Japanese Unicode order SORT_CHINESE_BIG5 = 0x0, // Chinese BIG5 order SORT_CHINESE_PRCP = 0x0, // PRC Chinese Phonetic order SORT_CHINESE_UNICODE = 0x1, // Chinese Unicode order SORT_CHINESE_PRC = 0x2, // PRC Chinese Stroke Count order SORT_KOREAN_KSC = 0x0, // Korean KSC order SORT_KOREAN_UNICODE = 0x1, // Korean Unicode order SORT_GERMAN_PHONE_BOOK = 0x1, // German Phone Book order } // end_r_winnt // // A language ID is a 16 bit value which is the combination of a // primary language ID and a secondary language ID. The bits are // allocated as follows: // // +-----------------------+-------------------------+ // | Sublanguage ID | Primary Language ID | // +-----------------------+-------------------------+ // 15 10 9 0 bit // // // Language ID creation/extraction macros: // // MAKELANGID - construct language id from a primary language id and // a sublanguage id. // PRIMARYLANGID - extract primary language id from a language id. // SUBLANGID - extract sublanguage id from a language id. // int MAKELANGID(int p, int s) { return ((cast(WORD)s) << 10) | cast(WORD)p; } WORD PRIMARYLANGID(int lgid) { return cast(WORD)(lgid & 0x3ff); } WORD SUBLANGID(int lgid) { return cast(WORD)(lgid >> 10); } version (Win64) { enum { CONTEXT_AMD64 = 0x100000, CONTEXT_CONTROL = (CONTEXT_AMD64 | 0x1L), CONTEXT_INTEGER = (CONTEXT_AMD64 | 0x2L), CONTEXT_SEGMENTS = (CONTEXT_AMD64 | 0x4L), CONTEXT_FLOATING_POINT = (CONTEXT_AMD64 | 0x8L), CONTEXT_DEBUG_REGISTERS = (CONTEXT_AMD64 | 0x10L), CONTEXT_FULL = (CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_FLOATING_POINT), CONTEXT_ALL = (CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS | CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS), CONTEXT_EXCEPTION_ACTIVE = 0x8000000, CONTEXT_SERVICE_ACTIVE = 0x10000000, CONTEXT_EXCEPTION_REQUEST = 0x40000000, CONTEXT_EXCEPTION_REPORTING = 0x80000000, // Define initial MxCsr and FpCsr control. INITIAL_MXCSR = 0x1f80, // initial MXCSR value INITIAL_FPCSR = 0x027f, // initial FPCSR value } // Copied from Public Domain w64 mingw-runtime package's winnt.h. align(16) struct M128A { ULONGLONG Low; LONGLONG High; } alias M128A* PM128A; struct XMM_SAVE_AREA32 { WORD ControlWord; WORD StatusWord; BYTE TagWord; BYTE Reserved1; WORD ErrorOpcode; DWORD ErrorOffset; WORD ErrorSelector; WORD Reserved2; DWORD DataOffset; WORD DataSelector; WORD Reserved3; DWORD MxCsr; DWORD MxCsr_Mask; M128A FloatRegisters[8]; M128A XmmRegisters[16]; BYTE Reserved4[96]; } alias XMM_SAVE_AREA32 PXMM_SAVE_AREA32; align(16) struct CONTEXT // sizeof(1232) { DWORD64 P1Home; DWORD64 P2Home; DWORD64 P3Home; DWORD64 P4Home; DWORD64 P5Home; DWORD64 P6Home; DWORD ContextFlags; DWORD MxCsr; WORD SegCs; WORD SegDs; WORD SegEs; WORD SegFs; WORD SegGs; WORD SegSs; DWORD EFlags; DWORD64 Dr0; DWORD64 Dr1; DWORD64 Dr2; DWORD64 Dr3; DWORD64 Dr6; DWORD64 Dr7; DWORD64 Rax; DWORD64 Rcx; DWORD64 Rdx; DWORD64 Rbx; DWORD64 Rsp; DWORD64 Rbp; DWORD64 Rsi; DWORD64 Rdi; DWORD64 R8; DWORD64 R9; DWORD64 R10; DWORD64 R11; DWORD64 R12; DWORD64 R13; DWORD64 R14; DWORD64 R15; DWORD64 Rip; union { XMM_SAVE_AREA32 FltSave; XMM_SAVE_AREA32 FloatSave; struct { M128A Header[2]; M128A Legacy[8]; M128A Xmm0; M128A Xmm1; M128A Xmm2; M128A Xmm3; M128A Xmm4; M128A Xmm5; M128A Xmm6; M128A Xmm7; M128A Xmm8; M128A Xmm9; M128A Xmm10; M128A Xmm11; M128A Xmm12; M128A Xmm13; M128A Xmm14; M128A Xmm15; }; }; M128A VectorRegister[26]; DWORD64 VectorControl; DWORD64 DebugControl; DWORD64 LastBranchToRip; DWORD64 LastBranchFromRip; DWORD64 LastExceptionToRip; DWORD64 LastExceptionFromRip; } } else // Win32 { enum { SIZE_OF_80387_REGISTERS = 80, // // The following flags control the contents of the CONTEXT structure. // CONTEXT_i386 = 0x00010000, // this assumes that i386 and CONTEXT_i486 = 0x00010000, // i486 have identical context records CONTEXT_CONTROL = (CONTEXT_i386 | 0x00000001), // SS:SP, CS:IP, FLAGS, BP CONTEXT_INTEGER = (CONTEXT_i386 | 0x00000002), // AX, BX, CX, DX, SI, DI CONTEXT_SEGMENTS = (CONTEXT_i386 | 0x00000004), // DS, ES, FS, GS CONTEXT_FLOATING_POINT = (CONTEXT_i386 | 0x00000008), // 387 state CONTEXT_DEBUG_REGISTERS = (CONTEXT_i386 | 0x00000010), // DB 0-3,6,7 CONTEXT_EXTENDED_REGISTERS = (CONTEXT_i386 | 0x00000020L), // cpu specific extensions CONTEXT_FULL = (CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS), CONTEXT_ALL = (CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS | CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS | CONTEXT_EXTENDED_REGISTERS), MAXIMUM_SUPPORTED_EXTENSION = 512 } struct FLOATING_SAVE_AREA { DWORD ControlWord; DWORD StatusWord; DWORD TagWord; DWORD ErrorOffset; DWORD ErrorSelector; DWORD DataOffset; DWORD DataSelector; BYTE RegisterArea[SIZE_OF_80387_REGISTERS]; DWORD Cr0NpxState; } struct CONTEXT { // // The flags values within this flag control the contents of // a CONTEXT record. // // If the context record is used as an input parameter, then // for each portion of the context record controlled by a flag // whose value is set, it is assumed that that portion of the // context record contains valid context. If the context record // is being used to modify a threads context, then only that // portion of the threads context will be modified. // // If the context record is used as an IN OUT parameter to capture // the context of a thread, then only those portions of the thread's // context corresponding to set flags will be returned. // // The context record is never used as an OUT only parameter. // DWORD ContextFlags; // // This section is specified/returned if CONTEXT_DEBUG_REGISTERS is // set in ContextFlags. Note that CONTEXT_DEBUG_REGISTERS is NOT // included in CONTEXT_FULL. // DWORD Dr0; DWORD Dr1; DWORD Dr2; DWORD Dr3; DWORD Dr6; DWORD Dr7; // // This section is specified/returned if the // ContextFlags word contians the flag CONTEXT_FLOATING_POINT. // FLOATING_SAVE_AREA FloatSave; // // This section is specified/returned if the // ContextFlags word contians the flag CONTEXT_SEGMENTS. // DWORD SegGs; DWORD SegFs; DWORD SegEs; DWORD SegDs; // // This section is specified/returned if the // ContextFlags word contians the flag CONTEXT_INTEGER. // DWORD Edi; DWORD Esi; DWORD Ebx; DWORD Edx; DWORD Ecx; DWORD Eax; // // This section is specified/returned if the // ContextFlags word contians the flag CONTEXT_CONTROL. // DWORD Ebp; DWORD Eip; DWORD SegCs; // MUST BE SANITIZED DWORD EFlags; // MUST BE SANITIZED DWORD Esp; DWORD SegSs; // // This section is specified/returned if the ContextFlags word // contains the flag CONTEXT_EXTENDED_REGISTERS. // The format and contexts are processor specific // BYTE ExtendedRegisters[MAXIMUM_SUPPORTED_EXTENSION]; } } enum ADDRESS_MODE { AddrMode1616, AddrMode1632, AddrModeReal, AddrModeFlat } struct ADDRESS { DWORD Offset; WORD Segment; ADDRESS_MODE Mode; } struct ADDRESS64 { DWORD64 Offset; WORD Segment; ADDRESS_MODE Mode; } struct KDHELP { DWORD Thread; DWORD ThCallbackStack; DWORD NextCallback; DWORD FramePointer; DWORD KiCallUserMode; DWORD KeUserCallbackDispatcher; DWORD SystemRangeStart; DWORD ThCallbackBStore; DWORD KiUserExceptionDispatcher; DWORD StackBase; DWORD StackLimit; DWORD[5] Reserved; } struct KDHELP64 { DWORD64 Thread; DWORD ThCallbackStack; DWORD ThCallbackBStore; DWORD NextCallback; DWORD FramePointer; DWORD64 KiCallUserMode; DWORD64 KeUserCallbackDispatcher; DWORD64 SystemRangeStart; DWORD64 KiUserExceptionDispatcher; DWORD64 StackBase; DWORD64 StackLimit; DWORD64[5] Reserved; } struct STACKFRAME { ADDRESS AddrPC; ADDRESS AddrReturn; ADDRESS AddrFrame; ADDRESS AddrStack; PVOID FuncTableEntry; DWORD[4] Params; BOOL Far; BOOL Virtual; DWORD[3] Reserved; KDHELP KdHelp; ADDRESS AddrBStore; } struct STACKFRAME64 { ADDRESS64 AddrPC; ADDRESS64 AddrReturn; ADDRESS64 AddrFrame; ADDRESS64 AddrStack; ADDRESS64 AddrBStore; PVOID FuncTableEntry; DWORD64[4] Params; BOOL Far; BOOL Virtual; DWORD64[3] Reserved; KDHELP64 KdHelp; } enum { THREAD_BASE_PRIORITY_LOWRT = 15, // value that gets a thread to LowRealtime-1 THREAD_BASE_PRIORITY_MAX = 2, // maximum thread base priority boost THREAD_BASE_PRIORITY_MIN = -2, // minimum thread base priority boost THREAD_BASE_PRIORITY_IDLE = -15, // value that gets a thread to idle THREAD_PRIORITY_LOWEST = THREAD_BASE_PRIORITY_MIN, THREAD_PRIORITY_BELOW_NORMAL = (THREAD_PRIORITY_LOWEST+1), THREAD_PRIORITY_NORMAL = 0, THREAD_PRIORITY_HIGHEST = THREAD_BASE_PRIORITY_MAX, THREAD_PRIORITY_ABOVE_NORMAL = (THREAD_PRIORITY_HIGHEST-1), THREAD_PRIORITY_ERROR_RETURN = int.max, THREAD_PRIORITY_TIME_CRITICAL = THREAD_BASE_PRIORITY_LOWRT, THREAD_PRIORITY_IDLE = THREAD_BASE_PRIORITY_IDLE, } struct SYSTEM_INFO { union { DWORD dwOemId; struct { WORD wProcessorArchitecture; WORD wReserved; } } DWORD dwPageSize; LPVOID lpMinimumApplicationAddress; LPVOID lpMaximumApplicationAddress; DWORD_PTR dwActiveProcessorMask; DWORD dwNumberOfProcessors; DWORD dwProcessorType; DWORD dwAllocationGranularity; WORD wProcessorLevel; WORD wProcessorRevision; } alias SYSTEM_INFO* LPSYSTEM_INFO; export void GetSystemInfo(LPSYSTEM_INFO lpSystemInfo); export void GetNativeSystemInfo(LPSYSTEM_INFO lpSystemInfo); enum : DWORD { MAX_COMPUTERNAME_LENGTH = 15, } export BOOL GetComputerNameA(LPSTR lpBuffer, LPDWORD nSize); export BOOL GetComputerNameW(LPWSTR lpBuffer, LPDWORD nSize); export BOOL SetComputerNameA(LPCSTR lpComputerName); export BOOL SetComputerNameW(LPCWSTR lpComputerName); export BOOL GetUserNameA(LPSTR lpBuffer, LPDWORD lpnSize); export BOOL GetUserNameW(LPWSTR lpBuffer, LPDWORD lpnSize); export HANDLE GetCurrentThread(); export BOOL GetProcessTimes(HANDLE hProcess, LPFILETIME lpCreationTime, LPFILETIME lpExitTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime); export HANDLE GetCurrentProcess(); export DWORD GetCurrentProcessId(); export BOOL DuplicateHandle (HANDLE sourceProcess, HANDLE sourceThread, HANDLE targetProcessHandle, HANDLE *targetHandle, DWORD access, BOOL inheritHandle, DWORD options); export DWORD GetCurrentThreadId(); export BOOL SetThreadPriority(HANDLE hThread, int nPriority); export BOOL SetThreadPriorityBoost(HANDLE hThread, BOOL bDisablePriorityBoost); export BOOL GetThreadPriorityBoost(HANDLE hThread, PBOOL pDisablePriorityBoost); export BOOL GetThreadTimes(HANDLE hThread, LPFILETIME lpCreationTime, LPFILETIME lpExitTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime); export int GetThreadPriority(HANDLE hThread); export BOOL GetThreadContext(HANDLE hThread, CONTEXT* lpContext); export BOOL SetThreadContext(HANDLE hThread, CONTEXT* lpContext); export DWORD SuspendThread(HANDLE hThread); export DWORD ResumeThread(HANDLE hThread); export DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds); export DWORD WaitForMultipleObjects(DWORD nCount, HANDLE *lpHandles, BOOL bWaitAll, DWORD dwMilliseconds); export void Sleep(DWORD dwMilliseconds); export BOOL SwitchToThread(); // Synchronization export { LONG InterlockedIncrement(LPLONG lpAddend); LONG InterlockedDecrement(LPLONG lpAddend); LONG InterlockedExchange(LPLONG Target, LONG Value); LONG InterlockedExchangeAdd(LPLONG Addend, LONG Value); PVOID InterlockedCompareExchange(PVOID *Destination, PVOID Exchange, PVOID Comperand); void InitializeCriticalSection(CRITICAL_SECTION * lpCriticalSection); void EnterCriticalSection(CRITICAL_SECTION * lpCriticalSection); BOOL TryEnterCriticalSection(CRITICAL_SECTION * lpCriticalSection); void LeaveCriticalSection(CRITICAL_SECTION * lpCriticalSection); void DeleteCriticalSection(CRITICAL_SECTION * lpCriticalSection); } export BOOL QueryPerformanceCounter(long* lpPerformanceCount); export BOOL QueryPerformanceFrequency(long* lpFrequency); enum { WM_NOTIFY = 0x004E, WM_INPUTLANGCHANGEREQUEST = 0x0050, WM_INPUTLANGCHANGE = 0x0051, WM_TCARD = 0x0052, WM_HELP = 0x0053, WM_USERCHANGED = 0x0054, WM_NOTIFYFORMAT = 0x0055, NFR_ANSI = 1, NFR_UNICODE = 2, NF_QUERY = 3, NF_REQUERY = 4, WM_CONTEXTMENU = 0x007B, WM_STYLECHANGING = 0x007C, WM_STYLECHANGED = 0x007D, WM_DISPLAYCHANGE = 0x007E, WM_GETICON = 0x007F, WM_SETICON = 0x0080, WM_NCCREATE = 0x0081, WM_NCDESTROY = 0x0082, WM_NCCALCSIZE = 0x0083, WM_NCHITTEST = 0x0084, WM_NCPAINT = 0x0085, WM_NCACTIVATE = 0x0086, WM_GETDLGCODE = 0x0087, WM_NCMOUSEMOVE = 0x00A0, WM_NCLBUTTONDOWN = 0x00A1, WM_NCLBUTTONUP = 0x00A2, WM_NCLBUTTONDBLCLK = 0x00A3, WM_NCRBUTTONDOWN = 0x00A4, WM_NCRBUTTONUP = 0x00A5, WM_NCRBUTTONDBLCLK = 0x00A6, WM_NCMBUTTONDOWN = 0x00A7, WM_NCMBUTTONUP = 0x00A8, WM_NCMBUTTONDBLCLK = 0x00A9, WM_KEYFIRST = 0x0100, WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_CHAR = 0x0102, WM_DEADCHAR = 0x0103, WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105, WM_SYSCHAR = 0x0106, WM_SYSDEADCHAR = 0x0107, WM_KEYLAST = 0x0108, WM_IME_STARTCOMPOSITION = 0x010D, WM_IME_ENDCOMPOSITION = 0x010E, WM_IME_COMPOSITION = 0x010F, WM_IME_KEYLAST = 0x010F, WM_INITDIALOG = 0x0110, WM_COMMAND = 0x0111, WM_SYSCOMMAND = 0x0112, WM_TIMER = 0x0113, WM_HSCROLL = 0x0114, WM_VSCROLL = 0x0115, WM_INITMENU = 0x0116, WM_INITMENUPOPUP = 0x0117, WM_MENUSELECT = 0x011F, WM_MENUCHAR = 0x0120, WM_ENTERIDLE = 0x0121, WM_CTLCOLORMSGBOX = 0x0132, WM_CTLCOLOREDIT = 0x0133, WM_CTLCOLORLISTBOX = 0x0134, WM_CTLCOLORBTN = 0x0135, WM_CTLCOLORDLG = 0x0136, WM_CTLCOLORSCROLLBAR = 0x0137, WM_CTLCOLORSTATIC = 0x0138, WM_MOUSEFIRST = 0x0200, WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_LBUTTONDBLCLK = 0x0203, WM_RBUTTONDOWN = 0x0204, WM_RBUTTONUP = 0x0205, WM_RBUTTONDBLCLK = 0x0206, WM_MBUTTONDOWN = 0x0207, WM_MBUTTONUP = 0x0208, WM_MBUTTONDBLCLK = 0x0209, WM_MOUSELAST = 0x0209, WM_PARENTNOTIFY = 0x0210, MENULOOP_WINDOW = 0, MENULOOP_POPUP = 1, WM_ENTERMENULOOP = 0x0211, WM_EXITMENULOOP = 0x0212, WM_NEXTMENU = 0x0213, } enum { /* * Dialog Box Command IDs */ IDOK = 1, IDCANCEL = 2, IDABORT = 3, IDRETRY = 4, IDIGNORE = 5, IDYES = 6, IDNO = 7, IDCLOSE = 8, IDHELP = 9, // end_r_winuser /* * Control Manager Structures and Definitions */ // begin_r_winuser /* * Edit Control Styles */ ES_LEFT = 0x0000, ES_CENTER = 0x0001, ES_RIGHT = 0x0002, ES_MULTILINE = 0x0004, ES_UPPERCASE = 0x0008, ES_LOWERCASE = 0x0010, ES_PASSWORD = 0x0020, ES_AUTOVSCROLL = 0x0040, ES_AUTOHSCROLL = 0x0080, ES_NOHIDESEL = 0x0100, ES_OEMCONVERT = 0x0400, ES_READONLY = 0x0800, ES_WANTRETURN = 0x1000, ES_NUMBER = 0x2000, // end_r_winuser /* * Edit Control Notification Codes */ EN_SETFOCUS = 0x0100, EN_KILLFOCUS = 0x0200, EN_CHANGE = 0x0300, EN_UPDATE = 0x0400, EN_ERRSPACE = 0x0500, EN_MAXTEXT = 0x0501, EN_HSCROLL = 0x0601, EN_VSCROLL = 0x0602, /* Edit control EM_SETMARGIN parameters */ EC_LEFTMARGIN = 0x0001, EC_RIGHTMARGIN = 0x0002, EC_USEFONTINFO = 0xffff, // begin_r_winuser /* * Edit Control Messages */ EM_GETSEL = 0x00B0, EM_SETSEL = 0x00B1, EM_GETRECT = 0x00B2, EM_SETRECT = 0x00B3, EM_SETRECTNP = 0x00B4, EM_SCROLL = 0x00B5, EM_LINESCROLL = 0x00B6, EM_SCROLLCARET = 0x00B7, EM_GETMODIFY = 0x00B8, EM_SETMODIFY = 0x00B9, EM_GETLINECOUNT = 0x00BA, EM_LINEINDEX = 0x00BB, EM_SETHANDLE = 0x00BC, EM_GETHANDLE = 0x00BD, EM_GETTHUMB = 0x00BE, EM_LINELENGTH = 0x00C1, EM_REPLACESEL = 0x00C2, EM_GETLINE = 0x00C4, EM_LIMITTEXT = 0x00C5, EM_CANUNDO = 0x00C6, EM_UNDO = 0x00C7, EM_FMTLINES = 0x00C8, EM_LINEFROMCHAR = 0x00C9, EM_SETTABSTOPS = 0x00CB, EM_SETPASSWORDCHAR = 0x00CC, EM_EMPTYUNDOBUFFER = 0x00CD, EM_GETFIRSTVISIBLELINE = 0x00CE, EM_SETREADONLY = 0x00CF, EM_SETWORDBREAKPROC = 0x00D0, EM_GETWORDBREAKPROC = 0x00D1, EM_GETPASSWORDCHAR = 0x00D2, EM_SETMARGINS = 0x00D3, EM_GETMARGINS = 0x00D4, EM_SETLIMITTEXT = EM_LIMITTEXT, /* ;win40 Name change */ EM_GETLIMITTEXT = 0x00D5, EM_POSFROMCHAR = 0x00D6, EM_CHARFROMPOS = 0x00D7, // end_r_winuser /* * EDITWORDBREAKPROC code values */ WB_LEFT = 0, WB_RIGHT = 1, WB_ISDELIMITER = 2, // begin_r_winuser /* * Button Control Styles */ BS_PUSHBUTTON = 0x00000000, BS_DEFPUSHBUTTON = 0x00000001, BS_CHECKBOX = 0x00000002, BS_AUTOCHECKBOX = 0x00000003, BS_RADIOBUTTON = 0x00000004, BS_3STATE = 0x00000005, BS_AUTO3STATE = 0x00000006, BS_GROUPBOX = 0x00000007, BS_USERBUTTON = 0x00000008, BS_AUTORADIOBUTTON = 0x00000009, BS_OWNERDRAW = 0x0000000B, BS_LEFTTEXT = 0x00000020, BS_TEXT = 0x00000000, BS_ICON = 0x00000040, BS_BITMAP = 0x00000080, BS_LEFT = 0x00000100, BS_RIGHT = 0x00000200, BS_CENTER = 0x00000300, BS_TOP = 0x00000400, BS_BOTTOM = 0x00000800, BS_VCENTER = 0x00000C00, BS_PUSHLIKE = 0x00001000, BS_MULTILINE = 0x00002000, BS_NOTIFY = 0x00004000, BS_FLAT = 0x00008000, BS_RIGHTBUTTON = BS_LEFTTEXT, /* * User Button Notification Codes */ BN_CLICKED = 0, BN_PAINT = 1, BN_HILITE = 2, BN_UNHILITE = 3, BN_DISABLE = 4, BN_DOUBLECLICKED = 5, BN_PUSHED = BN_HILITE, BN_UNPUSHED = BN_UNHILITE, BN_DBLCLK = BN_DOUBLECLICKED, BN_SETFOCUS = 6, BN_KILLFOCUS = 7, /* * Button Control Messages */ BM_GETCHECK = 0x00F0, BM_SETCHECK = 0x00F1, BM_GETSTATE = 0x00F2, BM_SETSTATE = 0x00F3, BM_SETSTYLE = 0x00F4, BM_CLICK = 0x00F5, BM_GETIMAGE = 0x00F6, BM_SETIMAGE = 0x00F7, BST_UNCHECKED = 0x0000, BST_CHECKED = 0x0001, BST_INDETERMINATE = 0x0002, BST_PUSHED = 0x0004, BST_FOCUS = 0x0008, /* * Static Control Constants */ SS_LEFT = 0x00000000, SS_CENTER = 0x00000001, SS_RIGHT = 0x00000002, SS_ICON = 0x00000003, SS_BLACKRECT = 0x00000004, SS_GRAYRECT = 0x00000005, SS_WHITERECT = 0x00000006, SS_BLACKFRAME = 0x00000007, SS_GRAYFRAME = 0x00000008, SS_WHITEFRAME = 0x00000009, SS_USERITEM = 0x0000000A, SS_SIMPLE = 0x0000000B, SS_LEFTNOWORDWRAP = 0x0000000C, SS_OWNERDRAW = 0x0000000D, SS_BITMAP = 0x0000000E, SS_ENHMETAFILE = 0x0000000F, SS_ETCHEDHORZ = 0x00000010, SS_ETCHEDVERT = 0x00000011, SS_ETCHEDFRAME = 0x00000012, SS_TYPEMASK = 0x0000001F, SS_NOPREFIX = 0x00000080, /* Don't do "&" character translation */ SS_NOTIFY = 0x00000100, SS_CENTERIMAGE = 0x00000200, SS_RIGHTJUST = 0x00000400, SS_REALSIZEIMAGE = 0x00000800, SS_SUNKEN = 0x00001000, SS_ENDELLIPSIS = 0x00004000, SS_PATHELLIPSIS = 0x00008000, SS_WORDELLIPSIS = 0x0000C000, SS_ELLIPSISMASK = 0x0000C000, // end_r_winuser /* * Static Control Mesages */ STM_SETICON = 0x0170, STM_GETICON = 0x0171, STM_SETIMAGE = 0x0172, STM_GETIMAGE = 0x0173, STN_CLICKED = 0, STN_DBLCLK = 1, STN_ENABLE = 2, STN_DISABLE = 3, STM_MSGMAX = 0x0174, } enum { /* * Window Messages */ WM_NULL = 0x0000, WM_CREATE = 0x0001, WM_DESTROY = 0x0002, WM_MOVE = 0x0003, WM_SIZE = 0x0005, WM_ACTIVATE = 0x0006, /* * WM_ACTIVATE state values */ WA_INACTIVE = 0, WA_ACTIVE = 1, WA_CLICKACTIVE = 2, WM_SETFOCUS = 0x0007, WM_KILLFOCUS = 0x0008, WM_ENABLE = 0x000A, WM_SETREDRAW = 0x000B, WM_SETTEXT = 0x000C, WM_GETTEXT = 0x000D, WM_GETTEXTLENGTH = 0x000E, WM_PAINT = 0x000F, WM_CLOSE = 0x0010, WM_QUERYENDSESSION = 0x0011, WM_QUIT = 0x0012, WM_QUERYOPEN = 0x0013, WM_ERASEBKGND = 0x0014, WM_SYSCOLORCHANGE = 0x0015, WM_ENDSESSION = 0x0016, WM_SHOWWINDOW = 0x0018, WM_WININICHANGE = 0x001A, WM_SETTINGCHANGE = WM_WININICHANGE, WM_DEVMODECHANGE = 0x001B, WM_ACTIVATEAPP = 0x001C, WM_FONTCHANGE = 0x001D, WM_TIMECHANGE = 0x001E, WM_CANCELMODE = 0x001F, WM_SETCURSOR = 0x0020, WM_MOUSEACTIVATE = 0x0021, WM_CHILDACTIVATE = 0x0022, WM_QUEUESYNC = 0x0023, WM_GETMINMAXINFO = 0x0024, } struct RECT { LONG left; LONG top; LONG right; LONG bottom; } alias RECT* PRECT, NPRECT, LPRECT; struct PAINTSTRUCT { HDC hdc; BOOL fErase; RECT rcPaint; BOOL fRestore; BOOL fIncUpdate; BYTE rgbReserved[32]; } alias PAINTSTRUCT* PPAINTSTRUCT, NPPAINTSTRUCT, LPPAINTSTRUCT; // flags for GetDCEx() enum { DCX_WINDOW = 0x00000001, DCX_CACHE = 0x00000002, DCX_NORESETATTRS = 0x00000004, DCX_CLIPCHILDREN = 0x00000008, DCX_CLIPSIBLINGS = 0x00000010, DCX_PARENTCLIP = 0x00000020, DCX_EXCLUDERGN = 0x00000040, DCX_INTERSECTRGN = 0x00000080, DCX_EXCLUDEUPDATE = 0x00000100, DCX_INTERSECTUPDATE = 0x00000200, DCX_LOCKWINDOWUPDATE = 0x00000400, DCX_VALIDATE = 0x00200000, } export { BOOL UpdateWindow(HWND hWnd); HWND SetActiveWindow(HWND hWnd); HWND GetForegroundWindow(); BOOL PaintDesktop(HDC hdc); BOOL SetForegroundWindow(HWND hWnd); HWND WindowFromDC(HDC hDC); HDC GetDC(HWND hWnd); HDC GetDCEx(HWND hWnd, HRGN hrgnClip, DWORD flags); HDC GetWindowDC(HWND hWnd); int ReleaseDC(HWND hWnd, HDC hDC); HDC BeginPaint(HWND hWnd, LPPAINTSTRUCT lpPaint); BOOL EndPaint(HWND hWnd, PAINTSTRUCT *lpPaint); BOOL GetUpdateRect(HWND hWnd, LPRECT lpRect, BOOL bErase); int GetUpdateRgn(HWND hWnd, HRGN hRgn, BOOL bErase); int SetWindowRgn(HWND hWnd, HRGN hRgn, BOOL bRedraw); int GetWindowRgn(HWND hWnd, HRGN hRgn); int ExcludeUpdateRgn(HDC hDC, HWND hWnd); BOOL InvalidateRect(HWND hWnd, RECT *lpRect, BOOL bErase); BOOL ValidateRect(HWND hWnd, RECT *lpRect); BOOL InvalidateRgn(HWND hWnd, HRGN hRgn, BOOL bErase); BOOL ValidateRgn(HWND hWnd, HRGN hRgn); BOOL RedrawWindow(HWND hWnd, RECT *lprcUpdate, HRGN hrgnUpdate, UINT flags); } // flags for RedrawWindow() enum { RDW_INVALIDATE = 0x0001, RDW_INTERNALPAINT = 0x0002, RDW_ERASE = 0x0004, RDW_VALIDATE = 0x0008, RDW_NOINTERNALPAINT = 0x0010, RDW_NOERASE = 0x0020, RDW_NOCHILDREN = 0x0040, RDW_ALLCHILDREN = 0x0080, RDW_UPDATENOW = 0x0100, RDW_ERASENOW = 0x0200, RDW_FRAME = 0x0400, RDW_NOFRAME = 0x0800, } export { BOOL GetClientRect(HWND hWnd, LPRECT lpRect); BOOL GetWindowRect(HWND hWnd, LPRECT lpRect); BOOL AdjustWindowRect(LPRECT lpRect, DWORD dwStyle, BOOL bMenu); BOOL AdjustWindowRectEx(LPRECT lpRect, DWORD dwStyle, BOOL bMenu, DWORD dwExStyle); HFONT CreateFontA(int, int, int, int, int, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, LPCSTR); HFONT CreateFontW(int, int, int, int, int, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, LPCWSTR); } enum { OUT_DEFAULT_PRECIS = 0, OUT_STRING_PRECIS = 1, OUT_CHARACTER_PRECIS = 2, OUT_STROKE_PRECIS = 3, OUT_TT_PRECIS = 4, OUT_DEVICE_PRECIS = 5, OUT_RASTER_PRECIS = 6, OUT_TT_ONLY_PRECIS = 7, OUT_OUTLINE_PRECIS = 8, OUT_SCREEN_OUTLINE_PRECIS = 9, CLIP_DEFAULT_PRECIS = 0, CLIP_CHARACTER_PRECIS = 1, CLIP_STROKE_PRECIS = 2, CLIP_MASK = 0xf, CLIP_LH_ANGLES = (1<<4), CLIP_TT_ALWAYS = (2<<4), CLIP_EMBEDDED = (8<<4), DEFAULT_QUALITY = 0, DRAFT_QUALITY = 1, PROOF_QUALITY = 2, NONANTIALIASED_QUALITY = 3, ANTIALIASED_QUALITY = 4, DEFAULT_PITCH = 0, FIXED_PITCH = 1, VARIABLE_PITCH = 2, MONO_FONT = 8, ANSI_CHARSET = 0, DEFAULT_CHARSET = 1, SYMBOL_CHARSET = 2, SHIFTJIS_CHARSET = 128, HANGEUL_CHARSET = 129, GB2312_CHARSET = 134, CHINESEBIG5_CHARSET = 136, OEM_CHARSET = 255, JOHAB_CHARSET = 130, HEBREW_CHARSET = 177, ARABIC_CHARSET = 178, GREEK_CHARSET = 161, TURKISH_CHARSET = 162, VIETNAMESE_CHARSET = 163, THAI_CHARSET = 222, EASTEUROPE_CHARSET = 238, RUSSIAN_CHARSET = 204, MAC_CHARSET = 77, BALTIC_CHARSET = 186, FS_LATIN1 = 0x00000001L, FS_LATIN2 = 0x00000002L, FS_CYRILLIC = 0x00000004L, FS_GREEK = 0x00000008L, FS_TURKISH = 0x00000010L, FS_HEBREW = 0x00000020L, FS_ARABIC = 0x00000040L, FS_BALTIC = 0x00000080L, FS_VIETNAMESE = 0x00000100L, FS_THAI = 0x00010000L, FS_JISJAPAN = 0x00020000L, FS_CHINESESIMP = 0x00040000L, FS_WANSUNG = 0x00080000L, FS_CHINESETRAD = 0x00100000L, FS_JOHAB = 0x00200000L, FS_SYMBOL = cast(int)0x80000000L, /* Font Families */ FF_DONTCARE = (0<<4), /* Don't care or don't know. */ FF_ROMAN = (1<<4), /* Variable stroke width, serifed. */ /* Times Roman, Century Schoolbook, etc. */ FF_SWISS = (2<<4), /* Variable stroke width, sans-serifed. */ /* Helvetica, Swiss, etc. */ FF_MODERN = (3<<4), /* Constant stroke width, serifed or sans-serifed. */ /* Pica, Elite, Courier, etc. */ FF_SCRIPT = (4<<4), /* Cursive, etc. */ FF_DECORATIVE = (5<<4), /* Old English, etc. */ /* Font Weights */ FW_DONTCARE = 0, FW_THIN = 100, FW_EXTRALIGHT = 200, FW_LIGHT = 300, FW_NORMAL = 400, FW_MEDIUM = 500, FW_SEMIBOLD = 600, FW_BOLD = 700, FW_EXTRABOLD = 800, FW_HEAVY = 900, FW_ULTRALIGHT = FW_EXTRALIGHT, FW_REGULAR = FW_NORMAL, FW_DEMIBOLD = FW_SEMIBOLD, FW_ULTRABOLD = FW_EXTRABOLD, FW_BLACK = FW_HEAVY, PANOSE_COUNT = 10, PAN_FAMILYTYPE_INDEX = 0, PAN_SERIFSTYLE_INDEX = 1, PAN_WEIGHT_INDEX = 2, PAN_PROPORTION_INDEX = 3, PAN_CONTRAST_INDEX = 4, PAN_STROKEVARIATION_INDEX = 5, PAN_ARMSTYLE_INDEX = 6, PAN_LETTERFORM_INDEX = 7, PAN_MIDLINE_INDEX = 8, PAN_XHEIGHT_INDEX = 9, PAN_CULTURE_LATIN = 0, } struct RGBQUAD { BYTE rgbBlue; BYTE rgbGreen; BYTE rgbRed; BYTE rgbReserved; } alias RGBQUAD* LPRGBQUAD; struct BITMAPINFOHEADER { DWORD biSize; LONG biWidth; LONG biHeight; WORD biPlanes; WORD biBitCount; DWORD biCompression; DWORD biSizeImage; LONG biXPelsPerMeter; LONG biYPelsPerMeter; DWORD biClrUsed; DWORD biClrImportant; } alias BITMAPINFOHEADER* LPBITMAPINFOHEADER, PBITMAPINFOHEADER; struct BITMAPINFO { BITMAPINFOHEADER bmiHeader; RGBQUAD bmiColors[1]; } alias BITMAPINFO* LPBITMAPINFO, PBITMAPINFO; struct PALETTEENTRY { BYTE peRed; BYTE peGreen; BYTE peBlue; BYTE peFlags; } alias PALETTEENTRY* PPALETTEENTRY, LPPALETTEENTRY; struct LOGPALETTE { WORD palVersion; WORD palNumEntries; PALETTEENTRY palPalEntry[1]; } alias LOGPALETTE* PLOGPALETTE, NPLOGPALETTE, LPLOGPALETTE; /* Pixel format descriptor */ struct PIXELFORMATDESCRIPTOR { WORD nSize; WORD nVersion; DWORD dwFlags; BYTE iPixelType; BYTE cColorBits; BYTE cRedBits; BYTE cRedShift; BYTE cGreenBits; BYTE cGreenShift; BYTE cBlueBits; BYTE cBlueShift; BYTE cAlphaBits; BYTE cAlphaShift; BYTE cAccumBits; BYTE cAccumRedBits; BYTE cAccumGreenBits; BYTE cAccumBlueBits; BYTE cAccumAlphaBits; BYTE cDepthBits; BYTE cStencilBits; BYTE cAuxBuffers; BYTE iLayerType; BYTE bReserved; DWORD dwLayerMask; DWORD dwVisibleMask; DWORD dwDamageMask; } alias PIXELFORMATDESCRIPTOR* PPIXELFORMATDESCRIPTOR, LPPIXELFORMATDESCRIPTOR; export { BOOL RoundRect(HDC, int, int, int, int, int, int); BOOL ResizePalette(HPALETTE, UINT); int SaveDC(HDC); int SelectClipRgn(HDC, HRGN); int ExtSelectClipRgn(HDC, HRGN, int); int SetMetaRgn(HDC); HGDIOBJ SelectObject(HDC, HGDIOBJ); HPALETTE SelectPalette(HDC, HPALETTE, BOOL); COLORREF SetBkColor(HDC, COLORREF); int SetBkMode(HDC, int); LONG SetBitmapBits(HBITMAP, DWORD, void *); UINT SetBoundsRect(HDC, RECT *, UINT); int SetDIBits(HDC, HBITMAP, UINT, UINT, void *, BITMAPINFO *, UINT); int SetDIBitsToDevice(HDC, int, int, DWORD, DWORD, int, int, UINT, UINT, void *, BITMAPINFO *, UINT); DWORD SetMapperFlags(HDC, DWORD); int SetGraphicsMode(HDC hdc, int iMode); int SetMapMode(HDC, int); HMETAFILE SetMetaFileBitsEx(UINT, BYTE *); UINT SetPaletteEntries(HPALETTE, UINT, UINT, PALETTEENTRY *); COLORREF SetPixel(HDC, int, int, COLORREF); BOOL SetPixelV(HDC, int, int, COLORREF); BOOL SetPixelFormat(HDC, int, PIXELFORMATDESCRIPTOR *); int SetPolyFillMode(HDC, int); BOOL StretchBlt(HDC, int, int, int, int, HDC, int, int, int, int, DWORD); BOOL SetRectRgn(HRGN, int, int, int, int); int StretchDIBits(HDC, int, int, int, int, int, int, int, int, void *, BITMAPINFO *, UINT, DWORD); int SetROP2(HDC, int); int SetStretchBltMode(HDC, int); UINT SetSystemPaletteUse(HDC, UINT); int SetTextCharacterExtra(HDC, int); COLORREF SetTextColor(HDC, COLORREF); UINT SetTextAlign(HDC, UINT); BOOL SetTextJustification(HDC, int, int); BOOL UpdateColors(HDC); } /* Text Alignment Options */ enum { TA_NOUPDATECP = 0, TA_UPDATECP = 1, TA_LEFT = 0, TA_RIGHT = 2, TA_CENTER = 6, TA_TOP = 0, TA_BOTTOM = 8, TA_BASELINE = 24, TA_RTLREADING = 256, TA_MASK = (TA_BASELINE+TA_CENTER+TA_UPDATECP+TA_RTLREADING), } struct POINT { LONG x; LONG y; } alias POINT* PPOINT, NPPOINT, LPPOINT; export { BOOL MoveToEx(HDC, int, int, LPPOINT); BOOL TextOutA(HDC, int, int, LPCSTR, int); BOOL TextOutW(HDC, int, int, LPCWSTR, int); } export void PostQuitMessage(int nExitCode); export LRESULT DefWindowProcA(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); export LRESULT DefWindowProcW(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); export HMODULE GetModuleHandleA(LPCSTR lpModuleName); export HMODULE GetModuleHandleW(LPCWSTR lpModuleName); alias LRESULT function (HWND, UINT, WPARAM, LPARAM) WNDPROC; struct WNDCLASSEXA { UINT cbSize; /* Win 3.x */ UINT style; WNDPROC lpfnWndProc; int cbClsExtra; int cbWndExtra; HINSTANCE hInstance; HICON hIcon; HCURSOR hCursor; HBRUSH hbrBackground; LPCSTR lpszMenuName; LPCSTR lpszClassName; /* Win 4.0 */ HICON hIconSm; } alias WNDCLASSEXA* PWNDCLASSEXA, NPWNDCLASSEXA, LPWNDCLASSEXA; struct WNDCLASSA { UINT style; WNDPROC lpfnWndProc; int cbClsExtra; int cbWndExtra; HINSTANCE hInstance; HICON hIcon; HCURSOR hCursor; HBRUSH hbrBackground; LPCSTR lpszMenuName; LPCSTR lpszClassName; } alias WNDCLASSA* PWNDCLASSA, NPWNDCLASSA, LPWNDCLASSA; alias WNDCLASSA WNDCLASS; /* * Window Styles */ enum : uint { WS_OVERLAPPED = 0x00000000, WS_POPUP = 0x80000000, WS_CHILD = 0x40000000, WS_MINIMIZE = 0x20000000, WS_VISIBLE = 0x10000000, WS_DISABLED = 0x08000000, WS_CLIPSIBLINGS = 0x04000000, WS_CLIPCHILDREN = 0x02000000, WS_MAXIMIZE = 0x01000000, WS_CAPTION = 0x00C00000, /* WS_BORDER | WS_DLGFRAME */ WS_BORDER = 0x00800000, WS_DLGFRAME = 0x00400000, WS_VSCROLL = 0x00200000, WS_HSCROLL = 0x00100000, WS_SYSMENU = 0x00080000, WS_THICKFRAME = 0x00040000, WS_GROUP = 0x00020000, WS_TABSTOP = 0x00010000, WS_MINIMIZEBOX = 0x00020000, WS_MAXIMIZEBOX = 0x00010000, WS_TILED = WS_OVERLAPPED, WS_ICONIC = WS_MINIMIZE, WS_SIZEBOX = WS_THICKFRAME, /* * Common Window Styles */ WS_OVERLAPPEDWINDOW = (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX), WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW, WS_POPUPWINDOW = (WS_POPUP | WS_BORDER | WS_SYSMENU), WS_CHILDWINDOW = (WS_CHILD), } enum : uint { WS_EX_ACCEPTFILES = 0x00000010, WS_EX_APPWINDOW = 0x00040000, WS_EX_CLIENTEDGE = 0x00000200, WS_EX_COMPOSITED = 0x02000000, WS_EX_CONTEXTHELP = 0x00000400, WS_EX_CONTROLPARENT = 0x00010000, WS_EX_DLGMODALFRAME = 0x00000001, WS_EX_LAYERED = 0x00080000, WS_EX_LAYOUTRTL = 0x00400000, WS_EX_LEFT = 0x00000000, WS_EX_LEFTSCROLLBAR = 0x00004000, WS_EX_LTRREADING = 0x00000000, WS_EX_MDICHILD = 0x00000040, WS_EX_NOACTIVATE = 0x08000000, WS_EX_NOINHERITLAYOUT = 0x00100000, WS_EX_NOPARENTNOTIFY = 0x00000004, WS_EX_RIGHT = 0x00001000, WS_EX_RIGHTSCROLLBAR = 0x00000000, WS_EX_RTLREADING = 0x00002000, WS_EX_STATICEDGE = 0x00020000, WS_EX_TOOLWINDOW = 0x00000080, WS_EX_TOPMOST = 0x00000008, WS_EX_TRANSPARENT = 0x00000020, WS_EX_WINDOWEDGE = 0x00000100, WS_EX_OVERLAPPEDWINDOW = (WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE), WS_EX_PALETTEWINDOW = (WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST), } /* * Class styles */ enum { CS_VREDRAW = 0x0001, CS_HREDRAW = 0x0002, CS_KEYCVTWINDOW = 0x0004, CS_DBLCLKS = 0x0008, CS_OWNDC = 0x0020, CS_CLASSDC = 0x0040, CS_PARENTDC = 0x0080, CS_NOKEYCVT = 0x0100, CS_NOCLOSE = 0x0200, CS_SAVEBITS = 0x0800, CS_BYTEALIGNCLIENT = 0x1000, CS_BYTEALIGNWINDOW = 0x2000, CS_GLOBALCLASS = 0x4000, CS_IME = 0x00010000, } export { HICON LoadIconA(HINSTANCE hInstance, LPCSTR lpIconName); HICON LoadIconW(HINSTANCE hInstance, LPCWSTR lpIconName); HCURSOR LoadCursorA(HINSTANCE hInstance, LPCSTR lpCursorName); HCURSOR LoadCursorW(HINSTANCE hInstance, LPCWSTR lpCursorName); } enum : LPSTR { IDI_APPLICATION = cast(LPSTR)(32512), IDC_ARROW = cast(LPSTR)(32512), IDC_CROSS = cast(LPSTR)(32515), } /* * Color Types */ enum { CTLCOLOR_MSGBOX = 0, CTLCOLOR_EDIT = 1, CTLCOLOR_LISTBOX = 2, CTLCOLOR_BTN = 3, CTLCOLOR_DLG = 4, CTLCOLOR_SCROLLBAR = 5, CTLCOLOR_STATIC = 6, CTLCOLOR_MAX = 7, COLOR_SCROLLBAR = 0, COLOR_BACKGROUND = 1, COLOR_ACTIVECAPTION = 2, COLOR_INACTIVECAPTION = 3, COLOR_MENU = 4, COLOR_WINDOW = 5, COLOR_WINDOWFRAME = 6, COLOR_MENUTEXT = 7, COLOR_WINDOWTEXT = 8, COLOR_CAPTIONTEXT = 9, COLOR_ACTIVEBORDER = 10, COLOR_INACTIVEBORDER = 11, COLOR_APPWORKSPACE = 12, COLOR_HIGHLIGHT = 13, COLOR_HIGHLIGHTTEXT = 14, COLOR_BTNFACE = 15, COLOR_BTNSHADOW = 16, COLOR_GRAYTEXT = 17, COLOR_BTNTEXT = 18, COLOR_INACTIVECAPTIONTEXT = 19, COLOR_BTNHIGHLIGHT = 20, COLOR_3DDKSHADOW = 21, COLOR_3DLIGHT = 22, COLOR_INFOTEXT = 23, COLOR_INFOBK = 24, COLOR_DESKTOP = COLOR_BACKGROUND, COLOR_3DFACE = COLOR_BTNFACE, COLOR_3DSHADOW = COLOR_BTNSHADOW, COLOR_3DHIGHLIGHT = COLOR_BTNHIGHLIGHT, COLOR_3DHILIGHT = COLOR_BTNHIGHLIGHT, COLOR_BTNHILIGHT = COLOR_BTNHIGHLIGHT, } enum : int { CW_USEDEFAULT = cast(int)0x80000000 } /* * Special value for CreateWindow, et al. */ enum : HWND { HWND_DESKTOP = cast(HWND)0, } export ATOM RegisterClassA(in WNDCLASSA *lpWndClass); export ATOM RegisterClassExA(in WNDCLASSEXA *lpWndClass); export HWND CreateWindowExA( DWORD dwExStyle, LPCSTR lpClassName, LPCSTR lpWindowName, DWORD dwStyle, int X, int Y, int nWidth, int nHeight, HWND hWndParent , HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam); HWND CreateWindowA( LPCSTR lpClassName, LPCSTR lpWindowName, DWORD dwStyle, int X, int Y, int nWidth, int nHeight, HWND hWndParent , HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam) { return CreateWindowExA(0, lpClassName, lpWindowName, dwStyle, X, Y, nWidth, nHeight, hWndParent, hMenu, hInstance, lpParam); } /* * Message structure */ struct MSG { HWND hwnd; UINT message; WPARAM wParam; LPARAM lParam; DWORD time; POINT pt; } alias MSG* PMSG, NPMSG, LPMSG; export { BOOL GetMessageA(LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax); BOOL TranslateMessage(MSG *lpMsg); LONG DispatchMessageA(MSG *lpMsg); BOOL PeekMessageA(MSG *lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg); HWND GetFocus(); } /* http://msdn.microsoft.com/en-us/library/windows/desktop/ms683187(v=vs.85).aspx According to MSDN about a value returned by GetEnvironmentString: "Treat this memory as read-only; do not modify it directly.". So return type of GetEnvironmentStrings is changed from LPWCH (as in *.h file) to LPCWCH. FreeEnvironmentStrings's argument type is changed correspondingly. */ export LPCWCH GetEnvironmentStringsW(); export BOOL FreeEnvironmentStringsW(LPCWCH lpszEnvironmentBlock); export DWORD GetEnvironmentVariableW(LPCWSTR lpName, LPWSTR lpBuffer, DWORD nSize); export BOOL SetEnvironmentVariableW(LPCWSTR lpName, LPCWSTR lpValue); export DWORD ExpandEnvironmentStringsA(LPCSTR lpSrc, LPSTR lpDst, DWORD nSize); export DWORD ExpandEnvironmentStringsW(LPCWSTR lpSrc, LPWSTR lpDst, DWORD nSize); export { BOOL IsValidCodePage(UINT CodePage); UINT GetACP(); UINT GetOEMCP(); //BOOL GetCPInfo(UINT CodePage, LPCPINFO lpCPInfo); BOOL IsDBCSLeadByte(BYTE TestChar); BOOL IsDBCSLeadByteEx(UINT CodePage, BYTE TestChar); int MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cchMultiByte, LPWSTR lpWideCharStr, int cchWideChar); int WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cchMultiByte, LPCSTR lpDefaultChar, LPBOOL lpUsedDefaultChar); } export HANDLE CreateFileMappingA(HANDLE hFile, LPSECURITY_ATTRIBUTES lpFileMappingAttributes, DWORD flProtect, DWORD dwMaximumSizeHigh, DWORD dwMaximumSizeLow, LPCSTR lpName); export HANDLE CreateFileMappingW(HANDLE hFile, LPSECURITY_ATTRIBUTES lpFileMappingAttributes, DWORD flProtect, DWORD dwMaximumSizeHigh, DWORD dwMaximumSizeLow, LPCWSTR lpName); export BOOL GetMailslotInfo(HANDLE hMailslot, LPDWORD lpMaxMessageSize, LPDWORD lpNextSize, LPDWORD lpMessageCount, LPDWORD lpReadTimeout); export BOOL SetMailslotInfo(HANDLE hMailslot, DWORD lReadTimeout); export LPVOID MapViewOfFile(HANDLE hFileMappingObject, DWORD dwDesiredAccess, DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow, SIZE_T dwNumberOfBytesToMap); export LPVOID MapViewOfFileEx(HANDLE hFileMappingObject, DWORD dwDesiredAccess, DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow, SIZE_T dwNumberOfBytesToMap, LPVOID lpBaseAddress); export BOOL FlushViewOfFile(LPCVOID lpBaseAddress, SIZE_T dwNumberOfBytesToFlush); export BOOL UnmapViewOfFile(LPCVOID lpBaseAddress); export HGDIOBJ GetStockObject(int); export BOOL ShowWindow(HWND hWnd, int nCmdShow); /* Stock Logical Objects */ enum { WHITE_BRUSH = 0, LTGRAY_BRUSH = 1, GRAY_BRUSH = 2, DKGRAY_BRUSH = 3, BLACK_BRUSH = 4, NULL_BRUSH = 5, HOLLOW_BRUSH = NULL_BRUSH, WHITE_PEN = 6, BLACK_PEN = 7, NULL_PEN = 8, OEM_FIXED_FONT = 10, ANSI_FIXED_FONT = 11, ANSI_VAR_FONT = 12, SYSTEM_FONT = 13, DEVICE_DEFAULT_FONT = 14, DEFAULT_PALETTE = 15, SYSTEM_FIXED_FONT = 16, DEFAULT_GUI_FONT = 17, STOCK_LAST = 17, } /* * ShowWindow() Commands */ enum { SW_HIDE = 0, SW_SHOWNORMAL = 1, SW_NORMAL = 1, SW_SHOWMINIMIZED = 2, SW_SHOWMAXIMIZED = 3, SW_MAXIMIZE = 3, SW_SHOWNOACTIVATE = 4, SW_SHOW = 5, SW_MINIMIZE = 6, SW_SHOWMINNOACTIVE = 7, SW_SHOWNA = 8, SW_RESTORE = 9, SW_SHOWDEFAULT = 10, SW_MAX = 10, } struct TEXTMETRICA { LONG tmHeight; LONG tmAscent; LONG tmDescent; LONG tmInternalLeading; LONG tmExternalLeading; LONG tmAveCharWidth; LONG tmMaxCharWidth; LONG tmWeight; LONG tmOverhang; LONG tmDigitizedAspectX; LONG tmDigitizedAspectY; BYTE tmFirstChar; BYTE tmLastChar; BYTE tmDefaultChar; BYTE tmBreakChar; BYTE tmItalic; BYTE tmUnderlined; BYTE tmStruckOut; BYTE tmPitchAndFamily; BYTE tmCharSet; } export BOOL GetTextMetricsA(HDC, TEXTMETRICA*); /* * Scroll Bar Constants */ enum { SB_HORZ = 0, SB_VERT = 1, SB_CTL = 2, SB_BOTH = 3, } /* * Scroll Bar Commands */ enum { SB_LINEUP = 0, SB_LINELEFT = 0, SB_LINEDOWN = 1, SB_LINERIGHT = 1, SB_PAGEUP = 2, SB_PAGELEFT = 2, SB_PAGEDOWN = 3, SB_PAGERIGHT = 3, SB_THUMBPOSITION = 4, SB_THUMBTRACK = 5, SB_TOP = 6, SB_LEFT = 6, SB_BOTTOM = 7, SB_RIGHT = 7, SB_ENDSCROLL = 8, } export int SetScrollPos(HWND hWnd, int nBar, int nPos, BOOL bRedraw); export int GetScrollPos(HWND hWnd, int nBar); export BOOL SetScrollRange(HWND hWnd, int nBar, int nMinPos, int nMaxPos, BOOL bRedraw); export BOOL GetScrollRange(HWND hWnd, int nBar, LPINT lpMinPos, LPINT lpMaxPos); export BOOL ShowScrollBar(HWND hWnd, int wBar, BOOL bShow); export BOOL EnableScrollBar(HWND hWnd, UINT wSBflags, UINT wArrows); /* * LockWindowUpdate API */ export BOOL LockWindowUpdate(HWND hWndLock); export BOOL ScrollWindow(HWND hWnd, int XAmount, int YAmount, RECT* lpRect, RECT* lpClipRect); export BOOL ScrollDC(HDC hDC, int dx, int dy, RECT* lprcScroll, RECT* lprcClip, HRGN hrgnUpdate, LPRECT lprcUpdate); export int ScrollWindowEx(HWND hWnd, int dx, int dy, RECT* prcScroll, RECT* prcClip, HRGN hrgnUpdate, LPRECT prcUpdate, UINT flags); /* * Virtual Keys, Standard Set */ enum { VK_LBUTTON = 0x01, VK_RBUTTON = 0x02, VK_CANCEL = 0x03, VK_MBUTTON = 0x04, /* NOT contiguous with L & RBUTTON */ VK_BACK = 0x08, VK_TAB = 0x09, VK_CLEAR = 0x0C, VK_RETURN = 0x0D, VK_SHIFT = 0x10, VK_CONTROL = 0x11, VK_MENU = 0x12, VK_PAUSE = 0x13, VK_CAPITAL = 0x14, VK_ESCAPE = 0x1B, VK_SPACE = 0x20, VK_PRIOR = 0x21, VK_NEXT = 0x22, VK_END = 0x23, VK_HOME = 0x24, VK_LEFT = 0x25, VK_UP = 0x26, VK_RIGHT = 0x27, VK_DOWN = 0x28, VK_SELECT = 0x29, VK_PRINT = 0x2A, VK_EXECUTE = 0x2B, VK_SNAPSHOT = 0x2C, VK_INSERT = 0x2D, VK_DELETE = 0x2E, VK_HELP = 0x2F, /* VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39) */ /* VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A) */ VK_LWIN = 0x5B, VK_RWIN = 0x5C, VK_APPS = 0x5D, VK_NUMPAD0 = 0x60, VK_NUMPAD1 = 0x61, VK_NUMPAD2 = 0x62, VK_NUMPAD3 = 0x63, VK_NUMPAD4 = 0x64, VK_NUMPAD5 = 0x65, VK_NUMPAD6 = 0x66, VK_NUMPAD7 = 0x67, VK_NUMPAD8 = 0x68, VK_NUMPAD9 = 0x69, VK_MULTIPLY = 0x6A, VK_ADD = 0x6B, VK_SEPARATOR = 0x6C, VK_SUBTRACT = 0x6D, VK_DECIMAL = 0x6E, VK_DIVIDE = 0x6F, VK_F1 = 0x70, VK_F2 = 0x71, VK_F3 = 0x72, VK_F4 = 0x73, VK_F5 = 0x74, VK_F6 = 0x75, VK_F7 = 0x76, VK_F8 = 0x77, VK_F9 = 0x78, VK_F10 = 0x79, VK_F11 = 0x7A, VK_F12 = 0x7B, VK_F13 = 0x7C, VK_F14 = 0x7D, VK_F15 = 0x7E, VK_F16 = 0x7F, VK_F17 = 0x80, VK_F18 = 0x81, VK_F19 = 0x82, VK_F20 = 0x83, VK_F21 = 0x84, VK_F22 = 0x85, VK_F23 = 0x86, VK_F24 = 0x87, VK_NUMLOCK = 0x90, VK_SCROLL = 0x91, /* * VK_L* & VK_R* - left and right Alt, Ctrl and Shift virtual keys. * Used only as parameters to GetAsyncKeyState() and GetKeyState(). * No other API or message will distinguish left and right keys in this way. */ VK_LSHIFT = 0xA0, VK_RSHIFT = 0xA1, VK_LCONTROL = 0xA2, VK_RCONTROL = 0xA3, VK_LMENU = 0xA4, VK_RMENU = 0xA5, VK_PROCESSKEY = 0xE5, VK_ATTN = 0xF6, VK_CRSEL = 0xF7, VK_EXSEL = 0xF8, VK_EREOF = 0xF9, VK_PLAY = 0xFA, VK_ZOOM = 0xFB, VK_NONAME = 0xFC, VK_PA1 = 0xFD, VK_OEM_CLEAR = 0xFE, } export LRESULT SendMessageA(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); alias UINT function (HWND, UINT, WPARAM, LPARAM) LPOFNHOOKPROC; struct OPENFILENAMEA { DWORD lStructSize; HWND hwndOwner; HINSTANCE hInstance; LPCSTR lpstrFilter; LPSTR lpstrCustomFilter; DWORD nMaxCustFilter; DWORD nFilterIndex; LPSTR lpstrFile; DWORD nMaxFile; LPSTR lpstrFileTitle; DWORD nMaxFileTitle; LPCSTR lpstrInitialDir; LPCSTR lpstrTitle; DWORD Flags; WORD nFileOffset; WORD nFileExtension; LPCSTR lpstrDefExt; LPARAM lCustData; LPOFNHOOKPROC lpfnHook; LPCSTR lpTemplateName; } alias OPENFILENAMEA *LPOPENFILENAMEA; struct OPENFILENAMEW { DWORD lStructSize; HWND hwndOwner; HINSTANCE hInstance; LPCWSTR lpstrFilter; LPWSTR lpstrCustomFilter; DWORD nMaxCustFilter; DWORD nFilterIndex; LPWSTR lpstrFile; DWORD nMaxFile; LPWSTR lpstrFileTitle; DWORD nMaxFileTitle; LPCWSTR lpstrInitialDir; LPCWSTR lpstrTitle; DWORD Flags; WORD nFileOffset; WORD nFileExtension; LPCWSTR lpstrDefExt; LPARAM lCustData; LPOFNHOOKPROC lpfnHook; LPCWSTR lpTemplateName; } alias OPENFILENAMEW *LPOPENFILENAMEW; BOOL GetOpenFileNameA(LPOPENFILENAMEA); BOOL GetOpenFileNameW(LPOPENFILENAMEW); BOOL GetSaveFileNameA(LPOPENFILENAMEA); BOOL GetSaveFileNameW(LPOPENFILENAMEW); short GetFileTitleA(LPCSTR, LPSTR, WORD); short GetFileTitleW(LPCWSTR, LPWSTR, WORD); enum { PM_NOREMOVE = 0x0000, PM_REMOVE = 0x0001, PM_NOYIELD = 0x0002, } /* Bitmap Header Definition */ struct BITMAP { LONG bmType; LONG bmWidth; LONG bmHeight; LONG bmWidthBytes; WORD bmPlanes; WORD bmBitsPixel; LPVOID bmBits; } alias BITMAP* PBITMAP, NPBITMAP, LPBITMAP; export HDC CreateCompatibleDC(HDC); export int GetObjectA(HGDIOBJ, int, LPVOID); export int GetObjectW(HGDIOBJ, int, LPVOID); export BOOL DeleteDC(HDC); struct LOGFONTA { LONG lfHeight; LONG lfWidth; LONG lfEscapement; LONG lfOrientation; LONG lfWeight; BYTE lfItalic; BYTE lfUnderline; BYTE lfStrikeOut; BYTE lfCharSet; BYTE lfOutPrecision; BYTE lfClipPrecision; BYTE lfQuality; BYTE lfPitchAndFamily; CHAR lfFaceName[32 ]; } alias LOGFONTA* PLOGFONTA, NPLOGFONTA, LPLOGFONTA; export HMENU LoadMenuA(HINSTANCE hInstance, LPCSTR lpMenuName); export HMENU LoadMenuW(HINSTANCE hInstance, LPCWSTR lpMenuName); export HMENU GetSubMenu(HMENU hMenu, int nPos); export HBITMAP LoadBitmapA(HINSTANCE hInstance, LPCSTR lpBitmapName); export HBITMAP LoadBitmapW(HINSTANCE hInstance, LPCWSTR lpBitmapName); LPSTR MAKEINTRESOURCEA(int i) { return cast(LPSTR)(cast(DWORD)(cast(WORD)(i))); } export HFONT CreateFontIndirectA(LOGFONTA *); export BOOL MessageBeep(UINT uType); export int ShowCursor(BOOL bShow); export BOOL SetCursorPos(int X, int Y); export HCURSOR SetCursor(HCURSOR hCursor); export BOOL GetCursorPos(LPPOINT lpPoint); export BOOL ClipCursor( RECT *lpRect); export BOOL GetClipCursor(LPRECT lpRect); export HCURSOR GetCursor(); export BOOL CreateCaret(HWND hWnd, HBITMAP hBitmap , int nWidth, int nHeight); export UINT GetCaretBlinkTime(); export BOOL SetCaretBlinkTime(UINT uMSeconds); export BOOL DestroyCaret(); export BOOL HideCaret(HWND hWnd); export BOOL ShowCaret(HWND hWnd); export BOOL SetCaretPos(int X, int Y); export BOOL GetCaretPos(LPPOINT lpPoint); export BOOL ClientToScreen(HWND hWnd, LPPOINT lpPoint); export BOOL ScreenToClient(HWND hWnd, LPPOINT lpPoint); export int MapWindowPoints(HWND hWndFrom, HWND hWndTo, LPPOINT lpPoints, UINT cPoints); export HWND WindowFromPoint(POINT Point); export HWND ChildWindowFromPoint(HWND hWndParent, POINT Point); export BOOL TrackPopupMenu(HMENU hMenu, UINT uFlags, int x, int y, int nReserved, HWND hWnd, RECT *prcRect); align (2) struct DLGTEMPLATE { DWORD style; DWORD dwExtendedStyle; WORD cdit; short x; short y; short cx; short cy; } alias DLGTEMPLATE *LPDLGTEMPLATEA; alias DLGTEMPLATE *LPDLGTEMPLATEW; alias LPDLGTEMPLATEA LPDLGTEMPLATE; alias DLGTEMPLATE *LPCDLGTEMPLATEA; alias DLGTEMPLATE *LPCDLGTEMPLATEW; alias LPCDLGTEMPLATEA LPCDLGTEMPLATE; export int DialogBoxParamA(HINSTANCE hInstance, LPCSTR lpTemplateName, HWND hWndParent, DLGPROC lpDialogFunc, LPARAM dwInitParam); export int DialogBoxIndirectParamA(HINSTANCE hInstance, LPCDLGTEMPLATEA hDialogTemplate, HWND hWndParent, DLGPROC lpDialogFunc, LPARAM dwInitParam); enum : DWORD { SRCCOPY = cast(DWORD)0x00CC0020, /* dest = source */ SRCPAINT = cast(DWORD)0x00EE0086, /* dest = source OR dest */ SRCAND = cast(DWORD)0x008800C6, /* dest = source AND dest */ SRCINVERT = cast(DWORD)0x00660046, /* dest = source XOR dest */ SRCERASE = cast(DWORD)0x00440328, /* dest = source AND (NOT dest) */ NOTSRCCOPY = cast(DWORD)0x00330008, /* dest = (NOT source) */ NOTSRCERASE = cast(DWORD)0x001100A6, /* dest = (NOT src) AND (NOT dest) */ MERGECOPY = cast(DWORD)0x00C000CA, /* dest = (source AND pattern) */ MERGEPAINT = cast(DWORD)0x00BB0226, /* dest = (NOT source) OR dest */ PATCOPY = cast(DWORD)0x00F00021, /* dest = pattern */ PATPAINT = cast(DWORD)0x00FB0A09, /* dest = DPSnoo */ PATINVERT = cast(DWORD)0x005A0049, /* dest = pattern XOR dest */ DSTINVERT = cast(DWORD)0x00550009, /* dest = (NOT dest) */ BLACKNESS = cast(DWORD)0x00000042, /* dest = BLACK */ WHITENESS = cast(DWORD)0x00FF0062, /* dest = WHITE */ } enum { SND_SYNC = 0x0000, /* play synchronously (default) */ SND_ASYNC = 0x0001, /* play asynchronously */ SND_NODEFAULT = 0x0002, /* silence (!default) if sound not found */ SND_MEMORY = 0x0004, /* pszSound points to a memory file */ SND_LOOP = 0x0008, /* loop the sound until next sndPlaySound */ SND_NOSTOP = 0x0010, /* don't stop any currently playing sound */ SND_NOWAIT = 0x00002000, /* don't wait if the driver is busy */ SND_ALIAS = 0x00010000, /* name is a registry alias */ SND_ALIAS_ID = 0x00110000, /* alias is a predefined ID */ SND_FILENAME = 0x00020000, /* name is file name */ SND_RESOURCE = 0x00040004, /* name is resource name or atom */ SND_PURGE = 0x0040, /* purge non-static events for task */ SND_APPLICATION = 0x0080, /* look for application specific association */ SND_ALIAS_START = 0, /* alias base */ } export BOOL PlaySoundA(LPCSTR pszSound, HMODULE hmod, DWORD fdwSound); export BOOL PlaySoundW(LPCWSTR pszSound, HMODULE hmod, DWORD fdwSound); export int GetClipBox(HDC, LPRECT); export int GetClipRgn(HDC, HRGN); export int GetMetaRgn(HDC, HRGN); export HGDIOBJ GetCurrentObject(HDC, UINT); export BOOL GetCurrentPositionEx(HDC, LPPOINT); export int GetDeviceCaps(HDC, int); struct LOGPEN { UINT lopnStyle; POINT lopnWidth; COLORREF lopnColor; } alias LOGPEN* PLOGPEN, NPLOGPEN, LPLOGPEN; enum { PS_SOLID = 0, PS_DASH = 1, /* ------- */ PS_DOT = 2, /* ....... */ PS_DASHDOT = 3, /* _._._._ */ PS_DASHDOTDOT = 4, /* _.._.._ */ PS_NULL = 5, PS_INSIDEFRAME = 6, PS_USERSTYLE = 7, PS_ALTERNATE = 8, PS_STYLE_MASK = 0x0000000F, PS_ENDCAP_ROUND = 0x00000000, PS_ENDCAP_SQUARE = 0x00000100, PS_ENDCAP_FLAT = 0x00000200, PS_ENDCAP_MASK = 0x00000F00, PS_JOIN_ROUND = 0x00000000, PS_JOIN_BEVEL = 0x00001000, PS_JOIN_MITER = 0x00002000, PS_JOIN_MASK = 0x0000F000, PS_COSMETIC = 0x00000000, PS_GEOMETRIC = 0x00010000, PS_TYPE_MASK = 0x000F0000, } export HPALETTE CreatePalette(LOGPALETTE *); export HPEN CreatePen(int, int, COLORREF); export HPEN CreatePenIndirect(LOGPEN *); export HRGN CreatePolyPolygonRgn(POINT *, INT *, int, int); export HBRUSH CreatePatternBrush(HBITMAP); export HRGN CreateRectRgn(int, int, int, int); export HRGN CreateRectRgnIndirect(RECT *); export HRGN CreateRoundRectRgn(int, int, int, int, int, int); export BOOL CreateScalableFontResourceA(DWORD, LPCSTR, LPCSTR, LPCSTR); export BOOL CreateScalableFontResourceW(DWORD, LPCWSTR, LPCWSTR, LPCWSTR); COLORREF RGB(int r, int g, int b) { return cast(COLORREF) ((cast(BYTE)r|(cast(WORD)(cast(BYTE)g)<<8))|((cast(DWORD)cast(BYTE)b)<<16)); } export BOOL LineTo(HDC, int, int); export BOOL DeleteObject(HGDIOBJ); export int FillRect(HDC hDC, RECT *lprc, HBRUSH hbr); export BOOL EndDialog(HWND hDlg, int nResult); export HWND GetDlgItem(HWND hDlg, int nIDDlgItem); export BOOL SetDlgItemInt(HWND hDlg, int nIDDlgItem, UINT uValue, BOOL bSigned); export UINT GetDlgItemInt(HWND hDlg, int nIDDlgItem, BOOL *lpTranslated, BOOL bSigned); export BOOL SetDlgItemTextA(HWND hDlg, int nIDDlgItem, LPCSTR lpString); export BOOL SetDlgItemTextW(HWND hDlg, int nIDDlgItem, LPCWSTR lpString); export UINT GetDlgItemTextA(HWND hDlg, int nIDDlgItem, LPSTR lpString, int nMaxCount); export UINT GetDlgItemTextW(HWND hDlg, int nIDDlgItem, LPWSTR lpString, int nMaxCount); export BOOL CheckDlgButton(HWND hDlg, int nIDButton, UINT uCheck); export BOOL CheckRadioButton(HWND hDlg, int nIDFirstButton, int nIDLastButton, int nIDCheckButton); export UINT IsDlgButtonChecked(HWND hDlg, int nIDButton); export HWND SetFocus(HWND hWnd); extern (C) { export int wsprintfA(LPSTR, LPCSTR, ...); export int wsprintfW(LPWSTR, LPCWSTR, ...); } enum : uint { INFINITE = uint.max, WAIT_OBJECT_0 = 0, WAIT_ABANDONED_0 = 0x80, WAIT_TIMEOUT = 0x102, WAIT_IO_COMPLETION = 0xc0, WAIT_ABANDONED = 0x80, WAIT_FAILED = uint.max, } export HANDLE CreateSemaphoreA(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lInitialCount, LONG lMaximumCount, LPCTSTR lpName); export HANDLE OpenSemaphoreA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCTSTR lpName); export BOOL ReleaseSemaphore(HANDLE hSemaphore, LONG lReleaseCount, LPLONG lpPreviousCount); struct COORD { SHORT X; SHORT Y; } alias COORD *PCOORD; struct SMALL_RECT { SHORT Left; SHORT Top; SHORT Right; SHORT Bottom; } alias SMALL_RECT *PSMALL_RECT; struct KEY_EVENT_RECORD { BOOL bKeyDown; WORD wRepeatCount; WORD wVirtualKeyCode; WORD wVirtualScanCode; union { WCHAR UnicodeChar; CHAR AsciiChar; } DWORD dwControlKeyState; } alias KEY_EVENT_RECORD *PKEY_EVENT_RECORD; // // ControlKeyState flags // enum { RIGHT_ALT_PRESSED = 0x0001, // the right alt key is pressed. LEFT_ALT_PRESSED = 0x0002, // the left alt key is pressed. RIGHT_CTRL_PRESSED = 0x0004, // the right ctrl key is pressed. LEFT_CTRL_PRESSED = 0x0008, // the left ctrl key is pressed. SHIFT_PRESSED = 0x0010, // the shift key is pressed. NUMLOCK_ON = 0x0020, // the numlock light is on. SCROLLLOCK_ON = 0x0040, // the scrolllock light is on. CAPSLOCK_ON = 0x0080, // the capslock light is on. ENHANCED_KEY = 0x0100, // the key is enhanced. } struct MOUSE_EVENT_RECORD { COORD dwMousePosition; DWORD dwButtonState; DWORD dwControlKeyState; DWORD dwEventFlags; } alias MOUSE_EVENT_RECORD *PMOUSE_EVENT_RECORD; // // ButtonState flags // enum { FROM_LEFT_1ST_BUTTON_PRESSED = 0x0001, RIGHTMOST_BUTTON_PRESSED = 0x0002, FROM_LEFT_2ND_BUTTON_PRESSED = 0x0004, FROM_LEFT_3RD_BUTTON_PRESSED = 0x0008, FROM_LEFT_4TH_BUTTON_PRESSED = 0x0010, } // // EventFlags // enum { MOUSE_MOVED = 0x0001, DOUBLE_CLICK = 0x0002, } struct WINDOW_BUFFER_SIZE_RECORD { COORD dwSize; } alias WINDOW_BUFFER_SIZE_RECORD *PWINDOW_BUFFER_SIZE_RECORD; struct MENU_EVENT_RECORD { UINT dwCommandId; } alias MENU_EVENT_RECORD *PMENU_EVENT_RECORD; struct FOCUS_EVENT_RECORD { BOOL bSetFocus; } alias FOCUS_EVENT_RECORD *PFOCUS_EVENT_RECORD; struct INPUT_RECORD { WORD EventType; union { KEY_EVENT_RECORD KeyEvent; MOUSE_EVENT_RECORD MouseEvent; WINDOW_BUFFER_SIZE_RECORD WindowBufferSizeEvent; MENU_EVENT_RECORD MenuEvent; FOCUS_EVENT_RECORD FocusEvent; } } alias INPUT_RECORD *PINPUT_RECORD; // // EventType flags: // enum { KEY_EVENT = 0x0001, // Event contains key event record MOUSE_EVENT = 0x0002, // Event contains mouse event record WINDOW_BUFFER_SIZE_EVENT = 0x0004, // Event contains window change event record MENU_EVENT = 0x0008, // Event contains menu event record FOCUS_EVENT = 0x0010, // event contains focus change } struct CHAR_INFO { union { WCHAR UnicodeChar; CHAR AsciiChar; } WORD Attributes; } alias CHAR_INFO *PCHAR_INFO; // // Attributes flags: // enum { FOREGROUND_BLUE = 0x0001, // text color contains blue. FOREGROUND_GREEN = 0x0002, // text color contains green. FOREGROUND_RED = 0x0004, // text color contains red. FOREGROUND_INTENSITY = 0x0008, // text color is intensified. BACKGROUND_BLUE = 0x0010, // background color contains blue. BACKGROUND_GREEN = 0x0020, // background color contains green. BACKGROUND_RED = 0x0040, // background color contains red. BACKGROUND_INTENSITY = 0x0080, // background color is intensified. } struct CONSOLE_SCREEN_BUFFER_INFO { COORD dwSize; COORD dwCursorPosition; WORD wAttributes; SMALL_RECT srWindow; COORD dwMaximumWindowSize; } alias CONSOLE_SCREEN_BUFFER_INFO *PCONSOLE_SCREEN_BUFFER_INFO; struct CONSOLE_CURSOR_INFO { DWORD dwSize; BOOL bVisible; } alias CONSOLE_CURSOR_INFO *PCONSOLE_CURSOR_INFO; enum { ENABLE_PROCESSED_INPUT = 0x0001, ENABLE_LINE_INPUT = 0x0002, ENABLE_ECHO_INPUT = 0x0004, ENABLE_WINDOW_INPUT = 0x0008, ENABLE_MOUSE_INPUT = 0x0010, } enum { ENABLE_PROCESSED_OUTPUT = 0x0001, ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002, } BOOL PeekConsoleInputA(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer, DWORD nLength, LPDWORD lpNumberOfEventsRead); BOOL PeekConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer, DWORD nLength, LPDWORD lpNumberOfEventsRead); BOOL ReadConsoleInputA(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer, DWORD nLength, LPDWORD lpNumberOfEventsRead); BOOL ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer, DWORD nLength, LPDWORD lpNumberOfEventsRead); BOOL WriteConsoleInputA(HANDLE hConsoleInput, in INPUT_RECORD *lpBuffer, DWORD nLength, LPDWORD lpNumberOfEventsWritten); BOOL WriteConsoleInputW(HANDLE hConsoleInput, in INPUT_RECORD *lpBuffer, DWORD nLength, LPDWORD lpNumberOfEventsWritten); BOOL ReadConsoleOutputA(HANDLE hConsoleOutput, PCHAR_INFO lpBuffer, COORD dwBufferSize, COORD dwBufferCoord, PSMALL_RECT lpReadRegion); BOOL ReadConsoleOutputW(HANDLE hConsoleOutput, PCHAR_INFO lpBuffer, COORD dwBufferSize, COORD dwBufferCoord, PSMALL_RECT lpReadRegion); BOOL WriteConsoleOutputA(HANDLE hConsoleOutput, in CHAR_INFO *lpBuffer, COORD dwBufferSize, COORD dwBufferCoord, PSMALL_RECT lpWriteRegion); BOOL WriteConsoleOutputW(HANDLE hConsoleOutput, in CHAR_INFO *lpBuffer, COORD dwBufferSize, COORD dwBufferCoord, PSMALL_RECT lpWriteRegion); BOOL ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpCharacter, DWORD nLength, COORD dwReadCoord, LPDWORD lpNumberOfCharsRead); BOOL ReadConsoleOutputCharacterW(HANDLE hConsoleOutput, LPWSTR lpCharacter, DWORD nLength, COORD dwReadCoord, LPDWORD lpNumberOfCharsRead); BOOL ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD nLength, COORD dwReadCoord, LPDWORD lpNumberOfAttrsRead); BOOL WriteConsoleOutputCharacterA(HANDLE hConsoleOutput, LPCSTR lpCharacter, DWORD nLength, COORD dwWriteCoord, LPDWORD lpNumberOfCharsWritten); BOOL WriteConsoleOutputCharacterW(HANDLE hConsoleOutput, LPCWSTR lpCharacter, DWORD nLength, COORD dwWriteCoord, LPDWORD lpNumberOfCharsWritten); BOOL WriteConsoleOutputAttribute(HANDLE hConsoleOutput, in WORD *lpAttribute, DWORD nLength, COORD dwWriteCoord, LPDWORD lpNumberOfAttrsWritten); BOOL FillConsoleOutputCharacterA(HANDLE hConsoleOutput, CHAR cCharacter, DWORD nLength, COORD dwWriteCoord, LPDWORD lpNumberOfCharsWritten); BOOL FillConsoleOutputCharacterW(HANDLE hConsoleOutput, WCHAR cCharacter, DWORD nLength, COORD dwWriteCoord, LPDWORD lpNumberOfCharsWritten); BOOL FillConsoleOutputAttribute(HANDLE hConsoleOutput, WORD wAttribute, DWORD nLength, COORD dwWriteCoord, LPDWORD lpNumberOfAttrsWritten); BOOL GetConsoleMode(HANDLE hConsoleHandle, LPDWORD lpMode); BOOL GetNumberOfConsoleInputEvents(HANDLE hConsoleInput, LPDWORD lpNumberOfEvents); BOOL GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, PCONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo); COORD GetLargestConsoleWindowSize( HANDLE hConsoleOutput); BOOL GetConsoleCursorInfo(HANDLE hConsoleOutput, PCONSOLE_CURSOR_INFO lpConsoleCursorInfo); BOOL GetNumberOfConsoleMouseButtons( LPDWORD lpNumberOfMouseButtons); BOOL SetConsoleMode(HANDLE hConsoleHandle, DWORD dwMode); BOOL SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput); BOOL FlushConsoleInputBuffer(HANDLE hConsoleInput); BOOL SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize); BOOL SetConsoleCursorPosition(HANDLE hConsoleOutput, COORD dwCursorPosition); BOOL SetConsoleCursorInfo(HANDLE hConsoleOutput, in CONSOLE_CURSOR_INFO *lpConsoleCursorInfo); BOOL ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, in SMALL_RECT *lpScrollRectangle, in SMALL_RECT *lpClipRectangle, COORD dwDestinationOrigin, in CHAR_INFO *lpFill); BOOL ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, in SMALL_RECT *lpScrollRectangle, in SMALL_RECT *lpClipRectangle, COORD dwDestinationOrigin, in CHAR_INFO *lpFill); BOOL SetConsoleWindowInfo(HANDLE hConsoleOutput, BOOL bAbsolute, in SMALL_RECT *lpConsoleWindow); BOOL SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttributes); alias BOOL function(DWORD CtrlType) PHANDLER_ROUTINE; BOOL SetConsoleCtrlHandler(PHANDLER_ROUTINE HandlerRoutine, BOOL Add); BOOL GenerateConsoleCtrlEvent( DWORD dwCtrlEvent, DWORD dwProcessGroupId); BOOL AllocConsole(); BOOL FreeConsole(); DWORD GetConsoleTitleA(LPSTR lpConsoleTitle, DWORD nSize); DWORD GetConsoleTitleW(LPWSTR lpConsoleTitle, DWORD nSize); BOOL SetConsoleTitleA(LPCSTR lpConsoleTitle); BOOL SetConsoleTitleW(LPCWSTR lpConsoleTitle); BOOL ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved); BOOL ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved); BOOL WriteConsoleA(HANDLE hConsoleOutput, in void *lpBuffer, DWORD nNumberOfCharsToWrite, LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved); BOOL WriteConsoleW(HANDLE hConsoleOutput, in void *lpBuffer, DWORD nNumberOfCharsToWrite, LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved); HANDLE CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode, in SECURITY_ATTRIBUTES *lpSecurityAttributes, DWORD dwFlags, LPVOID lpScreenBufferData); UINT GetConsoleCP(); BOOL SetConsoleCP( UINT wCodePageID); UINT GetConsoleOutputCP(); BOOL SetConsoleOutputCP(UINT wCodePageID); enum { CONSOLE_TEXTMODE_BUFFER = 1, } enum { SM_CXSCREEN = 0, SM_CYSCREEN = 1, SM_CXVSCROLL = 2, SM_CYHSCROLL = 3, SM_CYCAPTION = 4, SM_CXBORDER = 5, SM_CYBORDER = 6, SM_CXDLGFRAME = 7, SM_CYDLGFRAME = 8, SM_CYVTHUMB = 9, SM_CXHTHUMB = 10, SM_CXICON = 11, SM_CYICON = 12, SM_CXCURSOR = 13, SM_CYCURSOR = 14, SM_CYMENU = 15, SM_CXFULLSCREEN = 16, SM_CYFULLSCREEN = 17, SM_CYKANJIWINDOW = 18, SM_MOUSEPRESENT = 19, SM_CYVSCROLL = 20, SM_CXHSCROLL = 21, SM_DEBUG = 22, SM_SWAPBUTTON = 23, SM_RESERVED1 = 24, SM_RESERVED2 = 25, SM_RESERVED3 = 26, SM_RESERVED4 = 27, SM_CXMIN = 28, SM_CYMIN = 29, SM_CXSIZE = 30, SM_CYSIZE = 31, SM_CXFRAME = 32, SM_CYFRAME = 33, SM_CXMINTRACK = 34, SM_CYMINTRACK = 35, SM_CXDOUBLECLK = 36, SM_CYDOUBLECLK = 37, SM_CXICONSPACING = 38, SM_CYICONSPACING = 39, SM_MENUDROPALIGNMENT = 40, SM_PENWINDOWS = 41, SM_DBCSENABLED = 42, SM_CMOUSEBUTTONS = 43, SM_CXFIXEDFRAME = SM_CXDLGFRAME, SM_CYFIXEDFRAME = SM_CYDLGFRAME, SM_CXSIZEFRAME = SM_CXFRAME, SM_CYSIZEFRAME = SM_CYFRAME, SM_SECURE = 44, SM_CXEDGE = 45, SM_CYEDGE = 46, SM_CXMINSPACING = 47, SM_CYMINSPACING = 48, SM_CXSMICON = 49, SM_CYSMICON = 50, SM_CYSMCAPTION = 51, SM_CXSMSIZE = 52, SM_CYSMSIZE = 53, SM_CXMENUSIZE = 54, SM_CYMENUSIZE = 55, SM_ARRANGE = 56, SM_CXMINIMIZED = 57, SM_CYMINIMIZED = 58, SM_CXMAXTRACK = 59, SM_CYMAXTRACK = 60, SM_CXMAXIMIZED = 61, SM_CYMAXIMIZED = 62, SM_NETWORK = 63, SM_CLEANBOOT = 67, SM_CXDRAG = 68, SM_CYDRAG = 69, SM_SHOWSOUNDS = 70, SM_CXMENUCHECK = 71, SM_CYMENUCHECK = 72, SM_SLOWMACHINE = 73, SM_MIDEASTENABLED = 74, SM_CMETRICS = 75, } int GetSystemMetrics(int nIndex); enum : DWORD { STILL_ACTIVE = (0x103), } DWORD TlsAlloc(); LPVOID TlsGetValue(DWORD); BOOL TlsSetValue(DWORD, LPVOID); BOOL TlsFree(DWORD); struct STARTUPINFO { DWORD cb = STARTUPINFO.sizeof; LPSTR lpReserved; LPSTR lpDesktop; LPSTR lpTitle; DWORD dwX; DWORD dwY; DWORD dwXSize; DWORD dwYSize; DWORD dwXCountChars; DWORD dwYCountChars; DWORD dwFillAttribute; DWORD dwFlags; WORD wShowWindow; WORD cbReserved2; LPBYTE lpReserved2; HANDLE hStdInput; HANDLE hStdOutput; HANDLE hStdError; } struct STARTUPINFO_W { DWORD cb = STARTUPINFO_W.sizeof; LPWSTR lpReserved; LPWSTR lpDesktop; LPWSTR lpTitle; DWORD dwX; DWORD dwY; DWORD dwXSize; DWORD dwYSize; DWORD dwXCountChars; DWORD dwYCountChars; DWORD dwFillAttribute; DWORD dwFlags; WORD wShowWindow; WORD cbReserved2; LPBYTE lpReserved2; HANDLE hStdInput; HANDLE hStdOutput; HANDLE hStdError; } alias STARTUPINFO *LPSTARTUPINFO; alias STARTUPINFO_W *LPSTARTUPINFO_W; struct PROCESS_INFORMATION { HANDLE hProcess; HANDLE hThread; DWORD dwProcessId; DWORD dwThreadId; } alias PROCESS_INFORMATION *LPPROCESS_INFORMATION; export { BOOL CreateProcessA(LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCSTR lpCurrentDirectory, LPSTARTUPINFO lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); BOOL CreateProcessW(LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFO_W lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); BOOL CreatePipe(PHANDLE hReadPipe, PHANDLE hWritePipe, LPSECURITY_ATTRIBUTES lpPipeAttributes, DWORD nSize); } enum { STARTF_USESTDHANDLES = 0x00000100 } enum { CREATE_NO_WINDOW = 0x08000000 } // shellapi.h HINSTANCE ShellExecuteA(HWND hwnd, LPCSTR lpOperation, LPCSTR lpFile, LPCSTR lpParameters, LPCSTR lpDirectory, INT nShowCmd); HINSTANCE ShellExecuteW(HWND hwnd, LPCWSTR lpOperation, LPCWSTR lpFile, LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd); UINT_PTR SetTimer(HWND hwnd, UINT_PTR nIDEvent, UINT uElapse, TIMERPROC lpTimerFunc); BOOL KillTimer(HWND hwnd, UINT_PTR nIDEvent);
D
module mysql.mysql; import mysql.binding; public import mysql.mysql_result; public import mysql.mysql_row; import mysql.query_interface; import std.stdio; import std.exception; import std.typecons; class MysqlDatabaseException : Exception { this(string msg, string file = __FILE__, size_t line = __LINE__) { super(msg, file, line); } } class Mysql { private string _dbname; private MYSQL* mysql; private string lastErrorMsg; this(string host, string user, string pass, string db) { initMysql(); connect(host, 0, user, pass, db, null); } this(string host, uint port, string user, string pass, string db, string charset = null) { initMysql(); connect(host, port, user, pass, db, null, charset); } this(string host, string user, string pass) { initMysql(); connect(host, user, pass); } this() { initMysql(); } private void initMysql () { mysql = enforceEx!(MysqlDatabaseException)(mysql_init(null), "Couldn't init mysql"); setReconnect(true); } void connect(string host, uint port, string user, string pass, string db, string unixSocket, string charset = null) { enforceEx!(MysqlDatabaseException)( mysql_real_connect(mysql, toCstring(host), toCstring(user), toCstring(pass), toCstring(db), port, unixSocket ? toCstring(unixSocket) : null, 0), error() ); _dbname = db; if (charset != null) setCharset(charset); } void connect(string host, uint port, string user, string pass, string db, string charset="utf8") { connect(host, port, user, pass, db, null, charset); } void connect(string host, string user, string pass, string db) { connect(host, 0, user, pass, db, null); } void connect(string host, string user, string pass) { connect(host, 0, user, pass, null, null); } int selectDb(string newDbName) { auto res = mysql_select_db(mysql, toCstring(newDbName)); _dbname = newDbName; return res; } string dbname() { return _dbname; } int setOption(mysql_option option, const void* value) { return mysql_options(mysql, option, &value); } int setReconnect(bool value) { return setOption(mysql_option.MYSQL_OPT_RECONNECT, &value); } int setConnectTimeout(int value) { return setOption(mysql_option.MYSQL_OPT_CONNECT_TIMEOUT, cast(const(char*))value); } int setCharset(string charset) { return mysql_set_character_set(mysql, toCstring(charset)); } string charset() { return fromCstring(mysql_character_set_name(mysql)); } static ulong clientVersion() { return mysql_get_client_version(); } static string clientVersionString() { return fromCstring(mysql_get_client_info()); } void startTransaction() { query("START TRANSACTION"); } string error() { return fromCstring(mysql_error(mysql)); } void close() { if (mysql) { mysql_close(mysql); mysql = null; } } ~this() { close(); } // MYSQL API call int lastInsertId() { return cast(int) mysql_insert_id(mysql); } // MYSQL API call int affectedRows() { return cast(int) mysql_affected_rows(mysql); } // MYSQL API call string escape(string str) { ubyte[] buffer = new ubyte[str.length * 2 + 1]; buffer.length = mysql_real_escape_string(mysql, buffer.ptr, cast(cstring) str.ptr, cast(uint) str.length); return cast(string) buffer; } // MYSQL API call MysqlResult queryImpl(string sql) { enforceEx!(MysqlDatabaseException)( !mysql_query(mysql, toCstring(sql)), error() ~ " :::: " ~ sql); return new MysqlResult(mysql_store_result(mysql), sql); } // To be used with commands that do not return a result (INSERT, UPDATE, etc...) bool execImpl(string sql) { bool success = false; if (mysql_query(mysql, toCstring(sql)) == 0) { success = true; this.lastErrorMsg = ""; } else { this.lastErrorMsg = error() ~ " :::: " ~ sql; } return success; } // MYSQL API call int ping() { return mysql_ping(mysql); } // MYSQL API call string stat() { return fromCstring(mysql_stat(mysql)); } // ====== helpers ====== // Smart interface thing. // accept multiple attributes and make replacement of '?' in sql // like this: // auto row = mysql.query("select * from table where id = ?", 10); MysqlResult query(T...)(string sql, T t) { return queryImpl(QueryInterface.makeQuery(this, sql, t)); } bool exec(T...)(string sql, T t) { return execImpl(QueryInterface.makeQuery(this, sql, t)); } string dbErrorMsg() { return this.lastErrorMsg; } // simply make mysq.query().front // and if no rows then raise an exception Nullable!MysqlRow queryOneRow(string file = __FILE__, size_t line = __LINE__, T...)(string sql, T t) { auto res = query(sql, t); if (res.empty) { return Nullable!MysqlRow.init; } auto row = res.front; return Nullable!MysqlRow(row); } /* ResultByDataObject!R queryDataObject(R = DataObject, T...)(string sql, T t) { // modify sql for the best data object grabbing sql = fixupSqlForDataObjectUse(sql); auto magic = query(sql, t); return ResultByDataObject!R(cast(MysqlResult) magic, this); } ResultByDataObject!R queryDataObjectWithCustomKeys(R = DataObject, T...)(string[string] keyMapping, string sql, T t) { sql = fixupSqlForDataObjectUse(sql, keyMapping); auto magic = query(sql, t); return ResultByDataObject!R(cast(MysqlResult) magic, this); } */ } /* struct ResultByDataObject(ObjType) if (is(ObjType : DataObject)) { MysqlResult result; Mysql mysql; this(MysqlResult r, Mysql mysql) { result = r; auto fields = r.fields(); this.mysql = mysql; foreach(i, f; fields) { string tbl = fromCstring(f.org_table is null ? f.table : f.org_table, f.org_table is null ? f.table_length : f.org_table_length); mappings[fromCstring(f.name)] = tuple( tbl, fromCstring(f.org_name is null ? f.name : f.org_name, f.org_name is null ? f.name_length : f.org_name_length)); } } Tuple!(string, string)[string] mappings; ulong length() { return result.length; } bool empty() { return result.empty; } void popFront() { result.popFront(); } ObjType front() { return new ObjType(mysql, result.front.toAA, mappings); } // would it be good to add a new() method? would be valid even if empty // it'd just fill in the ID's at random and allow you to do the rest @disable this(this) { } } */ class EmptyResultException : Exception { this(string message, string file = __FILE__, size_t line = __LINE__) { super(message, file, line); } } /* void main() { auto mysql = new Mysql("localhost", "uname", "password", "test"); scope(exit) delete mysql; mysql.query("INSERT INTO users (id, password) VALUES (?, ?)", 10, "lol"); foreach(row; mysql.query("SELECT * FROM users")) { writefln("%s %s %s %s", row["id"], row[0], row[1], row["username"]); } } */ /+ mysql.linq.tablename.field[key] // select field from tablename where id = key mysql.link["name"].table.field[key] // select field from table where name = key auto q = mysql.prepQuery("select id from table where something"); q.sort("name"); q.limit(start, count); q.page(3, pagelength = ?); q.execute(params here); // returns the same Result range as query +/ /* void main() { auto db = new Mysql("localhost", "uname", "password", "test"); foreach(item; db.queryDataObject("SELECT users.*, username FROM users, password_manager_accounts WHERE password_manager_accounts.user_id = users.id LIMIT 5")) { writefln("item: %s, %s", item.id, item.username); item.first = "new"; item.last = "new2"; item.username = "kill"; //item.commitChanges(); } } */ /* Copyright: Adam D. Ruppe, 2009 - 2011 License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>. Authors: Adam D. Ruppe, with contributions from Nick Sabalausky Copyright Adam D. Ruppe 2009 - 2011. 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) */
D
module engine.core.containers.stack; import engine.core.containers.slist; alias Stack = SStack; struct SStack( T ) { private: SList!T lelements; public: void push( T elem ) { lelements.insertFront( elem ); } T pop() { T value; if ( lelements.length > 0 ) { value = lelements.head.data; lelements.removeFront(); } return value; } size_t length() { return lelements.length; } bool isEmpty() { return length == 0; } void free() { lelements.free(); } }
D
// PERMUTE_ARGS: // EXTRA_FILES: imports/testmangle.d /* TEST_OUTPUT: --- _D7imports10testmangle12detectMangleFPSQBlQBg6DetectZQq _D7imports10testmangle__T10DetectTmplTiZQpFNaNbNiNfZv true false --- */ module link6574; import imports.testmangle; enum Method { A, B, } @safe @nogc pure nothrow: enum FZi = "FNaNbNiNfZi"; // pure nothrow @nogc @safe int foo(Method method = Method.A)() { static assert(foo.mangleof == "_D8link6574"~tl!"28"~"__T3fooVE"~id!("8link6574","Qs")~"6Methodi0Z"~id!("3foo","Qs")~FZi); return 10 * foo!method(); } int foo(Method method : Method.A)() { static assert(foo.mangleof == "_D8link6574"~tl!"29"~"__T3fooHVE"~id!("8link6574","Qt")~"6Methodi0Z"~id!("3foo","Qt")~FZi); return 2; } int foo(Method method : Method.B)() { static assert(0); return 3; } int bar(Method method = Method.B)() { static assert(bar.mangleof == "_D8link6574"~tl!"28"~"__T3barVE"~id!("8link6574","Qs")~"6Methodi1Z"~id!("3bar","Qs")~FZi); return 10 * bar!method(); } int bar(Method method : Method.A)() { static assert(0); return 2; } int bar(Method method : Method.B)() { static assert(bar.mangleof == "_D8link6574"~tl!"29"~"__T3barHVE"~id!("8link6574","Qt")~"6Methodi1Z"~id!("3bar","Qt")~FZi); return 3; } void main() { assert(foo!() == 10 * 2); assert(foo() == 10 * 2); assert(bar!() == 10 * 3); assert(bar() == 10 * 3); }
D
/******************************************************************************* copyright: Copyright (c) 2008 Kris Bell. все rights reserved license: BSD стиль: $(LICENSE) version: Initial release: April 2008 author: Kris Since: 0.99.7 *******************************************************************************/ module util.container.more.Vector; private import exception : ArrayBoundsException; private import cidrus : memmove; /****************************************************************************** A вектор of the given значение-тип V, with maximum глубина Размер. Note that this does no память allocation of its own when Размер != 0, и does куча allocation when Размер == 0. Thus you can have a fixed-размер low-overhead экземпляр, or a куча oriented экземпляр. ******************************************************************************/ struct Вектор (V, цел Размер = 0) { alias добавь сунь; alias срез opSlice; alias сунь opCatAssign; static if (Размер == 0) { private бцел глубина; private V[] вектор; } else { private бцел глубина; private V[Размер] вектор; } /*********************************************************************** Clear the вектор ***********************************************************************/ Вектор* очисть () { глубина = 0; return this; } /*********************************************************************** Return глубина of the вектор ***********************************************************************/ бцел размер () { return глубина; } /*********************************************************************** Return остаток неиспользовано slots ***********************************************************************/ бцел неиспользовано () { return вектор.length - глубина; } /*********************************************************************** Returns a (shallow) клонируй of this вектор ***********************************************************************/ Вектор клонируй () { Вектор v; static if (Размер == 0) v.вектор.length = вектор.length; v.вектор[0..глубина] = вектор[0..глубина]; v.глубина = глубина; return v; } /********************************************************************** Добавь a значение в_ the вектор. Throws an исключение when the вектор is full **********************************************************************/ V* добавь (V значение) { static if (Размер == 0) { if (глубина >= вектор.length) вектор.length = вектор.length + 64; вектор[глубина++] = значение; } else { if (глубина < вектор.length) вектор[глубина++] = значение; else ошибка (__LINE__); } return &вектор[глубина-1]; } /********************************************************************** Добавь a значение в_ the вектор. Throws an исключение when the вектор is full **********************************************************************/ V* добавь () { static if (Размер == 0) { if (глубина >= вектор.length) вектор.length = вектор.length + 64; } else if (глубина >= вектор.length) ошибка (__LINE__); auto p = &вектор[глубина++]; *p = V.init; return p; } /********************************************************************** Добавь a series of значения в_ the вектор. Throws an исключение when the вектор is full **********************************************************************/ Вектор* добавь (V[] значение...) { foreach (v; значение) добавь (v); return this; } /********************************************************************** Удали и return the most recent добавьition в_ the вектор. Throws an исключение when the вектор is пустой **********************************************************************/ V удали () { if (глубина) return вектор[--глубина]; return ошибка (__LINE__); } /********************************************************************** Index вектор записи, where a zero индекс represents the oldest вектор Запись. Throws an исключение when the given индекс is out of range **********************************************************************/ V удали (бцел i) { if (i < глубина) { if (i is глубина-1) return удали; --глубина; auto v = вектор [i]; memmove (вектор.ptr+i, вектор.ptr+i+1, V.sizeof * глубина-i); return v; } return ошибка (__LINE__); } /********************************************************************** Index вектор записи, as though it were an Массив Throws an исключение when the given индекс is out of range **********************************************************************/ V opIndex (бцел i) { if (i < глубина) return вектор [i]; return ошибка (__LINE__); } /********************************************************************** Assign вектор записи as though it were an Массив. Throws an исключение when the given индекс is out of range **********************************************************************/ V opIndexAssign (V значение, бцел i) { if (i < глубина) { вектор[i] = значение; return значение; } return ошибка (__LINE__); } /********************************************************************** Return the вектор as an Массив of значения, where the первый Массив Запись represents the oldest значение. Doing a foreach() on the returned Массив will traverse in the opposite direction of foreach() upon a вектор **********************************************************************/ V[] срез () { return вектор [0 .. глубина]; } /********************************************************************** Throw an исключение **********************************************************************/ private V ошибка (т_мера строка) { throw new ArrayBoundsException (__FILE__, строка); } /*********************************************************************** Iterate из_ the most recent в_ the oldest вектор записи ***********************************************************************/ цел opApply (цел delegate(ref V значение) дг) { цел результат; for (цел i=глубина; i-- && результат is 0;) результат = дг (вектор [i]); return результат; } /*********************************************************************** Iterate из_ the most recent в_ the oldest вектор записи ***********************************************************************/ цел opApply (цел delegate(ref V значение, ref бул затуши) дг) { цел результат; for (цел i=глубина; i-- && результат is 0;) { auto затуши = нет; результат = дг (вектор[i], затуши); if (затуши) удали (i); } return результат; } } /******************************************************************************* *******************************************************************************/ debug (Вектор) { import io.Stdout; проц main() { Вектор!(цел, 0) v; v.добавь (1); Вектор!(цел, 10) s; Стдвыв.форматнс ("добавь four"); s.добавь (1); s.добавь (2); s.добавь (3); s.добавь (4); foreach (v; s) Стдвыв.форматнс ("{}", v); s = s.клонируй; Стдвыв.форматнс ("pop one: {}", s.удали); foreach (v; s) Стдвыв.форматнс ("{}", v); Стдвыв.форматнс ("удали[1]: {}", s.удали(1)); foreach (v; s) Стдвыв.форматнс ("{}", v); Стдвыв.форматнс ("удали two"); s.удали; s.удали; foreach (v; s) Стдвыв.форматнс ("> {}", v); s.добавь (1); s.добавь (2); s.добавь (3); s.добавь (4); foreach (v, ref k; s) k = да; Стдвыв.форматнс ("размер {}", s.размер); } }
D
module gold.lexer.issue77; import std.stdio; /**/ /* /* */ /* //*/ /*/*/ void main(string[] args){ }
D
/home/martogod/RustProgramms/QuestGiverRustGame/target/debug/build/num-complex-9a322b1492549fae/build_script_build-9a322b1492549fae: /home/martogod/.cargo/registry/src/github.com-1ecc6299db9ec823/num-complex-0.2.4/build.rs /home/martogod/RustProgramms/QuestGiverRustGame/target/debug/build/num-complex-9a322b1492549fae/build_script_build-9a322b1492549fae.d: /home/martogod/.cargo/registry/src/github.com-1ecc6299db9ec823/num-complex-0.2.4/build.rs /home/martogod/.cargo/registry/src/github.com-1ecc6299db9ec823/num-complex-0.2.4/build.rs:
D
module tango.stdc.math; pragma(lib, "rulada.lib"); public import rt.core.stdc.math;
D
module bass.error; import std.string; class BASSError : object.Exception { this(char[] s) { super(s); } } char[] BASSErrorString(int errCode) { switch(errCode) { case 0: return "BASS_OK"; case 1: return "BASS_ERROR_MEM"; case 2: return "BASS_ERROR_FILEOPEN"; case 3: return "BASS_ERROR_DRIVER"; case 4: return "BASS_ERROR_BUFLOST"; case 5: return "BASS_ERROR_HANDLE"; case 6: return "BASS_ERROR_FORMAT"; case 7: return "BASS_ERROR_POSITION"; case 8: return "BASS_ERROR_INIT"; case 9: return "BASS_ERROR_START"; case 14: return "BASS_ERROR_ALREADY"; case 18: return "BASS_ERROR_NOCHAN"; case 19: return "BASS_ERROR_ILLTYPE"; case 20: return "BASS_ERROR_ILLPARAM"; case 21: return "BASS_ERROR_NO3D"; case 22: return "BASS_ERROR_NOEAX"; case 23: return "BASS_ERROR_DEVICE"; case 24: return "BASS_ERROR_NOPLAY"; case 25: return "BASS_ERROR_FREQ"; case 27: return "BASS_ERROR_NOTFILE"; case 29: return "BASS_ERROR_NOHW"; case 31: return "BASS_ERROR_EMPTY"; case 32: return "BASS_ERROR_NONET"; case 33: return "BASS_ERROR_CREATE"; case 34: return "BASS_ERROR_NOFX"; case 37: return "BASS_ERROR_NOTAVAIL"; case 38: return "BASS_ERROR_DECODE"; case 39: return "BASS_ERROR_DX"; case 40: return "BASS_ERROR_TIMEOUT"; case 41: return "BASS_ERROR_FILEFORM"; case 42: return "BASS_ERROR_SPEAKER"; case 43: return "BASS_ERROR_VERSION"; case 44: return "BASS_ERROR_CODEC"; case 45: return "BASS_ERROR_ENDED"; case -1: return "BASS_ERROR_UNKNOWN"; default: return "unknown BASS error"; } }
D
/workspaces/競技プログラミング/AtCoder/本番/AHC/AHC001/ded8fd3366b4ff0b0d7d053f553cdb84/tools/target/rls/debug/build/proc-macro2-86543a6b4391c4a5/build_script_build-86543a6b4391c4a5: /usr/local/cargo/registry/src/github.com-1ecc6299db9ec823/proc-macro2-0.4.30/build.rs /workspaces/競技プログラミング/AtCoder/本番/AHC/AHC001/ded8fd3366b4ff0b0d7d053f553cdb84/tools/target/rls/debug/build/proc-macro2-86543a6b4391c4a5/build_script_build-86543a6b4391c4a5.d: /usr/local/cargo/registry/src/github.com-1ecc6299db9ec823/proc-macro2-0.4.30/build.rs /usr/local/cargo/registry/src/github.com-1ecc6299db9ec823/proc-macro2-0.4.30/build.rs:
D
instance TPL_1447_TEMPLER(NPC_DEFAULT) { name[0] = NAME_MADTEMPLAR; npctype = NPCTYPE_GUARD; guild = GIL_GUR; level = 50; voice = 8; id = 1447; attribute[ATR_STRENGTH] = 70; attribute[ATR_DEXTERITY] = 65; attribute[ATR_MANA_MAX] = 0; attribute[ATR_MANA] = 0; attribute[ATR_HITPOINTS_MAX] = 250; attribute[ATR_HITPOINTS] = 250; protection[PROT_BLUNT] = 90; protection[PROT_EDGE] = 90; protection[PROT_POINT] = 140; protection[PROT_FIRE] = 50; protection[PROT_FLY] = 80; protection[PROT_MAGIC] = 75; Mdl_SetVisual(self,"HUMANS.MDS"); Mdl_ApplyOverlayMds(self,"Humans_Mage.mds"); Mdl_SetVisualBody(self,"hum_body_Naked0",1,1,"Hum_Head_Bald",117,2,tpl_armor_m); b_scale(self); Mdl_SetModelFatness(self,-1); fight_tactic = FAI_HUMAN_STRONG; Npc_SetTalentSkill(self,NPC_TALENT_2H,1); CreateInvItem(self,itmw_2h_sword_light_01); CreateInvItem(self,itfosoup); CreateInvItem(self,itmijoint_1); CreateInvItem(self,itfo_potion_health_02); daily_routine = rtn_ot_1447; }; func void rtn_start_1447() { ta_hostileguard(0,0,21,0,"TPL_408"); ta_hostileguard(21,0,24,0,"TPL_408"); }; func void rtn_ot_1447() { ta_hostileguard(0,0,21,0,"TPL_139"); ta_hostileguard(21,0,24,0,"TPL_139"); };
D
import engine; import global; struct OMChar { dchar value; this ( dchar value_ ) { value = value_; } } struct OMOutString { string value; bool newline; this ( string value_, bool newline_ = false ) { value = value_; newline = newline_; } this ( OMChar[] chars, bool newline_ = false ) { import functional; this(chars.map!(n => n.value).array.to!string, newline_); } } OMChar[] To_OMChar ( string value ) { import functional; return value.map!(n => OMChar(n)).array; } alias OMChar[] OMString; auto CreateOMString ( string value ) { import functional; return value.map!(n => OMChar(n)).array; } import window; void Output ( inout Window window, OMString str ) { auto info = window.RWindow_Info; terminal.layer(info.layer); terminal.crop(info.start_x, info.start_y, info.width, info.height); terminal.clear_area(0, 0, 80, 26); import std.stdio; for ( int it, y; it < str.length || y >= info.height; ++ y) { auto out_str = window.Format_String(str, info, it); terminal.print(info.start_x, y, out_str.value); } }
D
module sevion.ad; import sevion.schema: IAdItem; struct Ad { IAdItem item; bool isPublished; int id; int addedOn; int expireOn; int priority; this(IAdItem itemValue) { item = itemValue; } }
D
/Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/DerivedData/NotebookAnimal/Build/Intermediates/NotebookAnimal.build/Debug-iphonesimulator/NotebookAnimal.build/Objects-normal/x86_64/iCloudNotebookPetTableViewControllerTableViewController.o : /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/iCloudNotebookPetTableViewControllerTableViewController.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal+CoreDataProperties.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/iCloudCustomTableViewCell.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/CustomTableViewCell.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/AddPetViewController.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/NotebookPetTablewViewController.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/AppDelegate.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CloudKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Contacts.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/CoreData.swiftmodule /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/DerivedData/NotebookAnimal/Build/Intermediates/NotebookAnimal.build/Debug-iphonesimulator/NotebookAnimal.build/Objects-normal/x86_64/iCloudNotebookPetTableViewControllerTableViewController~partial.swiftmodule : /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/iCloudNotebookPetTableViewControllerTableViewController.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal+CoreDataProperties.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/iCloudCustomTableViewCell.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/CustomTableViewCell.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/AddPetViewController.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/NotebookPetTablewViewController.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/AppDelegate.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CloudKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Contacts.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/CoreData.swiftmodule /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/DerivedData/NotebookAnimal/Build/Intermediates/NotebookAnimal.build/Debug-iphonesimulator/NotebookAnimal.build/Objects-normal/x86_64/iCloudNotebookPetTableViewControllerTableViewController~partial.swiftdoc : /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/iCloudNotebookPetTableViewControllerTableViewController.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal+CoreDataProperties.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/iCloudCustomTableViewCell.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/CustomTableViewCell.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/AddPetViewController.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/NotebookPetTablewViewController.swift /Users/nikolay/Documents/FolderWorkSwift/NotebookAnimal/NotebookAnimal/AppDelegate.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CloudKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Contacts.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/CoreData.swiftmodule
D
static foreach (thing; things){pragma(msg,thing);} static foreach_reverse (thing; things){pragma(msg,thing);} static foreach (thing; things) pragma(msg,thing); static foreach_reverse (thing; things) pragma(msg,thing);
D
/* * FTGL - OpenGL font library * * Copyright (c) 2001-2004 Henry Maddocks <ftgl@opengl.geek.nz> * Copyright (c) 2008 Sam Hocevar <sam@zoy.org> * Copyright (c) 2008 Sean Morrison <learner@brlcad.org> * * 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 dftgl.FTPolyGlyph; import dfreetype.ft; import dftgl.FTGlyph; extern(System): /** * Create a specialisation of FTGLglyph for creating tessellated * polygon glyphs. * * @param glyph The Freetype glyph to be processed * @param outset outset contour size * @param useDisplayList Enable or disable the use of Display Lists * for this glyph * <code>true</code> turns ON display lists. * <code>false</code> turns OFF display lists. * @return An FTGLglyph* object. */ FTGLglyph *ftglCreatePolygonGlyph(FT_GlyphSlot glyph, float outset, int useDisplayList);
D
module dopt.core.cuda.nnet.cudnn5; import std.algorithm; import std.array; import std.functional; import dopt.core.cuda; import dopt.core.ops; import derelict.cuda; import derelict.cudnn5; package { void initializeCuDNN5() { DerelictCuDNN5.load(); registerCUDAKernel("convolution", toDelegate(&cudaKernelCtr!ConvolutionForward)); registerCUDAKernel("convolutionFeaturesGrad", toDelegate(&cudaKernelCtr!ConvolutionFeaturesGrad)); registerCUDAKernel("convolutionFiltersGrad", toDelegate(&cudaKernelCtr!ConvolutionFiltersGrad)); registerCUDAKernel("maxpool", toDelegate(&cudaKernelCtr!MaxpoolForward)); registerCUDAKernel("maxpoolGrad", toDelegate(&cudaKernelCtr!MaxpoolGrad)); registerCUDAKernel("softmax", toDelegate(&cudaKernelCtr!Softmax)); registerCUDAKernel("softmaxGrad", toDelegate(&cudaKernelCtr!SoftmaxGrad)); registerCUDAKernel("relu", toDelegate(&cudaKernelCtr!ReLU)); registerCUDAKernel("reluGrad", toDelegate(&cudaKernelCtr!ReLUGrad)); registerCUDAKernel("addBias", toDelegate(&cudaKernelCtr!AddBias)); registerCUDAKernel("addBiasGrad", toDelegate(&cudaKernelCtr!AddBiasGrad)); registerCUDAKernel("batchNormTrain", toDelegate(&cudaKernelCtr!BatchNormTrain)); registerCUDAKernel("batchNormGrad", toDelegate(&cudaKernelCtr!BatchNormGrad)); registerCUDAKernel("batchNormInference", toDelegate(&cudaKernelCtr!BatchNormInference)); cudnnCreate(&handle); } } private { cudnnHandle_t handle; void cudnnCheck(cudnnStatus_t status, string mod = __MODULE__, size_t line = __LINE__) { import std.conv : to; import std.exception : enforce; enforce(status == CUDNN_STATUS_SUCCESS, mod ~ "(" ~ line.to!string ~ "): Failed to execute cuDNN function." ~ " Error code: " ~ status.to!string); } CUDAKernel cudaKernelCtr(K)(Operation op) { return new K(op); } class ConvolutionBase : CUDAKernel { this(Operation op, int[] inShape, int[] filterShape, int[] outShape) { mOp = op; int padH = 0; int padW = 0; int strideY = 1; int strideX = 1; auto padding = op.attributes["padding"].get!(size_t[]); padH = cast(int)padding[0]; padW = cast(int)padding[1]; auto stride = op.attributes["stride"].get!(size_t[]); strideY = cast(int)stride[0]; strideX = cast(int)stride[1]; cudnnCreateTensorDescriptor(&xDesc).cudnnCheck(); cudnnCreateFilterDescriptor(&wDesc).cudnnCheck(); cudnnCreateConvolutionDescriptor(&convDesc).cudnnCheck(); cudnnCreateTensorDescriptor(&yDesc).cudnnCheck(); cudnnSetTensor4dDescriptor(xDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, inShape[0], inShape[1], inShape[2], inShape[3]).cudnnCheck(); cudnnSetFilter4dDescriptor(wDesc, CUDNN_DATA_FLOAT, CUDNN_TENSOR_NCHW, filterShape[0], filterShape[1], filterShape[2], filterShape[3]).cudnnCheck(); cudnnSetConvolution2dDescriptor_v5(convDesc, padH, padW, strideY, strideX, 1, 1, CUDNN_CONVOLUTION, CUDNN_DATA_FLOAT).cudnnCheck(); cudnnSetTensor4dDescriptor(yDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, outShape[0], outShape[1], outShape[2], outShape[3]).cudnnCheck(); } ~this() { cudnnDestroyFilterDescriptor(wDesc).cudnnCheck(); cudnnDestroyTensorDescriptor(yDesc).cudnnCheck(); cudnnDestroyConvolutionDescriptor(convDesc).cudnnCheck(); cudnnDestroyTensorDescriptor(xDesc).cudnnCheck(); } abstract void execute(const(CUDABuffer)[] inputs, CUDABuffer output); Operation mOp; cudnnTensorDescriptor_t xDesc; cudnnFilterDescriptor_t wDesc; cudnnTensorDescriptor_t bDesc; cudnnConvolutionDescriptor_t convDesc; cudnnTensorDescriptor_t yDesc; } class ConvolutionForward : ConvolutionBase { this(Operation op) { auto inShape = op.deps[0].outputType.shape.map!(x => cast(int)x).array(); auto filterShape = op.deps[1].outputType.shape.map!(x => cast(int)x).array(); auto outShape = op.outputType.shape.map!(x => cast(int)x).array(); super(op, inShape, filterShape, outShape); } override void execute(const(CUDABuffer)[] inputs, CUDABuffer output) { auto x = cast(void *)inputs[0].ptr; auto w = cast(void *)inputs[1].ptr; auto y = cast(void *)output.ptr; float alpha = 1; float beta = 0; cudnnConvolutionForward(handle, &alpha, xDesc, x, wDesc, w, convDesc, 0, null, 0, &beta, yDesc, y) .cudnnCheck(); cuCtxSynchronize(); } } class ConvolutionFeaturesGrad : ConvolutionBase { this(Operation op) { auto inShape = op.shape.map!(x => cast(int)x).array(); auto filterShape = op.deps[1].shape.map!(x => cast(int)x).array(); auto outShape = op.deps[0].shape.map!(x => cast(int)x).array(); super(op, inShape, filterShape, outShape); } override void execute(const(CUDABuffer)[] inputs, CUDABuffer output) { auto w = cast(void *)inputs[1].ptr; auto dy = cast(void *)inputs[0].ptr; auto dx = cast(void *)output.ptr; float alpha = 1; float beta = 0; cudnnConvolutionBackwardData(handle, &alpha, wDesc, w, yDesc, dy, convDesc, 0, null, 0, &beta, xDesc, dx) .cudnnCheck(); cuCtxSynchronize(); } } class ConvolutionFiltersGrad : ConvolutionBase { this(Operation op) { auto inShape = op.deps[1].outputType.shape.map!(x => cast(int)x).array(); auto filterShape = op.outputType.shape.map!(x => cast(int)x).array(); auto outShape = op.deps[0].outputType.shape.map!(x => cast(int)x).array(); super(op, inShape, filterShape, outShape); } override void execute(const(CUDABuffer)[] inputs, CUDABuffer output) { auto x = cast(void *)inputs[1].ptr; auto dy = cast(void *)inputs[0].ptr; auto dw = cast(void *)output.ptr; float alpha = 1; float beta = 0; cudnnConvolutionBackwardFilter(handle, &alpha, xDesc, x, yDesc, dy, convDesc, 0, null, 0, &beta, wDesc, dw).cudnnCheck(); cuCtxSynchronize(); } } class MaxpoolBase : CUDAKernel { this(Operation op, int[] inShape, int[]outShape) { auto dims = op.attributes["dims"].get!(size_t[]); auto poolShape = dims.map!(x => cast(int)x).array(); auto poolStride = poolShape.dup; cudnnCreatePoolingDescriptor(&poolingDesc).cudnnCheck(); cudnnSetPooling2dDescriptor(poolingDesc, CUDNN_POOLING_MAX, 1, cast(int)poolShape[0], cast(int)poolShape[1], 0, 0, cast(int)poolStride[0], cast(int)poolStride[1]).cudnnCheck(); cudnnCreateTensorDescriptor(&xDesc).cudnnCheck(); cudnnCreateTensorDescriptor(&yDesc).cudnnCheck(); cudnnSetTensor4dDescriptor(xDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, inShape[0], inShape[1], inShape[2], inShape[3]).cudnnCheck(); cudnnSetTensor4dDescriptor(yDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, outShape[0], outShape[1], outShape[2], outShape[3]).cudnnCheck(); } ~this() { cudnnDestroyPoolingDescriptor(poolingDesc).cudnnCheck(); cudnnDestroyTensorDescriptor(xDesc).cudnnCheck(); cudnnDestroyTensorDescriptor(yDesc).cudnnCheck(); } abstract void execute(const(CUDABuffer)[] inputs, CUDABuffer output); cudnnPoolingDescriptor_t poolingDesc; cudnnTensorDescriptor_t xDesc; cudnnTensorDescriptor_t yDesc; } class MaxpoolForward : MaxpoolBase { this(Operation op) { auto inShape = op.deps[0].outputType.shape.map!(x => cast(int)x).array(); auto outShape = op.outputType.shape.map!(x => cast(int)x).array(); super(op, inShape, outShape); } override void execute(const(CUDABuffer)[] inputs, CUDABuffer output) { auto x = cast(void *)inputs[0].ptr; auto y = cast(void *)output.ptr; float alpha = 1; float beta = 0; cudnnPoolingForward(handle, poolingDesc, &alpha, xDesc, x, &beta, yDesc, y).cudnnCheck(); cuCtxSynchronize(); } } class MaxpoolGrad : MaxpoolBase { this(Operation op) { auto inShape = op.deps[2].outputType.shape.map!(x => cast(int)x).array(); auto outShape = op.deps[1].outputType.shape.map!(x => cast(int)x).array(); super(op, inShape, outShape); } override void execute(const(CUDABuffer)[] inputs, CUDABuffer output) { auto dx = cast(void *)output.ptr; auto dy = cast(void *)inputs[0].ptr; auto y = cast(void *)inputs[1].ptr; auto x = cast(void *)inputs[2].ptr; float alpha = 1; float beta = 0; cudnnPoolingBackward(handle, poolingDesc, &alpha, yDesc, y, yDesc, dy, xDesc, x, &beta, xDesc, dx) .cudnnCheck(); cuCtxSynchronize(); } } class Softmax : CUDAKernel { this(Operation op) { auto shape = op.shape.map!(x => cast(int)x).array(); auto vol = 1; for(size_t i = 2; i < shape.length; i++) { vol *= shape[i]; } cudnnCreateTensorDescriptor(&desc).cudnnCheck(); cudnnSetTensor4dDescriptor(desc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, shape[0], shape[1], vol, 1) .cudnnCheck(); } ~this() { cudnnDestroyTensorDescriptor(desc).cudnnCheck(); } override void execute(const(CUDABuffer)[] inputs, CUDABuffer output) { float alpha = 1.0; float beta = 0.0; auto x = cast(void *)inputs[0].ptr; auto y = cast(void *)output.ptr; cudnnSoftmaxForward(handle, CUDNN_SOFTMAX_ACCURATE, CUDNN_SOFTMAX_MODE_CHANNEL, &alpha, desc, x, &beta, desc, y).cudnnCheck(); cuCtxSynchronize(); } cudnnTensorDescriptor_t desc; } class SoftmaxGrad : CUDAKernel { this(Operation op) { auto shape = op.shape.map!(x => cast(int)x).array(); cudnnCreateTensorDescriptor(&desc).cudnnCheck(); cudnnSetTensor4dDescriptor(desc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, shape[0], shape[1], reduce!"a * b"(1, shape[2 .. $]), 1).cudnnCheck(); } ~this() { cudnnDestroyTensorDescriptor(desc).cudnnCheck(); } override void execute(const(CUDABuffer)[] inputs, CUDABuffer output) { float alpha = 1.0; float beta = 0.0; auto dy = cast(void *)inputs[0].ptr; auto y = cast(void *)inputs[1].ptr; auto dx = cast(void *)output.ptr; cudnnSoftmaxBackward(handle, CUDNN_SOFTMAX_ACCURATE, CUDNN_SOFTMAX_MODE_CHANNEL, &alpha, desc, y, desc, dy, &beta, desc, dx).cudnnCheck(); cuCtxSynchronize(); } cudnnTensorDescriptor_t desc; } class ReLU : CUDAKernel { this(Operation op) { auto shape = op.shape.map!(x => cast(int)x).array(); cudnnCreateTensorDescriptor(&desc).cudnnCheck(); cudnnSetTensor4dDescriptor(desc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, shape[0], shape[1], reduce!"a * b"(1, shape[2 .. $]), 1).cudnnCheck(); cudnnCreateActivationDescriptor(&actDesc).cudnnCheck(); cudnnSetActivationDescriptor(actDesc, CUDNN_ACTIVATION_RELU, CUDNN_PROPAGATE_NAN, 0.0).cudnnCheck(); } ~this() { cudnnDestroyTensorDescriptor(desc).cudnnCheck(); cudnnDestroyActivationDescriptor(actDesc).cudnnCheck(); } override void execute(const(CUDABuffer)[] inputs, CUDABuffer output) { float alpha = 1.0; float beta = 0.0; auto x = cast(void *)inputs[0].ptr; auto y = cast(void *)output.ptr; cudnnActivationForward(handle, actDesc, &alpha, desc, x, &beta, desc, y).cudnnCheck(); cuCtxSynchronize(); } cudnnTensorDescriptor_t desc; cudnnActivationDescriptor_t actDesc; } class ReLUGrad : CUDAKernel { this(Operation op) { auto shape = op.shape.map!(x => cast(int)x).array(); cudnnCreateTensorDescriptor(&desc).cudnnCheck(); cudnnSetTensor4dDescriptor(desc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, shape[0], shape[1], reduce!"a * b"(1, shape[2 .. $]), 1).cudnnCheck(); cudnnCreateActivationDescriptor(&actDesc).cudnnCheck(); cudnnSetActivationDescriptor(actDesc, CUDNN_ACTIVATION_RELU, CUDNN_PROPAGATE_NAN, 0.0).cudnnCheck(); } ~this() { cudnnDestroyTensorDescriptor(desc).cudnnCheck(); cudnnDestroyActivationDescriptor(actDesc).cudnnCheck(); } override void execute(const(CUDABuffer)[] inputs, CUDABuffer output) { float alpha = 1.0; float beta = 0.0; auto dy = cast(void *)inputs[0].ptr; auto y = cast(void *)inputs[1].ptr; auto x = cast(void *)inputs[2].ptr; auto dx = cast(void *)output.ptr; cudnnActivationBackward(handle, actDesc, &alpha, desc, y, desc, dy, desc, x, &beta, desc, dx).cudnnCheck(); cuCtxSynchronize(); } cudnnTensorDescriptor_t desc; cudnnActivationDescriptor_t actDesc; } class AddBias : CUDAKernel { this(Operation op) { auto shape = op.shape.map!(x => cast(int)x).array(); cudnnCreateTensorDescriptor(&cDesc).cudnnCheck(); cudnnSetTensor4dDescriptor(cDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, shape[0], shape[1], reduce!"a * b"(1, shape[2 .. $]), 1).cudnnCheck(); cudnnCreateTensorDescriptor(&aDesc).cudnnCheck(); cudnnSetTensor4dDescriptor(aDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, 1, shape[1], 1, 1).cudnnCheck(); } ~this() { cudnnDestroyTensorDescriptor(cDesc).cudnnCheck(); cudnnDestroyTensorDescriptor(aDesc).cudnnCheck(); } override void execute(const(CUDABuffer)[] inputs, CUDABuffer output) { cuMemcpy(output.ptr, inputs[0].ptr, output.numBytes); float alpha = 1; float beta = 1; cudnnAddTensor(handle, &alpha, aDesc, cast(void *)inputs[1].ptr, &beta, cDesc, cast(void *)output.ptr); } cudnnTensorDescriptor_t cDesc; cudnnTensorDescriptor_t aDesc; } class AddBiasGrad : CUDAKernel { this(Operation op) { auto shape = op.deps[0].shape.map!(x => cast(int)x).array(); cudnnCreateTensorDescriptor(&dyDesc).cudnnCheck(); cudnnSetTensor4dDescriptor(dyDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, shape[0], shape[1], reduce!"a * b"(1, shape[2 .. $]), 1).cudnnCheck(); cudnnCreateTensorDescriptor(&dbDesc).cudnnCheck(); cudnnSetTensor4dDescriptor(dbDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, 1, shape[1], 1, 1).cudnnCheck(); } ~this() { cudnnDestroyTensorDescriptor(dyDesc).cudnnCheck(); cudnnDestroyTensorDescriptor(dbDesc).cudnnCheck(); } override void execute(const(CUDABuffer)[] inputs, CUDABuffer output) { float alpha = 1.0f; float beta = 1.0f; cudnnConvolutionBackwardBias(handle, &alpha, dyDesc, cast(void *)inputs[0].ptr, &beta, dbDesc, cast(void *)output.ptr); } cudnnTensorDescriptor_t dyDesc; cudnnTensorDescriptor_t dbDesc; } abstract class BatchNormBase : CUDAKernel { this(Operation op) { if(op.deps[0].rank == 2) { mode = CUDNN_BATCHNORM_PER_ACTIVATION; } else { mode = CUDNN_BATCHNORM_SPATIAL; } import std.range; auto shape = op.deps[0].shape .chain(repeat(1)) .map!(x => cast(int)x) .take(4) .array(); cudnnCreateTensorDescriptor(&xDesc).cudnnCheck(); cudnnCreateTensorDescriptor(&bnDesc).cudnnCheck(); cudnnSetTensor4dDescriptor(xDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, shape[0], shape[1], shape[2], shape[3]).cudnnCheck(); cudnnDeriveBNTensorDescriptor(bnDesc, xDesc, mode).cudnnCheck(); } ~this() { cudnnDestroyTensorDescriptor(xDesc).cudnnCheck(); cudnnDestroyTensorDescriptor(bnDesc).cudnnCheck(); } cudnnBatchNormMode_t mode; cudnnTensorDescriptor_t xDesc; cudnnTensorDescriptor_t bnDesc; } class BatchNormTrain : BatchNormBase { this(Operation op) { super(op); mMomentum = 1.0 - op.attributes["momentum"].get!double; } void execute(const(CUDABuffer)[] inputs, CUDABuffer output) { float alpha = 1.0f; float beta = 0.0f; //We're going to pack the running mean/variance after the BN forward prop. Let the higher level //API slice them out into different nodes. auto mean = output.ptr + inputs[0].numBytes; auto var = mean + (output.numBytes - inputs[0].numBytes) / 2; cuMemcpy(mean, inputs[3].ptr, inputs[3].numBytes); cuMemcpy(var, inputs[4].ptr, inputs[4].numBytes); cudnnBatchNormalizationForwardTraining(handle, mode, &alpha, &beta, xDesc, cast(void *)inputs[0].ptr, xDesc, cast(void *)output.ptr, bnDesc, cast(void *)inputs[1].ptr, cast(void *)inputs[2].ptr, mMomentum, cast(void *)mean, cast(void *)var, 1e-5f, null, null).cudnnCheck(); } double mMomentum; } class BatchNormGrad : BatchNormBase { this(Operation op) { super(op); } void execute(const(CUDABuffer)[] inputs, CUDABuffer output) { float alpha = 1.0f; float beta = 0.0f; void *dx = cast(void *)(output.ptr); void *dscale = cast(void *)(output.ptr + inputs[1].numBytes); void *dbias = cast(void *)(output.ptr + inputs[1].numBytes + inputs[2].numBytes); cudnnBatchNormalizationBackward(handle, mode, &alpha, &beta, &alpha, &beta, xDesc, cast(void *)inputs[1].ptr, xDesc, cast(void *)inputs[0].ptr, xDesc, dx, bnDesc, cast(void *)inputs[2].ptr, dscale, dbias, 1e-5f, null, null); } } class BatchNormInference : BatchNormBase { this(Operation op) { super(op); } void execute(const(CUDABuffer)[] inputs, CUDABuffer output) { float alpha = 1.0f; float beta = 0.0f; cudnnBatchNormalizationForwardInference(handle, mode, &alpha, &beta, xDesc, cast(void *)inputs[0].ptr, xDesc, cast(void *)output.ptr, bnDesc, cast(void *)inputs[1].ptr, cast(void *)inputs[2].ptr, cast(void *)inputs[3].ptr, cast(void *)inputs[4].ptr, 1e-5).cudnnCheck(); } } }
D
import std.stdio; import std.math; import std.algorithm; import std.conv; import std.bigint; bool divisible(ulong a, ulong b) { return (a % b) == 0; } ulong[] divisors(ulong n) { auto pf = primeFactors(n); ulong[] res = [1u]; for (int i = 0; i < pf.length; ++i) { auto cpy = res.dup; foreach(ref c; cpy) c *= pf[i]; res = res ~ cpy; } // remove duplicates and n { int i = 0; while (i < res.length - 1) { bool isDup = false; for (int j = i + 1; j < res.length; ++j) if (res[i] == res[j]) { isDup = true; break; } if (isDup) { res = res[0..i] ~ res[i+1..$]; // remove } else ++i; } } // remove n res = res[0..$-1]; return res; } ulong[] primeFactors(ulong n) { //writefln("divisors(%s)", n); for (ulong x = 2; x * x <= n; ++ x) { if (divisible(n, x)) { //writefln("divisible by %s", x); return [x] ~ primeFactors(n / x); } } return [n]; } T sum(T)(T[] x) { T r = 0; foreach(e; x) r += e; return r; } bool isAmicableNumber(ulong u) { ulong sod = sum(divisors(u)); bool res = (u != sod) && (u == sum(divisors(sod))); if (res) writefln("%s and %s are an amicable pair", u, sod); return res; } void main(string[]) { ulong sum = 0; for (int i = 2; i < 10000; ++i) { if (isAmicableNumber(i)) sum += i; } writefln("sum = %s", sum); // 31626 }
D
/home/jannes/work/rust/rust_test1/com1/target/debug/deps/com1-e51087575b65b75d.rmeta: src/main.rs /home/jannes/work/rust/rust_test1/com1/target/debug/deps/com1-e51087575b65b75d.d: src/main.rs src/main.rs:
D
INSTANCE Dschinn_11013_OM (Npc_Default) { // ------ NSC ------ name = "Dschinn"; guild = GIL_SKELETON_MAGE; id = 11013; voice = 0; flags = NPC_FLAG_GHOST; npctype = NPCTYPE_MAIN; level = 400; // ------ Attribute ------ attribute[ATR_HITPOINTS_MAX] = 5000; attribute[ATR_HITPOINTS] = 5000; attribute[ATR_STRENGTH] = 500; self.aivar[AIV_Damage] = self.attribute[ATR_HITPOINTS]; // ------ Kampf-Taktik ------ fight_tactic = FAI_HUMAN_STRONG; // ------ Equippte Waffen ------ // ------ Inventory ------ // Händler // ------ visuals ------ Mdl_SetVisual (self, "HumanS.mds"); Mdl_ApplyOverlayMds (self, "humans_skeleton_fly.mds"); // Body-Mesh Body-Tex Skin-Color Head-MMS Head-Tex Teeth-Tex ARMOR Mdl_SetVisualBody (self, "Ske_Fly_Body", 1, DEFAULT, "", 1, DEFAULT, -1); // ------ NSC-relevante Talente vergeben ------ B_GiveNpcTalents (self); // ------ Kampf-Talente ------ B_SetFightSkills (self, 35); // ------ TA anmelden ------ daily_routine = Rtn_Start_11013; }; FUNC VOID Rtn_Start_11013 () { TA_Roam (08,00,22,00,Npc_GetNearestWP(hero)); TA_Roam (22,00,08,00,Npc_GetNearestWP(hero)); }; FUNC VOID Rtn_Tot_11013 () { TA_Stand_ArmsCrossed (08,00,22,00,"TOT"); TA_Stand_ArmsCrossed (22,00,08,00,"TOT"); };
D
/******************************************************************************* Helper structs to acquire and relinquish shared resources during the handling of a request. Copyright: Copyright (c) 2016-2017 sociomantic labs GmbH. All rights reserved License: Boost Software License Version 1.0. See LICENSE_BOOST.txt for details. *******************************************************************************/ module swarm.neo.util.AcquiredResources; import ocean.transition; /******************************************************************************* Set of acquired arrays of the templated type. An external source of untyped arrays -- a FreeList!(ubyte[]) -- is required. When arrays are acquired (via the acquire() method), they are requested from the free list and stored internally in a container array. When the arrays are no longer required, the relinquishAll() method will return them to the free list. Note that the container array used to store the acquired arrays is also itself acquired from the free list and relinquished by relinquishAll(). Params: T = element type of the arrays *******************************************************************************/ public struct AcquiredArraysOf ( T ) { import ocean.util.container.pool.FreeList; /*************************************************************************** Externally owned pool of untyped buffers, passed in via initialise(). ***************************************************************************/ private FreeList!(ubyte[]) buffer_pool; /*************************************************************************** List of acquired buffers. ***************************************************************************/ private T[][] acquired; /*************************************************************************** Initialises this instance. (No other methods may be called before calling this method.) Params: buffer_pool = shared pool of untyped arrays ***************************************************************************/ public void initialise ( FreeList!(ubyte[]) buffer_pool ) { this.buffer_pool = buffer_pool; } /*************************************************************************** Returns: a new array of T ***************************************************************************/ public T[]* acquire ( ) in { assert(this.buffer_pool !is null); } body { void[] newBuffer ( size_t capacity ) { auto buffer = this.buffer_pool.get(cast(ubyte[])new void[capacity]); buffer.length = 0; enableStomping(buffer); return buffer; } // Acquire container buffer, if not already done. if ( this.acquired is null ) { this.acquired = cast(T[][])newBuffer((T[]).sizeof * 4); } // Acquire and re-initialise new buffer to return to the user. Store // it in the container buffer. this.acquired ~= cast(T[])newBuffer(4); return &this.acquired[$-1]; } /*************************************************************************** Relinquishes all shared resources acquired by this instance. ***************************************************************************/ public void relinquishAll ( ) in { assert(this.buffer_pool !is null); } body { if ( this.acquired !is null ) { // Relinquish acquired buffers. foreach ( ref inst; this.acquired ) this.buffer_pool.recycle(cast(ubyte[])inst); // Relinquish container buffer. this.buffer_pool.recycle(cast(ubyte[])this.acquired); } } } /// unittest { // Demonstrates how a typical global shared resources container should look. // A single instance of this would be owned at the top level of the client/ // node. class SharedResources { import ocean.util.container.pool.FreeList; // The pool of untyped buffers required by AcquiredArraysOf. private FreeList!(ubyte[]) buffers; this ( ) { this.buffers = new FreeList!(ubyte[]); } // Objects of this class will be newed at scope and passed to request // handlers. This allows the handler to acquire various shared resources // and have them automatically relinquished when the handler exits. class RequestResources { // Tracker of buffers acquired by the request. private AcquiredArraysOf!(void) acquired_void_buffers; // Initialise the tracker in the ctor. this ( ) { this.acquired_void_buffers.initialise(this.outer.buffers); } // ...and be sure to relinquish all the acquired resources in the // dtor. ~this ( ) { this.acquired_void_buffers.relinquishAll(); } // Public method to get a new resource, managed by the tracker. public void[]* getVoidBuffer ( ) { return this.acquired_void_buffers.acquire(); } } } } /******************************************************************************* Set of acquired resources of the templated type. An external source of elements of this type -- a FreeList!(T) -- as well as a source of untyped buffers -- a FreeList!(ubyte[]) -- is required. When resources are acquired (via the acquire() method), they are requested from the free list and stored internally in an array. When the resources are no longer required, the relinquishAll() method will return them to the free list. Note that the array used to store the acquired resources is itself acquired from the free list of untyped buffers and relinquished by relinquishAll(). Params: T = type of resource *******************************************************************************/ public struct Acquired ( T ) { import ocean.util.container.pool.FreeList; /*************************************************************************** Determine the type of a new resource. ***************************************************************************/ static if ( is(typeof({T* t = new T;})) ) { alias T* Elem; } else { alias T Elem; } /*************************************************************************** Externally owned pool of untyped buffers, passed in via initialise(). ***************************************************************************/ private FreeList!(ubyte[]) buffer_pool; /*************************************************************************** Externally owned pool of T, passed in via initialise(). ***************************************************************************/ private FreeList!(T) t_pool; /*************************************************************************** List of acquired resources. ***************************************************************************/ private Elem[] acquired; /*************************************************************************** Initialises this instance. (No other methods may be called before calling this method.) Params: buffer_pool = shared pool of untyped arrays t_pool = shared pool of T ***************************************************************************/ public void initialise ( FreeList!(ubyte[]) buffer_pool, FreeList!(T) t_pool ) { this.buffer_pool = buffer_pool; this.t_pool = t_pool; } /*************************************************************************** Gets a new T. Params: new_t = lazily initialised new resource Returns: a new T ***************************************************************************/ public Elem acquire ( lazy Elem new_t ) in { assert(this.buffer_pool !is null); } body { void[] newBuffer ( size_t capacity ) { auto buffer = this.buffer_pool.get(cast(ubyte[])new void[capacity]); buffer.length = 0; enableStomping(buffer); return buffer; } // Acquire container buffer, if not already done. if ( this.acquired is null ) { this.acquired = cast(Elem[])newBuffer(Elem.sizeof * 4); } // Acquire new element. this.acquired ~= this.t_pool.get(new_t); return this.acquired[$-1]; } /*************************************************************************** Relinquishes all shared resources acquired by this instance. ***************************************************************************/ public void relinquishAll ( ) in { assert(this.buffer_pool !is null); } body { if ( this.acquired !is null ) { // Relinquish acquired Ts. foreach ( ref inst; this.acquired ) this.t_pool.recycle(inst); // Relinquish container buffer. this.buffer_pool.recycle(cast(ubyte[])this.acquired); } } } /// unittest { // Type of a specialised resource which may be required by requests. struct MyResource { } // Demonstrates how a typical global shared resources container should look. // A single instance of this would be owned at the top level of the client/ // node. class SharedResources { import ocean.util.container.pool.FreeList; // The pool of untyped buffers required by Acquired. private FreeList!(ubyte[]) buffers; // The pool of specialised resources required by Acquired. private FreeList!(MyResource) myresources; this ( ) { this.buffers = new FreeList!(ubyte[]); this.myresources = new FreeList!(MyResource); } // Objects of this class will be newed at scope and passed to request // handlers. This allows the handler to acquire various shared resources // and have them automatically relinquished when the handler exits. class RequestResources { private Acquired!(MyResource) acquired_myresources; // Initialise the tracker in the ctor. this ( ) { this.acquired_myresources.initialise(this.outer.buffers, this.outer.myresources); } // ...and be sure to relinquish all the acquired resources in the // dtor. ~this ( ) { this.acquired_myresources.relinquishAll(); } // Public method to get a new resource, managed by the tracker. public MyResource* getMyResource ( ) { return this.acquired_myresources.acquire(new MyResource); } } } } /******************************************************************************* Singleton (per-request) acquired resource of the templated type. An external source of elements of this type -- a FreeList!(T) -- is required. When the singleton resource is acquired (via the acquire() method), it is requested from the free list and stored internally. All subsequent calls to acquire() return the same instance. When the resource is no longer required, the relinquish() method will return it to the free list. Params: T = type of resource *******************************************************************************/ public struct AcquiredSingleton ( T ) { import ocean.util.container.pool.FreeList; /*************************************************************************** Determine the type of a new resource. ***************************************************************************/ static if ( is(typeof({T* t = new T;})) ) { alias T* Elem; } else { alias T Elem; } /*************************************************************************** Externally owned pool of T, passed in via initialise(). ***************************************************************************/ private FreeList!(T) t_pool; /*************************************************************************** Acquired resource. ***************************************************************************/ private Elem acquired; /*************************************************************************** Initialises this instance. (No other methods may be called before calling this method.) Params: t_pool = shared pool of T ***************************************************************************/ public void initialise ( FreeList!(T) t_pool ) { this.t_pool = t_pool; } /*************************************************************************** Gets the singleton T instance. Params: new_t = lazily initialised new resource Returns: singleton T instance ***************************************************************************/ public Elem acquire ( lazy Elem new_t ) in { assert(this.t_pool !is null); } body { if ( this.acquired is null ) this.acquired = this.t_pool.get(new_t); assert(this.acquired !is null); return this.acquired; } /*************************************************************************** Gets the singleton T instance. Params: new_t = lazily initialised new resource reset = delegate to call on the singleton instance when it is first acquired from the pool. Should perform any logic required to reset the instance to its initial state Returns: singleton T instance ***************************************************************************/ public Elem acquire ( lazy Elem new_t, void delegate ( Elem ) reset ) in { assert(this.t_pool !is null); } body { if ( this.acquired is null ) { this.acquired = this.t_pool.get(new_t); reset(this.acquired); } assert(this.acquired !is null); return this.acquired; } /*************************************************************************** Relinquishes singleton shared resources acquired by this instance. ***************************************************************************/ public void relinquish ( ) in { assert(this.t_pool !is null); } body { if ( this.acquired !is null ) this.t_pool.recycle(this.acquired); } } /// unittest { // Type of a specialised resource which may be required by requests. struct MyResource { } // Demonstrates how a typical global shared resources container should look. // A single instance of this would be owned at the top level of the client/ // node. class SharedResources { import ocean.util.container.pool.FreeList; // The pool of specialised resources required by AcquiredSingleton. private FreeList!(MyResource) myresources; this ( ) { this.myresources = new FreeList!(MyResource); } // Objects of this class will be newed at scope and passed to request // handlers. This allows the handler to acquire various shared resources // and have them automatically relinquished when the handler exits. class RequestResources { private AcquiredSingleton!(MyResource) myresource_singleton; // Initialise the tracker in the ctor. this ( ) { this.myresource_singleton.initialise(this.outer.myresources); } // ...and be sure to relinquish all the acquired resources in the // dtor. ~this ( ) { this.myresource_singleton.relinquish(); } // Public method to get the resource singleton for this request, // managed by the tracker. public MyResource* myResource ( ) { return this.myresource_singleton.acquire(new MyResource, ( MyResource* resource ) { // When the singleton is first acquired, perform any // logic required to reset it to its initial state. *resource = MyResource.init; } ); } } } } /******************************************************************************* Test that shared resources are acquired and relinquished correctly using the helper structs above. *******************************************************************************/ version ( UnitTest ) { import ocean.core.Test; } unittest { // Resource types that may be acquired. struct MyStruct { } class MyClass { } class SharedResources { import ocean.util.container.pool.FreeList; private FreeList!(MyStruct) mystructs; private FreeList!(MyClass) myclasses; private FreeList!(ubyte[]) buffers; this ( ) { this.mystructs = new FreeList!(MyStruct); this.myclasses = new FreeList!(MyClass); this.buffers = new FreeList!(ubyte[]); } class RequestResources { private Acquired!(MyStruct) acquired_mystructs; private AcquiredSingleton!(MyStruct) mystruct_singleton; private Acquired!(MyClass) acquired_myclasses; private AcquiredArraysOf!(void) acquired_void_arrays; this ( ) { this.acquired_mystructs.initialise(this.outer.buffers, this.outer.mystructs); this.mystruct_singleton.initialise(this.outer.mystructs); this.acquired_myclasses.initialise(this.outer.buffers, this.outer.myclasses); this.acquired_void_arrays.initialise(this.outer.buffers); } ~this ( ) { this.acquired_mystructs.relinquishAll(); this.mystruct_singleton.relinquish(); this.acquired_myclasses.relinquishAll(); this.acquired_void_arrays.relinquishAll(); } public MyStruct* getMyStruct ( ) { return this.acquired_mystructs.acquire(new MyStruct); } public MyStruct* myStructSingleton ( ) { return this.mystruct_singleton.acquire(new MyStruct); } public MyClass getMyClass ( ) { return this.acquired_myclasses.acquire(new MyClass); } public void[]* getVoidArray ( ) { return this.acquired_void_arrays.acquire(); } } } auto resources = new SharedResources; // Test acquiring some resources. { scope acquired = resources.new RequestResources; test!("==")(resources.buffers.num_idle, 0); test!("==")(resources.mystructs.num_idle, 0); test!("==")(resources.myclasses.num_idle, 0); // Acquire a struct. acquired.getMyStruct(); test!("==")(resources.buffers.num_idle, 0); test!("==")(resources.mystructs.num_idle, 0); test!("==")(resources.myclasses.num_idle, 0); test!("==")(acquired.acquired_mystructs.acquired.length, 1); // Acquire a struct singleton twice. acquired.myStructSingleton(); acquired.myStructSingleton(); test!("==")(resources.buffers.num_idle, 0); test!("==")(resources.mystructs.num_idle, 0); test!("==")(resources.myclasses.num_idle, 0); test!("==")(acquired.acquired_mystructs.acquired.length, 1); // Acquire a class. acquired.getMyClass(); test!("==")(resources.buffers.num_idle, 0); test!("==")(resources.mystructs.num_idle, 0); test!("==")(resources.myclasses.num_idle, 0); test!("==")(acquired.acquired_myclasses.acquired.length, 1); // Acquire an array. acquired.getVoidArray(); test!("==")(resources.buffers.num_idle, 0); test!("==")(resources.mystructs.num_idle, 0); test!("==")(resources.myclasses.num_idle, 0); test!("==")(acquired.acquired_void_arrays.acquired.length, 1); } // Test that the acquired resources appear in the free-lists, once the // acquired tracker goes out of scope. test!("==")(resources.buffers.num_idle, 4); // 3 container arrays + 1 test!("==")(resources.mystructs.num_idle, 2); test!("==")(resources.myclasses.num_idle, 1); // Now do it again and test that the resources in the free-lists are reused. { scope acquired = resources.new RequestResources; test!("==")(resources.buffers.num_idle, 4); test!("==")(resources.mystructs.num_idle, 2); test!("==")(resources.myclasses.num_idle, 1); // Acquire a struct. acquired.getMyStruct(); test!("==")(resources.buffers.num_idle, 3); test!("==")(resources.mystructs.num_idle, 1); test!("==")(resources.myclasses.num_idle, 1); test!("==")(acquired.acquired_mystructs.acquired.length, 1); // Acquire a class. acquired.getMyClass(); test!("==")(resources.buffers.num_idle, 2); test!("==")(resources.mystructs.num_idle, 1); test!("==")(resources.myclasses.num_idle, 0); test!("==")(acquired.acquired_myclasses.acquired.length, 1); // Acquire an array. acquired.getVoidArray(); test!("==")(resources.buffers.num_idle, 0); test!("==")(resources.mystructs.num_idle, 1); test!("==")(resources.myclasses.num_idle, 0); test!("==")(acquired.acquired_void_arrays.acquired.length, 1); } // No more resources should have been allocated. test!("==")(resources.buffers.num_idle, 4); // 3 container arrays + 1 test!("==")(resources.mystructs.num_idle, 2); test!("==")(resources.myclasses.num_idle, 1); }
D
// Copyright Brian Schott (Sir Alaran) 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) import stdx.d.lexer; import stdx.d.ast; import std.stdio; import std.string; import std.array; import formatter; template tagAndAccept(string tagName) { immutable tagAndAccept = `output.writeln("<` ~ tagName ~ `>");` ~ tagName ~ `.accept(this);` ~ `output.writeln("</` ~ tagName ~ `>");`; } class XMLPrinter : ASTVisitor { override void visit(AddExpression addExpression) { output.writeln("<addExpression operator=\"", str(addExpression.operator) ,"\">"); output.writeln("<left>"); addExpression.left.accept(this); output.writeln("</left>"); if (addExpression.right !is null) { output.writeln("<right>"); addExpression.right.accept(this); output.writeln("</right>"); } output.writeln("</addExpression>"); } override void visit(AliasDeclaration aliasDeclaration) { mixin (tagAndAccept!"aliasDeclaration"); } override void visit(AliasInitializer aliasInitializer) { mixin (tagAndAccept!"aliasInitializer"); } override void visit(AliasThisDeclaration aliasThisDeclaration) { mixin (tagAndAccept!"aliasThisDeclaration"); } override void visit(AlignAttribute alignAttribute) { output.writeln("<alignAttribute align=\"", alignAttribute.intLiteral.text, "\">"); } override void visit(AndAndExpression andAndExpression) { output.writeln("<andAndExpression>"); output.writeln("<left>"); andAndExpression.left.accept(this); output.writeln("</left>"); if (andAndExpression.right !is null) { output.writeln("<right>"); andAndExpression.right.accept(this); output.writeln("</right>"); } output.writeln("</andAndExpression>"); } override void visit(AndExpression andExpression) { output.writeln("<andExpression>"); output.writeln("<left>"); andExpression.left.accept(this); output.writeln("</left>"); if (andExpression.right !is null) { output.writeln("<right>"); andExpression.right.accept(this); output.writeln("</right>"); } output.writeln("</andExpression>"); } override void visit(ArgumentList argumentList) { mixin (tagAndAccept!"argumentList"); } override void visit(Arguments arguments) { mixin (tagAndAccept!"arguments"); } override void visit(ArrayInitializer arrayInitializer) { mixin (tagAndAccept!"arrayInitializer"); } override void visit(ArrayLiteral arrayLiteral) { mixin (tagAndAccept!"arrayLiteral"); } override void visit(ArrayMemberInitialization arrayMemberInitialization) { mixin (tagAndAccept!"arrayMemberInitialization"); } override void visit(AssertExpression assertExpression) { output.writeln("<assertExpression>"); output.writeln("<assertion>"); assertExpression.assertion.accept(this); output.writeln("</assertion>"); if (assertExpression.message !is null) { output.writeln("<message>"); assertExpression.message.accept(this); output.writeln("</message>"); } output.writeln("</assertExpression>"); } override void visit(AssignExpression assignExpression) { if (assignExpression.assignExpression is null) output.writeln("<assignExpression>"); else output.writeln("<assignExpression operator=\"", str(assignExpression.operator), "\">"); assignExpression.accept(this); output.writeln("</assignExpression>"); } override void visit(AssocArrayLiteral assocArrayLiteral) { mixin (tagAndAccept!"assocArrayLiteral"); } override void visit(AtAttribute atAttribute) { output.writeln("<atAttribute>"); if (atAttribute.identifier.type == tok!"") atAttribute.accept(this); else output.writeln("<identifier>", atAttribute.identifier.text, "</identifier>"); output.writeln("</atAttribute>"); } override void visit(Attribute attribute) { output.writeln("<attribute>"); if (attribute.attribute == tok!"") attribute.accept(this); else output.writeln(str(attribute.attribute)); output.writeln("</attribute>"); } override void visit(AttributeDeclaration attributeDeclaration) { assert (attributeDeclaration !is null); mixin (tagAndAccept!"attributeDeclaration"); } override void visit(AutoDeclaration autoDec) { output.writeln("<autoDeclaration>"); for (size_t i = 0; i < autoDec.identifiers.length; i++) { output.writeln("<item>"); output.writeln("<name line=\"", autoDec.identifiers[i].line, "\">", autoDec.identifiers[i].text, "</name>"); visit(autoDec.initializers[i]); output.writeln("</item>"); } output.writeln("</autoDeclaration>"); } override void visit(BlockStatement blockStatement) { output.writeln("<blockStatement>"); blockStatement.accept(this); output.writeln("</blockStatement>"); } override void visit(BodyStatement bodyStatement) { output.writeln("<bodyStatement>"); bodyStatement.accept(this); output.writeln("</bodyStatement>"); } override void visit(BreakStatement breakStatement) { if (breakStatement.label.type == tok!"") output.writeln("<breakStatement/>"); else output.writeln("<breakStatement label=\"", breakStatement.label.text, "\"/>"); } override void visit(BaseClass baseClass) { mixin (tagAndAccept!"baseClass"); } override void visit(BaseClassList baseClassList) { mixin (tagAndAccept!"baseClassList"); } override void visit(CaseRangeStatement caseRangeStatement) { output.writeln("<caseRangeStatement>"); if (caseRangeStatement.low !is null) { output.writeln("<low>"); visit(caseRangeStatement.low); output.writeln("</low>"); } if (caseRangeStatement.high !is null) { output.writeln("<high>"); visit(caseRangeStatement.high); output.writeln("</high>"); } if (caseRangeStatement.declarationsAndStatements !is null) visit(caseRangeStatement.declarationsAndStatements); output.writeln("</caseRangeStatement>"); } override void visit(CaseStatement caseStatement) { mixin (tagAndAccept!"caseStatement"); } override void visit(CastExpression castExpression) { mixin (tagAndAccept!"castExpression"); } override void visit(CastQualifier castQualifier) { mixin (tagAndAccept!"castQualifier"); } override void visit(Catches catches) { mixin (tagAndAccept!"catches"); } override void visit(Catch catch_) { output.writeln("<catch>"); catch_.accept(this); output.writeln("</catch>"); } override void visit(ClassDeclaration classDec) { output.writeln("<classDeclaration line=\"", classDec.name.line, "\">"); output.writeln("<name>", classDec.name.text, "</name>"); writeDdoc(classDec.comment); classDec.accept(this); output.writeln("</classDeclaration>"); } override void visit(CmpExpression cmpExpression) { mixin (tagAndAccept!"cmpExpression"); } override void visit(CompileCondition compileCondition) { mixin (tagAndAccept!"compileCondition"); } override void visit(ConditionalDeclaration conditionalDeclaration) { output.writeln("<conditionalDeclaration>"); visit(conditionalDeclaration.compileCondition); output.writeln("<trueDeclarations>"); foreach (dec; conditionalDeclaration.trueDeclarations) visit(dec); output.writeln("</trueDeclarations>"); if (conditionalDeclaration.falseDeclaration !is null) { output.writeln("<falseDeclaration>"); visit(conditionalDeclaration.falseDeclaration); output.writeln("</falseDeclaration>"); } output.writeln("</conditionalDeclaration>"); } override void visit(ConditionalStatement conditionalStatement) { output.writeln("<conditionalStatement>"); visit(conditionalStatement.compileCondition); output.writeln("<trueStatement>"); visit(conditionalStatement.trueStatement); output.writeln("</trueStatement>"); if (conditionalStatement.falseStatement !is null) { output.writeln("<falseStatement>"); visit(conditionalStatement.falseStatement); output.writeln("</falseStatement>"); } output.writeln("</conditionalStatement>"); } override void visit(Constraint constraint) { output.writeln("<constraint>"); constraint.accept(this); output.writeln("</constraint>"); } override void visit(Constructor constructor) { mixin (tagAndAccept!"constructor"); } override void visit(ContinueStatement continueStatement) { if (continueStatement.label.type == tok!"") output.writeln("<continueStatement/>"); else output.writeln("<continueStatement label=\"", continueStatement.label.text, "\"/>"); } override void visit(DebugCondition debugCondition) { if (debugCondition.identifierOrInteger.type == tok!"") output.writeln("<debugCondition/>"); else output.writeln("<debugCondition condition=\"", debugCondition.identifierOrInteger.text, "\"/>"); } override void visit(DebugSpecification debugSpecification) { if (debugSpecification.identifierOrInteger.type == tok!"") output.writeln("<debugSpecification/>"); else output.writeln("<debugSpecification condition=\"", debugSpecification.identifierOrInteger.text, "\"/>"); } override void visit(Declaration declaration) { mixin (tagAndAccept!"declaration"); } override void visit(DeclarationsAndStatements declarationsAndStatements) { mixin (tagAndAccept!"declarationsAndStatements"); } override void visit(DeclarationOrStatement declarationOrStatement) { mixin (tagAndAccept!"declarationOrStatement"); } override void visit(Declarator declarator) { output.writeln("<declarator line=\"", declarator.name.line, "\">"); output.writeln("<name>", declarator.name.text, "</name>"); declarator.accept(this); output.writeln("</declarator>"); } override void visit(DefaultStatement defaultStatement) { mixin (tagAndAccept!"defaultStatement"); } override void visit(DeleteExpression deleteExpression) { mixin (tagAndAccept!"deleteExpression"); } override void visit(DeleteStatement deleteStatement) { mixin (tagAndAccept!"deleteStatement"); } override void visit(Deprecated deprecated_) { if (deprecated_.assignExpression !is null) { output.writeln("<deprecated>"); deprecated_.accept(this); output.writeln("</deprecated>"); } else output.writeln("<deprecated/>"); } override void visit(Destructor destructor) { mixin (tagAndAccept!"destructor"); } override void visit(DoStatement doStatement) { mixin (tagAndAccept!"doStatement"); } override void visit(EnumBody enumBody) { mixin (tagAndAccept!"enumBody"); } override void visit(EnumDeclaration enumDec) { output.writeln("<enumDeclaration line=\"", enumDec.name.line, "\">"); writeDdoc(enumDec.comment); if (enumDec.name.type == tok!"identifier") output.writeln("<name>", enumDec.name.text, "</name>"); enumDec.accept(this); output.writeln("</enumDeclaration>"); } override void visit(EnumMember enumMem) { output.writeln("<enumMember line=\"", enumMem.name.line, "\">"); writeDdoc(enumMem.comment); enumMem.accept(this); output.writeln("</enumMember>"); } override void visit(EqualExpression equalExpression) { output.writeln("<equalExpression operator=\"", str(equalExpression.operator), "\">"); output.writeln("<left>"); equalExpression.left.accept(this); output.writeln("</left>"); output.writeln("<right>"); equalExpression.right.accept(this); output.writeln("</right>"); output.writeln("</equalExpression>"); } override void visit(Expression expression) { output.writeln("<expression>"); expression.accept(this); output.writeln("</expression>"); } override void visit(ExpressionStatement expressionStatement) { output.writeln("<expressionStatement>"); expressionStatement.accept(this); output.writeln("</expressionStatement>"); } override void visit(FinalSwitchStatement finalSwitchStatement) { output.writeln("<finalSwitchStatement>"); finalSwitchStatement.accept(this); output.writeln("</finalSwitchStatement>"); } override void visit(Finally finally_) { output.writeln("<finally>"); finally_.accept(this); output.writeln("</finally>"); } override void visit(ForStatement forStatement) { output.writeln("<forStatement>"); if (forStatement.declarationOrStatement !is null) { output.writeln("<initialization>"); visit(forStatement.initialization); output.writeln("</initialization>"); } if (forStatement.test !is null) { output.writeln("<test>"); visit(forStatement.test); output.writeln("</test>"); } if (forStatement.increment !is null) { output.writeln("<increment>"); visit(forStatement.increment); output.writeln("</increment>"); } visit(forStatement.declarationOrStatement); output.writeln("</forStatement>"); } override void visit(ForeachStatement foreachStatement) { output.writeln("<foreachStatement type=\"", str( foreachStatement.type), "\">"); if (foreachStatement.foreachType !is null) visit(foreachStatement.foreachType); if (foreachStatement.foreachTypeList !is null) visit(foreachStatement.foreachTypeList); output.writeln("<low>"); visit(foreachStatement.low); output.writeln("</low>"); if (foreachStatement.high !is null) { output.writeln("<high>"); visit(foreachStatement.high); output.writeln("</high>"); } visit(foreachStatement.declarationOrStatement); output.writeln("</foreachStatement>"); } override void visit(ForeachType foreachType) { output.writeln("<foreachType>"); foreach (constructor; foreachType.typeConstructors) { output.writeln("<typeConstructor>", str(constructor), "</typeConstructor>"); } if (foreachType.type !is null) visit(foreachType.type); visit(foreachType.identifier); output.writeln("</foreachType>"); } override void visit(ForeachTypeList foreachTypeList) { mixin (tagAndAccept!"foreachTypeList"); } override void visit(FunctionAttribute functionAttribute) { mixin (tagAndAccept!"functionAttribute"); } override void visit(FunctionBody functionBody) { mixin (tagAndAccept!"functionBody"); } override void visit(FunctionCallExpression functionCallExpression) { mixin (tagAndAccept!"functionCallExpression"); } override void visit(FunctionCallStatement functionCallStatement) { mixin (tagAndAccept!"functionCallStatement"); } override void visit(FunctionDeclaration functionDec) { output.writeln("<functionDeclaration line=\"", functionDec.name.line, "\">"); output.writeln("<name>", functionDec.name.text, "</name>"); writeDdoc(functionDec.comment); if (functionDec.hasAuto) output.writeln("<auto/>"); if (functionDec.hasRef) output.writeln("<ref/>"); functionDec.accept(this); output.writeln("</functionDeclaration>"); } override void visit(FunctionLiteralExpression functionLiteralExpression) { output.writeln("<functionLiteralExpression type=\"", str(functionLiteralExpression.functionOrDelegate), "\">"); functionLiteralExpression.accept(this); output.writeln("</functionLiteralExpression>"); } override void visit(GotoStatement gotoStatement) { if (gotoStatement.label.type == tok!"default") output.writeln("<gotoStatement default=\"true\"/>"); else if (gotoStatement.label.type == tok!"identifier") output.writeln("<gotoStatement label=\"", gotoStatement.label.text, "\"/>"); else { output.writeln("<gotoStatement>"); output.writeln("<case>"); visit(gotoStatement.expression); output.writeln("</case>"); output.writeln("</gotoStatement>"); } } override void visit(IdentifierChain identifierChain) { mixin (tagAndAccept!"identifierChain"); } override void visit(IdentifierList identifierList) { mixin (tagAndAccept!"identifierList"); } override void visit(IdentifierOrTemplateChain identifierOrTemplateChain) { mixin (tagAndAccept!"identifierOrTemplateChain"); } override void visit(IdentifierOrTemplateInstance identifierOrTemplateInstance) { mixin (tagAndAccept!"identifierOrTemplateInstance"); } override void visit(IdentityExpression identityExpression) { if (identityExpression.negated) output.writeln("<identityExpression operator=\"!is\">"); else output.writeln("<identityExpression operator=\"is\">"); output.writeln("<left>"); visit(identityExpression.left); output.writeln("</left>"); output.writeln("<right>"); visit(identityExpression.right); output.writeln("</right>"); output.writeln("</identityExpression>"); } override void visit(IfStatement ifStatement) { output.writeln("<ifStatement>"); output.writeln("<condition>"); if (ifStatement.identifier.type != tok!"") { if (ifStatement.type is null) output.writeln("<auto/>"); else visit(ifStatement.type); visit(ifStatement.identifier); } ifStatement.expression.accept(this); output.writeln("</condition>"); output.writeln("<then>"); ifStatement.thenStatement.accept(this); output.writeln("</then>"); if (ifStatement.elseStatement !is null) { output.writeln("<else>"); ifStatement.elseStatement.accept(this); output.writeln("</else>"); } output.writeln("</ifStatement>"); } override void visit(ImportBind importBind) { if (importBind.right.type == tok!"") output.writeln("<importBind symbol=\"", importBind.left.text, "\">"); else output.writeln("<importBind symbol=\"", importBind.right.text, "\" rename=\"", importBind.left.text, "\">"); } override void visit(ImportBindings importBindings) { mixin (tagAndAccept!"importBindings"); } override void visit(ImportDeclaration importDeclaration) { mixin (tagAndAccept!"importDeclaration"); } override void visit(ImportExpression importExpression) { mixin (tagAndAccept!"importExpression"); } override void visit(IndexExpression indexExpression) { mixin (tagAndAccept!"indexExpression"); } override void visit(InExpression inExpression) { if (inExpression.negated) output.writeln("<inExpression operator=\"!in\">"); else output.writeln("<inExpression operator=\"in\">"); output.writeln("<left>"); visit(inExpression.left); output.writeln("</left>"); output.writeln("<right>"); visit(inExpression.right); output.writeln("</right>"); output.writeln("</inExpression>"); } override void visit(InStatement inStatement) { mixin (tagAndAccept!"inStatement"); } override void visit(Initialize initialize) { if (initialize.statementNoCaseNoDefault is null) output.writeln("<initialize/>"); else { output.writeln("<initialize>"); visit(initialize.statementNoCaseNoDefault); output.writeln("</initialize>"); } } override void visit(Initializer initializer) { if (initializer.nonVoidInitializer is null) output.writeln("<initializer void=\"true\"/>"); else { output.writeln("<initializer>"); visit(initializer.nonVoidInitializer); output.writeln("</initializer>"); } } override void visit(InterfaceDeclaration interfaceDec) { output.writeln("<interfaceDeclaration line=\"", interfaceDec.name.line, "\">"); output.writeln("<name>", interfaceDec.name.text, "</name>"); writeDdoc(interfaceDec.comment); interfaceDec.accept(this); output.writeln("</interfaceDeclaration>"); } override void visit(Invariant invariant_) { output.writeln("<invariant>"); writeDdoc(invariant_.comment); invariant_.accept(this); output.writeln("</invariant>"); } override void visit(IsExpression isExpression) { output.writeln("<isExpression>"); visit(isExpression.type); if (isExpression.identifier.type != tok!"") visit(isExpression.identifier); if (isExpression.typeSpecialization !is null) { if (isExpression.equalsOrColon == tok!":") output.writeln("<colon/>"); else output.writeln("<equals/>"); visit(isExpression.typeSpecialization); if (isExpression.templateParameterList !is null) visit(isExpression.templateParameterList); } output.writeln("</isExpression>"); } override void visit(KeyValuePair keyValuePair) { output.writeln("<keyValuePair>"); output.writeln("<key>"); visit(keyValuePair.key); output.writeln("</key>"); output.writeln("<value>"); visit(keyValuePair.value); output.writeln("<value>"); output.writeln("</keyValuePair>"); } override void visit(KeyValuePairs keyValuePairs) { mixin (tagAndAccept!"keyValuePairs"); } override void visit (LabeledStatement labeledStatement) { output.writeln("<labeledStatement label=\"", labeledStatement.identifier.text ,"\">"); visit(labeledStatement.declarationOrStatement); output.writeln("</labeledStatement>"); } override void visit(LambdaExpression lambdaExpression) { output.writeln("<lambdaExpression>"); if (lambdaExpression.functionType == tok!"function") output.writeln("<function/>"); if (lambdaExpression.functionType == tok!"delegate") output.writeln("<delegate/>"); lambdaExpression.accept(this); output.writeln("</lambdaExpression>"); } override void visit(LastCatch lastCatch) { mixin (tagAndAccept!"lastCatch"); } override void visit(LinkageAttribute linkageAttribute) { if (linkageAttribute.hasPlusPlus) output.writeln("<linkageAttribute linkage=\"c++\"/>"); else output.writeln("<linkageAttribute linkage=\"", linkageAttribute.identifier.text, "\"/>"); } override void visit(MemberFunctionAttribute memberFunctionAttribute) { output.writeln("<memberFunctionAttribute>"); if (memberFunctionAttribute.atAttribute is null) output.writeln(str(memberFunctionAttribute.tokenType)); else memberFunctionAttribute.accept(this); output.writeln("</memberFunctionAttribute>"); } override void visit(MixinDeclaration mixinDeclaration) { mixin (tagAndAccept!"mixinDeclaration"); } override void visit(MixinExpression mixinExpression) { mixin (tagAndAccept!"mixinExpression"); } override void visit(MixinTemplateDeclaration mixinTemplateDeclaration) { mixin (tagAndAccept!"mixinTemplateDeclaration"); } override void visit(MixinTemplateName mixinTemplateName) { mixin (tagAndAccept!"mixinTemplateName"); } override void visit(Module module_) { output.writeln("<?xml version=\"1.0\"?>"); output.writeln("<module>"); module_.accept(this); output.writeln("</module>"); } override void visit(ModuleDeclaration moduleDeclaration) { mixin (tagAndAccept!"moduleDeclaration"); } override void visit(MulExpression mulExpression) { output.writeln("<mulExpression operator=\"", str(mulExpression.operator) ,"\">"); output.writeln("<left>"); mulExpression.left.accept(this); output.writeln("</left>"); if (mulExpression.right !is null) { output.writeln("<right>"); mulExpression.right.accept(this); output.writeln("</right>"); } output.writeln("</mulExpression>"); } override void visit(NewAnonClassExpression newAnonClassExpression) { mixin (tagAndAccept!"newAnonClassExpression"); } override void visit(NewExpression newExpression) { mixin (tagAndAccept!"newExpression"); } override void visit(StatementNoCaseNoDefault statementNoCaseNoDefault) { mixin (tagAndAccept!"statementNoCaseNoDefault"); } override void visit(NonVoidInitializer nonVoidInitializer) { mixin (tagAndAccept!"nonVoidInitializer"); } override void visit(OrExpression orExpression) { mixin (tagAndAccept!"orExpression"); } override void visit(OrOrExpression orOrExpression) { mixin (tagAndAccept!"orOrExpression"); } override void visit(OutStatement outStatement) { mixin (tagAndAccept!"outStatement"); } override void visit(Parameter param) { output.writeln("<parameter>"); if (param.name.type == tok!"identifier") output.writeln("<name>", param.name.text, "</name>"); foreach (attribute; param.parameterAttributes) { output.writeln("<parameterAttribute>", str(attribute), "</parameterAttribute>"); } param.accept(this); if (param.vararg) output.writeln("<vararg/>"); output.writeln("</parameter>"); } override void visit(Parameters parameters) { mixin (tagAndAccept!"parameters"); } override void visit(Postblit postblit) { mixin (tagAndAccept!"postblit"); } override void visit(PostIncDecExpression postIncDecExpression) { output.writeln("<postIncDecExpression operator=\"", str(postIncDecExpression.operator), "\">"); postIncDecExpression.accept(this); output.writeln("</postIncDecExpression>"); } override void visit(PowExpression powExpression) { output.writeln("<powExpression>"); output.writeln("<left>"); powExpression.left.accept(this); output.writeln("</left>"); if (powExpression.right !is null) { output.writeln("<right>"); powExpression.right.accept(this); output.writeln("</right>"); } output.writeln("</powExpression>"); } override void visit(PragmaDeclaration pragmaDeclaration) { mixin (tagAndAccept!"pragmaDeclaration"); } override void visit(PragmaExpression pragmaExpression) { mixin (tagAndAccept!"pragmaExpression"); } override void visit(PreIncDecExpression preIncDecExpression) { output.writeln("<preIncDecExpression operator=\"", str(preIncDecExpression.operator), "\">"); preIncDecExpression.accept(this); output.writeln("</preIncDecExpression>"); } override void visit(PrimaryExpression primaryExpression) { mixin (tagAndAccept!"primaryExpression"); } // TODO: Register override void visit(RelExpression relExpression) { output.writeln("<relExpression operator=\"", xmlEscape(str(relExpression.operator)), "\">"); output.writeln("<left>"); relExpression.left.accept(this); output.writeln("</left>"); output.writeln("<right>"); relExpression.right.accept(this); output.writeln("</right>"); output.writeln("</relExpression>"); } override void visit(ReturnStatement returnStatement) { if (returnStatement.expression is null) output.writeln("<returnStatement/>"); else { output.writeln("<returnStatement>"); returnStatement.accept(this); output.writeln("</returnStatement>"); } } override void visit(ScopeGuardStatement scopeGuardStatement) { mixin (tagAndAccept!"scopeGuardStatement"); } override void visit(SharedStaticConstructor sharedStaticConstructor) { mixin (tagAndAccept!"sharedStaticConstructor"); } override void visit(SharedStaticDestructor sharedStaticDestructor) { mixin (tagAndAccept!"sharedStaticDestructor"); } override void visit(ShiftExpression shiftExpression) { output.writeln("<shiftExpression operator=\"", xmlEscape(str(shiftExpression.operator)), "\">"); output.writeln("<left>"); shiftExpression.left.accept(this); output.writeln("</left>"); output.writeln("<right>"); shiftExpression.right.accept(this); output.writeln("</right>"); output.writeln("</shiftExpression>"); } override void visit(SingleImport singleImport) { if (singleImport.rename.type == tok!"") output.writeln("<singleImport>"); else output.writeln("<singleImport rename=\"", singleImport.rename.text, "\">"); visit(singleImport.identifierChain); output.writeln("</singleImport>"); } override void visit(SliceExpression sliceExpression) { output.writeln("<sliceExpression>"); if (sliceExpression.unaryExpression is null) { output.writeln("<low"); visit(sliceExpression.lower); output.writeln("</low"); output.writeln("<high"); visit(sliceExpression.upper); output.writeln("</high"); } else visit(sliceExpression.unaryExpression); output.writeln("<sliceExpression>"); } override void visit(Statement statement) { mixin (tagAndAccept!"statement"); } override void visit(StaticAssertDeclaration staticAssertDeclaration) { mixin (tagAndAccept!"staticAssertDeclaration"); } override void visit(StaticAssertStatement staticAssertStatement) { mixin (tagAndAccept!"staticAssertStatement"); } override void visit(StaticConstructor staticConstructor) { mixin (tagAndAccept!"staticConstructor"); } override void visit(StaticDestructor staticDestructor) { mixin (tagAndAccept!"staticDestructor"); } override void visit(StaticIfCondition staticIfCondition) { mixin (tagAndAccept!"staticIfCondition"); } override void visit(StorageClass storageClass) { mixin (tagAndAccept!"storageClass"); } override void visit(StructBody structBody) { mixin (tagAndAccept!"structBody"); } override void visit(StructDeclaration structDec) { output.writeln("<structDeclaration line=\"", structDec.name.line, "\">"); output.writeln("<name>", structDec.name.text, "</name>"); writeDdoc(structDec.comment); structDec.accept(this); output.writeln("</structDeclaration>"); } override void visit(StructInitializer structInitializer) { mixin (tagAndAccept!"structInitializer"); } override void visit(StructMemberInitializer structMemberInitializer) { mixin (tagAndAccept!"structMemberInitializer"); } override void visit(StructMemberInitializers structMemberInitializers) { mixin (tagAndAccept!"structMemberInitializers"); } override void visit(SwitchStatement switchStatement) { mixin (tagAndAccept!"switchStatement"); } override void visit(Symbol symbol) { mixin (tagAndAccept!"symbol"); } override void visit(SynchronizedStatement synchronizedStatement) { mixin (tagAndAccept!"synchronizedStatement"); } override void visit(TemplateAliasParameter templateAliasParameter) { output.writeln("<templateAliasParameter>"); if (templateAliasParameter.type !is null) visit(templateAliasParameter.type); visit(templateAliasParameter.identifier); if (templateAliasParameter.colonExpression !is null) { output.writeln("<specialization>"); visit(templateAliasParameter.colonExpression); output.writeln("</specialization>"); } else if (templateAliasParameter.colonType !is null) { output.writeln("<specialization>"); visit(templateAliasParameter.colonType); output.writeln("</specialization>"); } if (templateAliasParameter.assignExpression !is null) { output.writeln("<default>"); visit(templateAliasParameter.assignExpression); output.writeln("</default>"); } else if (templateAliasParameter.assignType !is null) { output.writeln("<default>"); visit(templateAliasParameter.assignType); output.writeln("</default>"); } output.writeln("</templateAliasParameter>"); } override void visit(TemplateArgument templateArgument) { mixin (tagAndAccept!"templateArgument"); } override void visit(TemplateArgumentList templateArgumentList) { mixin (tagAndAccept!"templateArgumentList"); } override void visit(TemplateArguments templateArguments) { mixin (tagAndAccept!"templateArguments"); } override void visit (EponymousTemplateDeclaration eponymousTemplateDeclaration) { mixin (tagAndAccept!"eponymousTemplateDeclaration"); } override void visit(TemplateDeclaration templateDeclaration) { if (templateDeclaration.eponymousTemplateDeclaration !is null) { output.writeln("<templateDeclaration>"); visit(templateDeclaration.eponymousTemplateDeclaration); output.writeln("</templateDeclaration>"); return; } writeDdoc(templateDeclaration.comment); output.writeln("<templateDeclaration line=\"", templateDeclaration.name.line, "\">"); output.writeln("<name>", templateDeclaration.name.text, "</name>"); visit(templateDeclaration.templateParameters); if (templateDeclaration.constraint !is null) visit(templateDeclaration.constraint); foreach (dec; templateDeclaration.declarations) { if (dec !is null) visit(dec); } output.writeln("</templateDeclaration>"); } override void visit(TemplateInstance templateInstance) { mixin (tagAndAccept!"templateInstance"); } override void visit(TemplateMixinExpression templateMixinExpression) { mixin (tagAndAccept!"templateMixinExpression"); } override void visit(TemplateParameter templateParameter) { mixin (tagAndAccept!"templateParameter"); } override void visit(TemplateParameterList templateParameterList) { mixin (tagAndAccept!"templateParameterList"); } override void visit(TemplateParameters templateParameters) { mixin (tagAndAccept!"templateParameters"); } override void visit(TemplateSingleArgument templateSingleArgument) { mixin (tagAndAccept!"templateSingleArgument"); } override void visit(TemplateThisParameter templateThisParameter) { mixin (tagAndAccept!"templateThisParameter"); } override void visit(TemplateTupleParameter templateTupleParameter) { mixin (tagAndAccept!"templateTupleParameter"); } override void visit(TemplateTypeParameter templateTypeParameter) { mixin (tagAndAccept!"templateTypeParameter"); } override void visit(TemplateValueParameter templateValueParameter) { mixin (tagAndAccept!"templateValueParameter"); } override void visit(TemplateValueParameterDefault templateValueParameterDefault) { mixin (tagAndAccept!"templateValueParameterDefault"); } override void visit(TernaryExpression ternaryExpression) { mixin (tagAndAccept!"ternaryExpression"); } override void visit(ThrowStatement throwStatement) { mixin (tagAndAccept!"throwStatement"); } override void visit(Token token) { string tagName; switch (token.type) { case tok!"": return; case tok!"identifier": tagName = "identifier"; break; case tok!"doubleLiteral": tagName = "doubleLiteral"; break; case tok!"idoubleLiteral": tagName = "idoubleLiteral"; break; case tok!"floatLiteral": tagName = "floatLiteral"; break; case tok!"ifloatLiteral": tagName = "ifloatLiteral"; break; case tok!"intLiteral": tagName = "intLiteral"; break; case tok!"uintLiteral": tagName = "uintLiteral"; break; case tok!"longLiteral": tagName = "longLiteral"; break; case tok!"ulongLiteral": tagName = "ulongLiteral"; break; case tok!"realLiteral": tagName = "realLiteral"; break; case tok!"irealLiteral": tagName = "irealLiteral"; break; case tok!"characterLiteral": tagName = "characterLiteral"; break; case tok!"stringLiteral": tagName = "stringLiteral"; break; case tok!"dstringLiteral": tagName = "dstringLiteral"; break; case tok!"wstringLiteral": tagName = "wstringLiteral"; break; case tok!"$": output.writeln("<dollar/>"); return; default: output.writeln("<", str(token.type), "/>"); return; } output.writeln("<", tagName, ">", xmlEscape(token.text), "</", tagName, ">"); } override void visit(TraitsExpression traitsExpression) { mixin (tagAndAccept!"traitsExpression"); } override void visit(TryStatement tryStatement) { mixin (tagAndAccept!"tryStatement"); } override void visit(Type type) { auto app = appender!string(); auto formatter = new Formatter!(typeof(app))(app); formatter.format(type); output.writeln("<type pretty=\"", app.data, "\">"); type.accept(this); output.writeln("</type>"); } override void visit(Type2 type2) { if (type2.builtinType != tok!"") output.writeln("<type2>", str(type2.builtinType), "</type2>"); else { output.writeln("<type2>"); type2.accept(this); output.writeln("</type2>"); } } override void visit(TypeSpecialization typeSpecialization) { mixin (tagAndAccept!"typeSpecialization"); } override void visit(TypeSuffix typeSuffix) { if (typeSuffix.star) output.writeln("<typeSuffix type=\"*\"/>"); else if (typeSuffix.array) { if (typeSuffix.low is null && typeSuffix.type is null) output.writeln("<typeSuffix type=\"[]\"/>"); else { if (typeSuffix.low is null) { output.writeln("<typeSuffix type=\"[]\">"); visit(typeSuffix.type); output.writeln("</typeSuffix>"); } else { output.writeln("<typeSuffix type=\"[]\">"); if (typeSuffix.high !is null) { output.writeln("<low>"); visit(typeSuffix.low); output.writeln("</low>"); output.writeln("<high>"); visit(typeSuffix.high); output.writeln("</high>"); } else visit(typeSuffix.low); output.writeln("</typeSuffix>"); } } } else { visit(typeSuffix.delegateOrFunction); visit(typeSuffix.parameters); foreach (attr; typeSuffix.memberFunctionAttributes) { if (attr !is null) visit(attr); } } } override void visit(TypeidExpression typeidExpression) { mixin (tagAndAccept!"typeidExpression"); } override void visit(TypeofExpression typeofExpression) { mixin (tagAndAccept!"typeofExpression"); } override void visit(UnaryExpression unaryExpression) { output.writeln("<unaryExpression>"); if (unaryExpression.prefix != tok!"") { output.writeln("<prefix>", xmlEscape(unaryExpression.prefix.text), "</prefix>"); unaryExpression.unaryExpression.accept(this); } if (unaryExpression.suffix != tok!"") { unaryExpression.unaryExpression.accept(this); output.writeln("<suffix>", unaryExpression.suffix.text, "</suffix>"); } else unaryExpression.accept(this); output.writeln("</unaryExpression>"); } override void visit(UnionDeclaration unionDeclaration) { output.writeln("<unionDeclaration line=\"", unionDeclaration.name.line, "\">"); if (unionDeclaration.name != tok!"") output.writeln("<name>", unionDeclaration.name.text, "</name>"); if (unionDeclaration.templateParameters !is null) visit(unionDeclaration.templateParameters); if (unionDeclaration.constraint !is null) visit(unionDeclaration.constraint); if (unionDeclaration.structBody !is null) visit(unionDeclaration.structBody); output.writeln("</unionDeclaration>"); } override void visit(Unittest unittest_) { output.writeln("<unittest>"); unittest_.accept(this); output.writeln("</unittest>"); } override void visit(VariableDeclaration variableDeclaration) { output.writeln("<variableDeclaration>"); writeDdoc(variableDeclaration.comment); variableDeclaration.accept(this); output.writeln("</variableDeclaration>"); } override void visit(Vector vector) { mixin (tagAndAccept!"vector"); } override void visit(VersionCondition versionCondition) { mixin (tagAndAccept!"versionCondition"); } override void visit(VersionSpecification versionSpecification) { mixin (tagAndAccept!"versionSpecification"); } override void visit(WhileStatement whileStatement) { mixin (tagAndAccept!"whileStatement"); } override void visit(WithStatement withStatement) { mixin (tagAndAccept!"withStatement"); } override void visit(XorExpression xorExpression) { output.writeln("<xorExpression>"); output.writeln("<left>"); xorExpression.left.accept(this); output.writeln("</left>"); if (xorExpression.right !is null) { output.writeln("<right>"); xorExpression.right.accept(this); output.writeln("</right>"); } output.writeln("</xorExpression>"); } alias visit = ASTVisitor.visit; private static string xmlEscape(string s) { return s.translate(['<' : "&lt;", '>' : "&gt;", '&' : "&amp;"]); } private void writeDdoc(string comment) { if (comment is null) return; output.writeln("<ddoc>", xmlEscape(comment), "</ddoc>"); } File output; }
D
// ************************************************************ // EXIT // ************************************************************ instance DIA_Ricelord_EXIT(C_INFO) { npc = Bau_900_Ricelord; nr = 999; condition = DIA_Ricelord_EXIT_Condition; information = DIA_Ricelord_EXIT_Info; permanent = 1; description = DIALOG_ENDE; }; func int DIA_Ricelord_EXIT_Condition() { return 1; }; func void DIA_Ricelord_EXIT_Info() { AI_StopProcessInfos(self); }; // ************************************************************ // Hallo // ************************************************************ instance DIA_Ricelord_Hello(C_INFO) { npc = Bau_900_Ricelord; nr = 1; condition = DIA_Ricelord_Hello_Condition; information = DIA_Ricelord_Hello_Info; permanent = 0; // description = "You take care of the rice fields, don't you?"; // description = "Du kümmerst dich um die Reisfelder, richtig?"; description = "Staráš se o rýžová pole, že jo?"; }; func int DIA_Ricelord_Hello_Condition() { return 1; }; func void DIA_Ricelord_Hello_Info() { // AI_Output(other,self,"DIA_Ricelord_Hello_15_00"); //You take care of the rice fields, don't you? // AI_Output(other,self,"DIA_Ricelord_Hello_15_00"); //Du kümmerst dich um die Reisfelder, richtig? AI_Output(other,self,"DIA_Ricelord_Hello_15_00"); //Staráš se o rýžová pole, že jo? // AI_Output(self,other,"DIA_Ricelord_Hello_12_01"); //Why? You looking for work? // AI_Output(self,other,"DIA_Ricelord_Hello_12_01"); //Warum? Suchst du Arbeit? AI_Output(self,other,"DIA_Ricelord_Hello_12_01"); //Proč? Sháníš práci? }; // ************************************************************ // Arbeit // ************************************************************ instance DIA_Ricelord_Arbeit(C_INFO) { npc = Bau_900_Ricelord; nr = 1; condition = DIA_Ricelord_Arbeit_Condition; information = DIA_Ricelord_Arbeit_Info; permanent = 0; // description = "Have you got work for me?"; // description = "Hast du Arbeit für mich?"; description = "Máš pro mě nějakou práci?"; }; func int DIA_Ricelord_Arbeit_Condition() { if Npc_KnowsInfo(hero,DIA_Ricelord_Hello) && !Npc_KnowsInfo(hero,DIA_Lefty_First) && (LeftyDead == False) { return 1; }; }; func void DIA_Ricelord_Arbeit_Info() { // AI_Output(other,self,"DIA_Ricelord_Arbeit_15_00"); //Have you got work for me? // AI_Output(other,self,"DIA_Ricelord_Arbeit_15_00"); //Hast du Arbeit für mich? AI_Output(other,self,"DIA_Ricelord_Arbeit_15_00"); //Máš pro mě nějakou práci? // AI_Output(self,other,"DIA_Ricelord_Arbeit_12_01"); //Go and see Lefty. He's usually to the right of the shed. // AI_Output(self,other,"DIA_Ricelord_Arbeit_12_01"); //Geh zu Lefty. Er ist meistens hier vorne rechts neben der Scheune. AI_Output(self,other,"DIA_Ricelord_Arbeit_12_01"); //Běž za Leftym. Obvykle bývá napravo od stodoly. }; // ************************************************************ // TRADE // ************************************************************ instance DIA_Ricelord_TRADE(C_INFO) { npc = Bau_900_Ricelord; nr = 800; condition = DIA_Ricelord_TRADE_Condition; information = DIA_Ricelord_TRADE_Info; permanent = 1; // description = "We could make a deal..."; // description = "Wir könnten handeln..."; description = "Můžeme uzavřít smlouvu."; trade = 1; }; func int DIA_Ricelord_TRADE_Condition() { // if (Npc_KnowsInfo(hero,DIA_Ricelord_Hello)) // { // return 1; // }; }; func void DIA_Ricelord_TRADE_Info() { // AI_Output(other,self,"DIA_Ricelord_TRADE_15_00"); //We could make a deal... // AI_Output(other,self,"DIA_Ricelord_TRADE_15_00"); //Wir könnten handeln ... AI_Output(other,self,"DIA_Ricelord_TRADE_15_00"); //Můžeme uzavřít smlouvu. // AI_Output(self,other,"DIA_Ricelord_TRADE_12_01"); //What have you got to offer? // AI_Output(self,other,"DIA_Ricelord_TRADE_12_01"); //Was hast du denn zu bieten? AI_Output(self,other,"DIA_Ricelord_TRADE_12_01"); //Co mi můžeš nabídnout? }; // ************************************************************ // Lefty Mission // ************************************************************ instance DIA_Ricelord_LeftySentMe(C_INFO) { npc = Bau_900_Ricelord; nr = 1; condition = DIA_Ricelord_LeftySentMe_Condition; information = DIA_Ricelord_LeftySentMe_Info; permanent = 1; // description = "Lefty sent me."; // description = "Lefty schickt mich."; description = "Poslal mě Lefty."; }; func int DIA_Ricelord_LeftySentMe_Condition() { if Npc_KnowsInfo(hero,DIA_Ricelord_Hello) && (Lefty_Mission == LOG_RUNNING) && (Ricelord_AskedForWater == FALSE) && (LeftyDead == False) { return 1; }; }; func void DIA_Ricelord_LeftySentMe_Info() { // AI_Output(other,self,"DIA_Ricelord_LeftySentMe_15_00"); //Lefty sent me. // AI_Output(other,self,"DIA_Ricelord_LeftySentMe_15_00"); //Lefty schickt mich. AI_Output(other,self,"DIA_Ricelord_LeftySentMe_15_00"); //Poslal mě Lefty. // AI_Output(self,other,"DIA_Ricelord_LeftySentMe_12_01"); //Oh yeah. What did he say? // AI_Output(self,other,"DIA_Ricelord_LeftySentMe_12_01"); //Ach so. Was hat er gesagt? AI_Output(self,other,"DIA_Ricelord_LeftySentMe_12_01"); //Aha. Co říkal? Ricelord_AskedForWater = TRUE; }; // ************************************************************ // Lefty Mission // ************************************************************ instance DIA_Ricelord_GetWater(C_INFO) { npc = Bau_900_Ricelord; nr = 1; condition = DIA_Ricelord_GetWater_Condition; information = DIA_Ricelord_GetWater_Info; permanent = 1; // description = "I'm to bring the peasants some water."; // description = "Ich soll den Bauern Wasser bringen."; description = "Mám přinést rolníkům vodu."; }; func int DIA_Ricelord_GetWater_Condition() { if (Ricelord_AskedForWater == TRUE) { return 1; }; }; func void DIA_Ricelord_GetWater_Info() { // AI_Output(other,self,"DIA_Ricelord_GetWater_15_00"); //I'm to bring the peasants some water. // AI_Output(other,self,"DIA_Ricelord_GetWater_15_00"); //Ich soll den Bauern Wasser bringen. AI_Output(other,self,"DIA_Ricelord_GetWater_15_00"); //Mám přinést rolníkům vodu. if(Lefty_WorkDay == Wld_GetDay()) { // AI_Output(self,other,"DIA_Ricelord_GetWater_12_01"); //Right. Here's a dozen bottles of water. // AI_Output(self,other,"DIA_Ricelord_GetWater_12_01"); //Gut. Hier sind ein Dutzend Flaschen Wasser. AI_Output(self,other,"DIA_Ricelord_GetWater_12_01"); //Dobře. Tady je tucet láhví vody. // AI_Output(self,other,"DIA_Ricelord_GetWater_12_02"); //There's about twice that amount of peasants, so make sure you share it out evenly. // AI_Output(self,other,"DIA_Ricelord_GetWater_12_02"); //Es gibt etwa doppelt so viele Bauern, also verteil sie gleichmäßig. // AI_Output(self,other,"DIA_Ricelord_GetWater_12_02"); //Je toho asi dvakrát víc než potřebují, tak dávej pozor, aby se rozdělila rovnoměrně. AI_Output(self,other,"DIA_Ricelord_GetWater_12_02"); //Je tu asi dvakrát víc rolníků, tak dávej pozor, abys ji rozdělil rovnoměrně. CreateInvItems(self,ItFo_Potion_Water_01, 12); B_GiveInvItems(self,other,ItFo_Potion_Water_01, 12); Ricelord_AskedForWater = FALSE; // B_LogEntry(CH1_CarryWater,"The Rice Lord gave me a dozen water bottles."); // B_LogEntry(CH1_CarryWater,"Der Reislord gab mir ein Dutzend Wasserflaschen."); B_LogEntry(CH1_CarryWater,"Rýžový lord mi dal tucet lahví s vodou."); AI_StopProcessInfos(self); } else if (Lefty_WorkDay == Wld_GetDay()-1) { // AI_Output(self,other,"DIA_Ricelord_GetWater_TooLate_12_00"); //That was yesterday, lad! You'd better go to him. He has something to tell you. // AI_Output(self,other,"DIA_Ricelord_GetWater_TooLate_12_00"); //Das war gestern, Bursche! Geh besser zu ihm. Er hat dir was zu sagen. AI_Output(self,other,"DIA_Ricelord_GetWater_TooLate_12_00"); //To bylo včera, hochu! Bude lepší, když za ním zajdeš. Musí ti něco říci. AI_StopProcessInfos(self); } else { // AI_Output(self,other,"DIA_Ricelord_GetWater_TooLate_12_01"); //That was a few days ago, lad! You'd better go to him. He has something to tell you. // AI_Output(self,other,"DIA_Ricelord_GetWater_TooLate_12_01"); //Das war vor einigen Tagen, Bursche! Geh besser zu ihm. Er hat dir was zu sagen. AI_Output(self,other,"DIA_Ricelord_GetWater_TooLate_12_01"); //To bylo před pár dny, hochu! Měl bys za ním jít. Musí ti něco říci. AI_StopProcessInfos(self); }; };
D
module core.service; import core.configuration; struct Service { private static Configuration _config; static @property ref Configuration config() { return _config; } static @property ref Configuration config(ref Configuration c) { _config = c; return _config; } }
D
import bindbc.sdl; import bindbc.opengl; import bindbc.nuklear; import core.stdc.string; import core.stdc.stdlib; import core.stdc.math; import core.stdc.stdio; import overview; import calculator; import style; import node_editor; struct nk_sdl_device { nk_buffer cmds; nk_draw_null_texture null_; GLuint vbo, vao, ebo; GLuint prog; GLuint vert_shdr; GLuint frag_shdr; GLint attrib_pos; GLint attrib_uv; GLint attrib_col; GLint uniform_tex; GLint uniform_proj; GLuint font_tex; } struct nk_sdl_vertex { float[2] position; float[2] uv; nk_byte[4] col; }; struct nk_sdl { SDL_Window *win; nk_sdl_device ogl; nk_context ctx; nk_font_atlas atlas; } nk_sdl sdl; void nk_sdl_device_create() { GLint status; const(GLchar*) vertex_shader = q{ #version 300 es uniform mat4 ProjMtx; in vec2 Position; in vec2 TexCoord; in vec4 Color; out vec2 Frag_UV; out vec4 Frag_Color; void main() { Frag_UV = TexCoord; Frag_Color = Color; gl_Position = ProjMtx * vec4(Position.xy, 0, 1); } }; const(GLchar*) fragment_shader = q{ #version 300 es precision mediump float; uniform sampler2D Texture; in vec2 Frag_UV; in vec4 Frag_Color; out vec4 Out_Color; void main(){ Out_Color = Frag_Color * texture(Texture, Frag_UV.st); } }; nk_sdl_device *dev = &sdl.ogl; nk_buffer_init_default(&dev.cmds); dev.prog = glCreateProgram(); dev.vert_shdr = glCreateShader(GL_VERTEX_SHADER); dev.frag_shdr = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(dev.vert_shdr, 1, &vertex_shader, null); glShaderSource(dev.frag_shdr, 1, &fragment_shader, null); glCompileShader(dev.vert_shdr); glCompileShader(dev.frag_shdr); glGetShaderiv(dev.vert_shdr, GL_COMPILE_STATUS, &status); assert(status == GL_TRUE); glGetShaderiv(dev.frag_shdr, GL_COMPILE_STATUS, &status); assert(status == GL_TRUE); glAttachShader(dev.prog, dev.vert_shdr); glAttachShader(dev.prog, dev.frag_shdr); glLinkProgram(dev.prog); glGetProgramiv(dev.prog, GL_LINK_STATUS, &status); assert(status == GL_TRUE); dev.uniform_tex = glGetUniformLocation(dev.prog, "Texture"); dev.uniform_proj = glGetUniformLocation(dev.prog, "ProjMtx"); dev.attrib_pos = glGetAttribLocation(dev.prog, "Position"); dev.attrib_uv = glGetAttribLocation(dev.prog, "TexCoord"); dev.attrib_col = glGetAttribLocation(dev.prog, "Color"); { /* buffer setup */ GLsizei vs = nk_sdl_vertex.sizeof; size_t vp = nk_sdl_vertex.position.offsetof; size_t vt = nk_sdl_vertex.uv.offsetof; size_t vc = nk_sdl_vertex.col.offsetof; glGenBuffers(1, &dev.vbo); glGenBuffers(1, &dev.ebo); glGenVertexArrays(1, &dev.vao); glBindVertexArray(dev.vao); glBindBuffer(GL_ARRAY_BUFFER, dev.vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, dev.ebo); glEnableVertexAttribArray(cast(GLuint)dev.attrib_pos); glEnableVertexAttribArray(cast(GLuint)dev.attrib_uv); glEnableVertexAttribArray(cast(GLuint)dev.attrib_col); glVertexAttribPointer(cast(GLuint)dev.attrib_pos, 2, GL_FLOAT, GL_FALSE, vs, cast(void*)vp); glVertexAttribPointer(cast(GLuint)dev.attrib_uv, 2, GL_FLOAT, GL_FALSE, vs, cast(void*)vt); glVertexAttribPointer(cast(GLuint)dev.attrib_col, 4, GL_UNSIGNED_BYTE, GL_TRUE, vs, cast(void*)vc); } glBindTexture(GL_TEXTURE_2D, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindVertexArray(0); } void nk_sdl_device_upload_atlas(const void *image, int width, int height) { nk_sdl_device *dev = &sdl.ogl; glGenTextures(1, &dev.font_tex); glBindTexture(GL_TEXTURE_2D, dev.font_tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, cast(GLsizei)width, cast(GLsizei)height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); } void nk_sdl_device_destroy() { nk_sdl_device* dev = &sdl.ogl; glDetachShader(dev.prog, dev.vert_shdr); glDetachShader(dev.prog, dev.frag_shdr); glDeleteShader(dev.vert_shdr); glDeleteShader(dev.frag_shdr); glDeleteProgram(dev.prog); glDeleteTextures(1, &dev.font_tex); glDeleteBuffers(1, &dev.vbo); glDeleteBuffers(1, &dev.ebo); nk_buffer_free(&dev.cmds); } void nk_sdl_render(nk_anti_aliasing AA, int max_vertex_buffer, int max_element_buffer) { nk_sdl_device *dev = &sdl.ogl; int width, height; int display_width, display_height; nk_vec2 scale; GLfloat[4][4] ortho = [ [2.0f, 0.0f, 0.0f, 0.0f], [0.0f,-2.0f, 0.0f, 0.0f], [0.0f, 0.0f,-1.0f, 0.0f], [-1.0f,1.0f, 0.0f, 1.0f], ]; SDL_GetWindowSize(sdl.win, &width, &height); SDL_GL_GetDrawableSize(sdl.win, &display_width, &display_height); ortho[0][0] /= cast(GLfloat)width; ortho[1][1] /= cast(GLfloat)height; scale.x = display_width/cast(float)width; scale.y = display_height/cast(float)height; /* setup global state */ glViewport(0,0,display_width,display_height); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glActiveTexture(GL_TEXTURE0); /* setup program */ glUseProgram(dev.prog); glUniform1i(dev.uniform_tex, 0); glUniformMatrix4fv(dev.uniform_proj, 1, GL_FALSE, &ortho[0][0]); { /* convert from command queue into draw list and draw to screen */ const(nk_draw_command) *cmd; void *vertices; void *elements; const(nk_draw_index) *offset = null; nk_buffer vbuf; nk_buffer ebuf; /* allocate vertex and element buffer */ glBindVertexArray(dev.vao); glBindBuffer(GL_ARRAY_BUFFER, dev.vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, dev.ebo); glBufferData(GL_ARRAY_BUFFER, max_vertex_buffer, null, GL_STREAM_DRAW); glBufferData(GL_ELEMENT_ARRAY_BUFFER, max_element_buffer, null, GL_STREAM_DRAW); /* load vertices/elements directly into vertex/element buffer */ vertices = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); elements = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_WRITE_ONLY); { /* fill convert configuration */ nk_convert_config config; const(nk_draw_vertex_layout_element)[4] vertex_layout = [ {nk_draw_vertex_layout_attribute.NK_VERTEX_POSITION, nk_draw_vertex_layout_format.NK_FORMAT_FLOAT, nk_sdl_vertex.position.offsetof}, {nk_draw_vertex_layout_attribute.NK_VERTEX_TEXCOORD, nk_draw_vertex_layout_format.NK_FORMAT_FLOAT, nk_sdl_vertex.uv.offsetof}, {nk_draw_vertex_layout_attribute.NK_VERTEX_COLOR, nk_draw_vertex_layout_format.NK_FORMAT_R8G8B8A8, nk_sdl_vertex.col.offsetof}, NK_VERTEX_LAYOUT_END ]; memset(&config, 0, config.sizeof); config.vertex_layout = vertex_layout.ptr; config.vertex_size = nk_sdl_vertex.sizeof; config.vertex_alignment = nk_sdl_vertex.alignof; config.null_ = dev.null_; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; config.global_alpha = 1.0f; config.shape_AA = AA; config.line_AA = AA; /* setup buffers to load vertices and elements */ nk_buffer_init_fixed(&vbuf, vertices, cast(nk_size)max_vertex_buffer); nk_buffer_init_fixed(&ebuf, elements, cast(nk_size)max_element_buffer); nk_convert(&sdl.ctx, &dev.cmds, &vbuf, &ebuf, &config); } glUnmapBuffer(GL_ARRAY_BUFFER); glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); /* iterate over and execute each draw command */ nk_draw_foreach(&sdl.ctx, &dev.cmds, (cmd) { if (!cmd.elem_count) return; glBindTexture(GL_TEXTURE_2D, cast(GLuint)cmd.texture.id); glScissor(cast(GLint)(cmd.clip_rect.x * scale.x), cast(GLint)((height - cast(GLint)(cmd.clip_rect.y + cmd.clip_rect.h)) * scale.y), cast(GLint)(cmd.clip_rect.w * scale.x), cast(GLint)(cmd.clip_rect.h * scale.y)); glDrawElements(GL_TRIANGLES, cast(GLsizei)cmd.elem_count, GL_UNSIGNED_INT, offset); offset += cmd.elem_count; }); nk_clear(&sdl.ctx); } glUseProgram(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindVertexArray(0); glDisable(GL_BLEND); glDisable(GL_SCISSOR_TEST); } extern(C) void nk_sdl_clipboard_paste(nk_handle usr, nk_text_edit *edit) { const char *text = SDL_GetClipboardText(); if (text) nk_textedit_paste(edit, text, nk_strlen(text)); } extern(C) void nk_sdl_clipboard_copy(nk_handle usr, const(char) *text, int len) { import core.stdc.string; import core.stdc.stdlib; char *str = null; if (!len) return; str = cast(char*)malloc(cast(size_t)len+1); if (!str) return; memcpy(str, text, cast(size_t)len); str[len] = '\0'; SDL_SetClipboardText(str); free(str); } nk_context* nk_sdl_init(SDL_Window *win) { sdl.win = win; nk_init_default(&sdl.ctx, null); sdl.ctx.clip.copy = cast(nk_plugin_copy)&nk_sdl_clipboard_copy; sdl.ctx.clip.paste = cast(nk_plugin_paste)&nk_sdl_clipboard_paste; sdl.ctx.clip.userdata = nk_handle_ptr(null); nk_sdl_device_create(); return &sdl.ctx; } void nk_sdl_font_stash_begin(nk_font_atlas **atlas) { nk_font_atlas_init_default(&sdl.atlas); nk_font_atlas_begin(&sdl.atlas); *atlas = &sdl.atlas; } void nk_sdl_font_stash_end() { const(void) *image; int w; int h; image = nk_font_atlas_bake(&sdl.atlas, &w, &h, nk_font_atlas_format.NK_FONT_ATLAS_RGBA32); nk_sdl_device_upload_atlas(image, w, h); nk_font_atlas_end(&sdl.atlas, nk_handle_id(cast(int)sdl.ogl.font_tex), &sdl.ogl.null_); if (sdl.atlas.default_font) nk_style_set_font(&sdl.ctx, &sdl.atlas.default_font.handle); } int nk_sdl_handle_event(SDL_Event *evt) { nk_context *ctx = &sdl.ctx; /* optional grabbing behavior */ if (ctx.input.mouse.grab) { SDL_SetRelativeMouseMode(SDL_TRUE); ctx.input.mouse.grab = 0; } else if (ctx.input.mouse.ungrab) { int x = cast(int)ctx.input.mouse.prev.x, y = cast(int)ctx.input.mouse.prev.y; SDL_SetRelativeMouseMode(SDL_FALSE); SDL_WarpMouseInWindow(sdl.win, x, y); ctx.input.mouse.ungrab = 0; } if (evt.type == SDL_KEYUP || evt.type == SDL_KEYDOWN) { /* key events */ int down = evt.type == SDL_KEYDOWN; const Uint8* state = SDL_GetKeyboardState(null); SDL_Keycode sym = evt.key.keysym.sym; if (sym == SDLK_RSHIFT || sym == SDLK_LSHIFT) nk_input_key(ctx, nk_keys.NK_KEY_SHIFT, down); else if (sym == SDLK_DELETE) nk_input_key(ctx, nk_keys.NK_KEY_DEL, down); else if (sym == SDLK_RETURN) nk_input_key(ctx, nk_keys.NK_KEY_ENTER, down); else if (sym == SDLK_TAB) nk_input_key(ctx, nk_keys.NK_KEY_TAB, down); else if (sym == SDLK_BACKSPACE) nk_input_key(ctx, nk_keys.NK_KEY_BACKSPACE, down); else if (sym == SDLK_HOME) { nk_input_key(ctx, nk_keys.NK_KEY_TEXT_START, down); nk_input_key(ctx, nk_keys.NK_KEY_SCROLL_START, down); } else if (sym == SDLK_END) { nk_input_key(ctx, nk_keys.NK_KEY_TEXT_END, down); nk_input_key(ctx, nk_keys.NK_KEY_SCROLL_END, down); } else if (sym == SDLK_PAGEDOWN) { nk_input_key(ctx, nk_keys.NK_KEY_SCROLL_DOWN, down); } else if (sym == SDLK_PAGEUP) { nk_input_key(ctx, nk_keys.NK_KEY_SCROLL_UP, down); } else if (sym == SDLK_z) nk_input_key(ctx, nk_keys.NK_KEY_TEXT_UNDO, down && state[SDL_SCANCODE_LCTRL]); else if (sym == SDLK_r) nk_input_key(ctx, nk_keys.NK_KEY_TEXT_REDO, down && state[SDL_SCANCODE_LCTRL]); else if (sym == SDLK_c) nk_input_key(ctx, nk_keys.NK_KEY_COPY, down && state[SDL_SCANCODE_LCTRL]); else if (sym == SDLK_v) nk_input_key(ctx, nk_keys.NK_KEY_PASTE, down && state[SDL_SCANCODE_LCTRL]); else if (sym == SDLK_x) nk_input_key(ctx, nk_keys.NK_KEY_CUT, down && state[SDL_SCANCODE_LCTRL]); else if (sym == SDLK_b) nk_input_key(ctx, nk_keys.NK_KEY_TEXT_LINE_START, down && state[SDL_SCANCODE_LCTRL]); else if (sym == SDLK_e) nk_input_key(ctx, nk_keys.NK_KEY_TEXT_LINE_END, down && state[SDL_SCANCODE_LCTRL]); else if (sym == SDLK_UP) nk_input_key(ctx, nk_keys.NK_KEY_UP, down); else if (sym == SDLK_DOWN) nk_input_key(ctx, nk_keys.NK_KEY_DOWN, down); else if (sym == SDLK_LEFT) { if (state[SDL_SCANCODE_LCTRL]) nk_input_key(ctx, nk_keys.NK_KEY_TEXT_WORD_LEFT, down); else nk_input_key(ctx, nk_keys.NK_KEY_LEFT, down); } else if (sym == SDLK_RIGHT) { if (state[SDL_SCANCODE_LCTRL]) nk_input_key(ctx, nk_keys.NK_KEY_TEXT_WORD_RIGHT, down); else nk_input_key(ctx, nk_keys.NK_KEY_RIGHT, down); } else return 0; return 1; } else if (evt.type == SDL_MOUSEBUTTONDOWN || evt.type == SDL_MOUSEBUTTONUP) { /* mouse button */ int down = evt.type == SDL_MOUSEBUTTONDOWN; const int x = evt.button.x, y = evt.button.y; if (evt.button.button == SDL_BUTTON_LEFT) { if (evt.button.clicks > 1) nk_input_button(ctx, nk_buttons.NK_BUTTON_DOUBLE, x, y, down); nk_input_button(ctx, nk_buttons.NK_BUTTON_LEFT, x, y, down); } else if (evt.button.button == SDL_BUTTON_MIDDLE) nk_input_button(ctx, nk_buttons.NK_BUTTON_MIDDLE, x, y, down); else if (evt.button.button == SDL_BUTTON_RIGHT) nk_input_button(ctx, nk_buttons.NK_BUTTON_RIGHT, x, y, down); return 1; } else if (evt.type == SDL_MOUSEMOTION) { /* mouse motion */ if (ctx.input.mouse.grabbed) { int x = cast(int)ctx.input.mouse.prev.x, y = cast(int)ctx.input.mouse.prev.y; nk_input_motion(ctx, x + evt.motion.xrel, y + evt.motion.yrel); } else nk_input_motion(ctx, evt.motion.x, evt.motion.y); return 1; } else if (evt.type == SDL_TEXTINPUT) { /* text input */ nk_glyph glyph; memcpy(cast(void*)glyph.ptr, cast(void*)evt.text.text, NK_UTF_SIZE); nk_input_glyph(ctx, glyph.ptr); return 1; } else if (evt.type == SDL_MOUSEWHEEL) { /* mouse wheel */ nk_input_scroll(ctx,nk_vec2(cast(float)evt.wheel.x,cast(float)evt.wheel.y)); return 1; } return 0; } void nk_sdl_shutdown() { nk_font_atlas_clear(&sdl.atlas); nk_free(&sdl.ctx); nk_sdl_device_destroy(); memset(&sdl, 0, sdl.sizeof); } int main(string[] args) { int win_width= 1200; int win_height = 800; version(BindNuklear_Static) {} else { NuklearSupport nuksup = loadNuklear(); if(nuksup != NuklearSupport.Nuklear4) { printf("Error: Nuklear library is not found."); return -1; } } version(BindSDL_Static) {} else { SDLSupport sdlsup = loadSDL(); if (sdlsup != sdlSupport) { if (sdlsup == SDLSupport.badLibrary) printf("Warning: failed to load some SDL functions. It seems that you have an old version of SDL."); else { printf("Error: SDL library is not found. Please, install SDL 2.0.5"); return -1; } } } if (SDL_Init(SDL_INIT_EVERYTHING) == -1) { printf("Error: failed to init SDL: %s\n", SDL_GetError()); return -1; } SDL_GL_SetAttribute (SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_Window *win = SDL_CreateWindow("Demo", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1200, 800, SDL_WINDOW_OPENGL|SDL_WINDOW_SHOWN); SDL_GLContext glContext = SDL_GL_CreateContext(win); GLSupport glsup = loadOpenGL(); if (!isOpenGLLoaded()) { printf("Error: failed to load OpenGL functions. Please, update graphics card driver and make sure it supports OpenGL"); return -1; } SDL_GL_SetSwapInterval(1); glViewport(0, 0, win_width, win_height); nk_context *ctx; nk_colorf bg; ctx = nk_sdl_init(win); nk_font_atlas *atlas; nk_sdl_font_stash_begin(&atlas); nk_sdl_font_stash_end(); style.theme them = style.theme.THEME_BLUE; style.set_style(ctx, them); bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f; enum {EASY, HARD} int op = EASY; int property = 20; bool running = true; while(running) { /* Input */ SDL_Event evt; nk_input_begin(ctx); while (SDL_PollEvent(&evt)) { if (evt.type == SDL_QUIT) { running = false; continue; } nk_sdl_handle_event(&evt); } nk_input_end(ctx); calculator.calculator(ctx); if (nk_begin(ctx, "Demo", nk_rect(50, 50, 230, 250), NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_SCALABLE| NK_WINDOW_MINIMIZABLE|NK_WINDOW_TITLE)) { nk_layout_row_static(ctx, 30, 80, 1); if (nk_button_label(ctx, "button")) { printf("button pressed\n"); } if (nk_button_label(ctx, "style")) { them += 1; if(them > style.theme.max) them = style.theme.min; style.set_style(ctx, them); } nk_layout_row_dynamic(ctx, 30, 2); if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); nk_layout_row_dynamic(ctx, 20, 1); nk_label(ctx, "background:", NK_TEXT_LEFT); nk_layout_row_dynamic(ctx, 25, 1); if (nk_combo_begin_color(ctx, nk_rgb_cf(bg), nk_vec2(nk_widget_width(ctx),400))) { nk_layout_row_dynamic(ctx, 120, 1); bg = nk_color_picker(ctx, bg, NK_RGBA); nk_layout_row_dynamic(ctx, 25, 1); bg.r = nk_propertyf(ctx, "#R:", 0, bg.r, 1.0f, 0.01f,0.005f); bg.g = nk_propertyf(ctx, "#G:", 0, bg.g, 1.0f, 0.01f,0.005f); bg.b = nk_propertyf(ctx, "#B:", 0, bg.b, 1.0f, 0.01f,0.005f); bg.a = nk_propertyf(ctx, "#A:", 0, bg.a, 1.0f, 0.01f,0.005f); nk_combo_end(ctx); } } nk_end(ctx); overview.overview(ctx); node_editor.node_editor(ctx); /* Draw */ SDL_GetWindowSize(win, &win_width, &win_height); glViewport(0, 0, win_width, win_height); glClear(GL_COLOR_BUFFER_BIT); glClearColor(bg.r, bg.g, bg.b, bg.a); /* IMPORTANT: `nk_sdl_render` modifies some global OpenGL state * with blending, scissor, face culling, depth test and viewport and * defaults everything back into a default state. * Make sure to either a.) save and restore or b.) reset your own state after * rendering the UI. */ nk_sdl_render(NK_ANTI_ALIASING_ON,512*1024, 128*1024); SDL_GL_SwapWindow(win); } nk_sdl_shutdown(); SDL_GL_DeleteContext(glContext); SDL_DestroyWindow(win); SDL_Quit(); return 0; }
D
/Users/piaojin/Desktop/PiaojinSwiftServer/.build/debug/MySQL.build/MySQL.swift.o : /Users/piaojin/Desktop/PiaojinSwiftServer/.build/checkouts/Perfect-MySQL.git-4976130768219902098/Sources/MySQL/MySQL.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql/psi/psi_base.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql/psi/psi_memory.h /usr/local/Cellar/mysql/5.7.18/include/mysql/my_alloc.h /usr/local/Cellar/mysql/5.7.18/include/mysql/typelib.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql/plugin_auth_common.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql/client_plugin.h /usr/local/Cellar/mysql/5.7.18/include/mysql/my_list.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql_time.h /usr/local/Cellar/mysql/5.7.18/include/mysql/my_command.h /usr/local/Cellar/mysql/5.7.18/include/mysql/binary_log_types.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql_com.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql_version.h /usr/local/include/mysql/mysql.h /Users/piaojin/Desktop/PiaojinSwiftServer/.build/checkouts/Perfect-mysqlclient.git-5333716826204139417/module.modulemap /Users/piaojin/Desktop/PiaojinSwiftServer/.build/debug/MySQL.build/MySQL~partial.swiftmodule : /Users/piaojin/Desktop/PiaojinSwiftServer/.build/checkouts/Perfect-MySQL.git-4976130768219902098/Sources/MySQL/MySQL.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql/psi/psi_base.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql/psi/psi_memory.h /usr/local/Cellar/mysql/5.7.18/include/mysql/my_alloc.h /usr/local/Cellar/mysql/5.7.18/include/mysql/typelib.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql/plugin_auth_common.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql/client_plugin.h /usr/local/Cellar/mysql/5.7.18/include/mysql/my_list.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql_time.h /usr/local/Cellar/mysql/5.7.18/include/mysql/my_command.h /usr/local/Cellar/mysql/5.7.18/include/mysql/binary_log_types.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql_com.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql_version.h /usr/local/include/mysql/mysql.h /Users/piaojin/Desktop/PiaojinSwiftServer/.build/checkouts/Perfect-mysqlclient.git-5333716826204139417/module.modulemap /Users/piaojin/Desktop/PiaojinSwiftServer/.build/debug/MySQL.build/MySQL~partial.swiftdoc : /Users/piaojin/Desktop/PiaojinSwiftServer/.build/checkouts/Perfect-MySQL.git-4976130768219902098/Sources/MySQL/MySQL.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql/psi/psi_base.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql/psi/psi_memory.h /usr/local/Cellar/mysql/5.7.18/include/mysql/my_alloc.h /usr/local/Cellar/mysql/5.7.18/include/mysql/typelib.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql/plugin_auth_common.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql/client_plugin.h /usr/local/Cellar/mysql/5.7.18/include/mysql/my_list.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql_time.h /usr/local/Cellar/mysql/5.7.18/include/mysql/my_command.h /usr/local/Cellar/mysql/5.7.18/include/mysql/binary_log_types.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql_com.h /usr/local/Cellar/mysql/5.7.18/include/mysql/mysql_version.h /usr/local/include/mysql/mysql.h /Users/piaojin/Desktop/PiaojinSwiftServer/.build/checkouts/Perfect-mysqlclient.git-5333716826204139417/module.modulemap
D
module pixelgui.render; /// Premultiplied [R, G, B, A] color alias Color = ubyte[4]; /// string toColorHexString(in Color color) { pragma(inline, true) immutable(char)[2] digit(ubyte b) { ubyte l = b / 16; ubyte r = b % 16; immutable(char) lc = cast(immutable(char))((l >= 10 ? 'A' - 10 : '0') + l); immutable(char) rc = cast(immutable(char))((r >= 10 ? 'A' - 10 : '0') + r); return [lc, rc]; } if (color[3] == 0xFF) return '#' ~ digit(color[0]) ~ digit(color[1]) ~ digit(color[2]); else return '#' ~ digit(color[0]) ~ digit(color[1]) ~ digit(color[2]) ~ digit(color[3]); } /// Non-premultiplied color template colUnmul(string hex) { static if (hex.length == 6) enum colUnmul = cast(Color)[mixin("0x" ~ hex[0 .. 2]), mixin("0x" ~ hex[2 .. 4]), mixin("0x" ~ hex[4 .. 6]), 0xFF]; else static if (hex.length == 8) enum colUnmul = cast(Color)[mixin("0x" ~ hex[0 .. 2]), mixin("0x" ~ hex[2 .. 4]), mixin("0x" ~ hex[4 .. 6]), mixin("0x" ~ hex[6 .. 8])]; else static assert(false, "Hex color string '" ~ hex ~ "' not supported"); } /// Premultiplied color template col(string hex) { static if (hex.length == 6) enum col = cast(Color)[mixin("0x" ~ hex[0 .. 2]), mixin("0x" ~ hex[2 .. 4]), mixin("0x" ~ hex[4 .. 6]), 0xFF]; else static if (hex.length == 8) enum col = cast(Color)[mixin("0x" ~ hex[0 .. 2]), mixin("0x" ~ hex[2 .. 4]), mixin("0x" ~ hex[4 .. 6]), mixin("0x" ~ hex[6 .. 8])].premultiply; else static assert(false, "Hex color string '" ~ hex ~ "' not supported"); } enum HTMLColors : Color { aliceBlue = col!"F0F8FF", antiqueWhite = col!"FAEBD7", aqua = col!"00FFFF", aquamarine = col!"7FFFD4", azure = col!"F0FFFF", beige = col!"F5F5DC", bisque = col!"FFE4C4", black = col!"000000", blanchedAlmond = col!"FFEBCD", blue = col!"0000FF", blueViolet = col!"8A2BE2", brown = col!"A52A2A", burlyWood = col!"DEB887", cadetBlue = col!"5F9EA0", chartreuse = col!"7FFF00", chocolate = col!"D2691E", coral = col!"FF7F50", cornflowerBlue = col!"6495ED", cornsilk = col!"FFF8DC", crimson = col!"DC143C", cyan = col!"00FFFF", darkBlue = col!"00008B", darkCyan = col!"008B8B", darkGoldenRod = col!"B8860B", darkGray = col!"A9A9A9", darkGrey = col!"A9A9A9", darkGreen = col!"006400", darkKhaki = col!"BDB76B", darkMagenta = col!"8B008B", darkOliveGreen = col!"556B2F", darkOrange = col!"FF8C00", darkOrchid = col!"9932CC", darkRed = col!"8B0000", darkSalmon = col!"E9967A", darkSeaGreen = col!"8FBC8F", darkSlateBlue = col!"483D8B", darkSlateGray = col!"2F4F4F", darkSlateGrey = col!"2F4F4F", darkTurquoise = col!"00CED1", darkViolet = col!"9400D3", deepPink = col!"FF1493", deepSkyBlue = col!"00BFFF", dimGray = col!"696969", dimGrey = col!"696969", dodgerBlue = col!"1E90FF", fireBrick = col!"B22222", floralWhite = col!"FFFAF0", forestGreen = col!"228B22", fuchsia = col!"FF00FF", gainsboro = col!"DCDCDC", ghostWhite = col!"F8F8FF", gold = col!"FFD700", goldenRod = col!"DAA520", gray = col!"808080", grey = col!"808080", green = col!"008000", greenYellow = col!"ADFF2F", honeyDew = col!"F0FFF0", hotPink = col!"FF69B4", indianRed = col!"CD5C5C", indigo = col!"4B0082", ivory = col!"FFFFF0", khaki = col!"F0E68C", lavender = col!"E6E6FA", lavenderBlush = col!"FFF0F5", lawnGreen = col!"7CFC00", lemonChiffon = col!"FFFACD", lightBlue = col!"ADD8E6", lightCoral = col!"F08080", lightCyan = col!"E0FFFF", lightGoldenRodYellow = col!"FAFAD2", lightGray = col!"D3D3D3", lightGrey = col!"D3D3D3", lightGreen = col!"90EE90", lightPink = col!"FFB6C1", lightSalmon = col!"FFA07A", lightSeaGreen = col!"20B2AA", lightSkyBlue = col!"87CEFA", lightSlateGray = col!"778899", lightSlateGrey = col!"778899", lightSteelBlue = col!"B0C4DE", lightYellow = col!"FFFFE0", lime = col!"00FF00", limeGreen = col!"32CD32", linen = col!"FAF0E6", magenta = col!"FF00FF", maroon = col!"800000", mediumAquaMarine = col!"66CDAA", mediumBlue = col!"0000CD", mediumOrchid = col!"BA55D3", mediumPurple = col!"9370DB", mediumSeaGreen = col!"3CB371", mediumSlateBlue = col!"7B68EE", mediumSpringGreen = col!"00FA9A", mediumTurquoise = col!"48D1CC", mediumVioletRed = col!"C71585", midnightBlue = col!"191970", mintCream = col!"F5FFFA", mistyRose = col!"FFE4E1", moccasin = col!"FFE4B5", navajoWhite = col!"FFDEAD", navy = col!"000080", oldLace = col!"FDF5E6", olive = col!"808000", oliveDrab = col!"6B8E23", orange = col!"FFA500", orangeRed = col!"FF4500", orchid = col!"DA70D6", paleGoldenRod = col!"EEE8AA", paleGreen = col!"98FB98", paleTurquoise = col!"AFEEEE", paleVioletRed = col!"DB7093", papayaWhip = col!"FFEFD5", peachPuff = col!"FFDAB9", peru = col!"CD853F", pink = col!"FFC0CB", plum = col!"DDA0DD", powderBlue = col!"B0E0E6", purple = col!"800080", rebeccaPurple = col!"663399", red = col!"FF0000", rosyBrown = col!"BC8F8F", royalBlue = col!"4169E1", saddleBrown = col!"8B4513", salmon = col!"FA8072", sandyBrown = col!"F4A460", seaGreen = col!"2E8B57", seaShell = col!"FFF5EE", sienna = col!"A0522D", silver = col!"C0C0C0", skyBlue = col!"87CEEB", slateBlue = col!"6A5ACD", slateGray = col!"708090", slateGrey = col!"708090", snow = col!"FFFAFA", springGreen = col!"00FF7F", steelBlue = col!"4682B4", tan = col!"D2B48C", teal = col!"008080", thistle = col!"D8BFD8", tomato = col!"FF6347", turquoise = col!"40E0D0", violet = col!"EE82EE", wheat = col!"F5DEB3", white = col!"FFFFFF", whiteSmoke = col!"F5F5F5", yellow = col!"FFFF00", yellowGreen = col!"9ACD32", } /// Represents a drawable area struct RenderTarget { /// Pixels in RGBA format ubyte[] pixels; /// in pixels int w, h; } /// Alpha premultiply a color. Color premultiply(ubyte[4] rgba) { const ushort r = rgba[0] * rgba[3]; const ushort g = rgba[1] * rgba[3]; const ushort b = rgba[2] * rgba[3]; return [(r / 255) & 0xFF, (g / 255) & 0xFF, (b / 255) & 0xFF, rgba[3]]; } /// Alpha premultiply a color (alpha as first argument). ubyte[4] premultiplyARGB(ubyte[4] rgba) { const ushort r = rgba[1] * rgba[0]; const ushort g = rgba[2] * rgba[0]; const ushort b = rgba[3] * rgba[0]; return [rgba[0], (r / 255) & 0xFF, (g / 255) & 0xFF, (b / 255) & 0xFF]; } /// Undo alpha premultiplication ubyte[4] demultiply(Color c) { if (c[3] == 0) return c; auto r = c[0] * 255 / c[3]; auto g = c[1] * 255 / c[3]; auto b = c[2] * 255 / c[3]; return [r & 0xFF, g & 0xFF, b & 0xFF, c[3]]; } /// Linear interpolation of a 4 byte object Color lerpColor(Color a, Color b, float t) { Color ret; ret[0] = cast(ubyte)(a[0] * (1 - t) + b[0] * t); ret[1] = cast(ubyte)(a[1] * (1 - t) + b[1] * t); ret[2] = cast(ubyte)(a[2] * (1 - t) + b[2] * t); ret[3] = cast(ubyte)(a[3] * (1 - t) + b[3] * t); return ret; } /// Blending operators (See https://www.cairographics.org/operators/) enum BlendOp { /// Always fully replace the color with the foreground source, /// Physically accurate color mixing over, } /// Combines two colors using either preset blending operations or a function pragma(inline, true) Color blend(alias mixOp = BlendOp.over)(Color fg, Color bg) { static if (is(typeof(mixOp) == BlendOp)) { static if (mixOp == BlendOp.source) { pragma(msg, "Warning: blend called with BlendOp.source, consider just using the fg instead as this is a no-op"); return fg; } else { ubyte[4] r; static if (mixOp == BlendOp.over) { r[3] = (fg[3] + bg[3] * (255 - fg[3]) / 255) & 0xFF; if (r[3] == 0) return r; foreach (c; 0 .. 3) { r[c] = ((fg[c] * 255 + bg[c] * (255 - fg[3])) / r[3]) & 0xFF; } } else static assert(false); return r; } } else return mixOp(fg, bg); } /// @safe unittest { assert(blend!(BlendOp.over)(col!"FF000080", col!"000000") == col!"800000"); assert(blend!(BlendOp.over)(col!"FF0000", col!"000000") == col!"FF0000"); assert(blend!((a, b) => b)(col!"FF0000", col!"00FF00") == col!"00FF00"); } /// Copies a bitmap to another one void copyTo(alias mixOp = BlendOp.over)(in RenderTarget src, ref RenderTarget target, int x, int y, int offX = 0, int offY = 0, int clipWidth = 0, int clipHeight = 0) { if (clipWidth == 0) clipWidth = src.w; else if (clipWidth < 0) clipWidth = src.w + clipWidth; if (clipHeight == 0) clipHeight = src.h; else if (clipHeight == 0) clipHeight = src.h + clipHeight; if (x < 0) { offX -= x; clipWidth += x; x = 0; } if (y < 0) { offY -= y; clipHeight += y; y = 0; } if (x >= target.w || y >= target.h) return; if (clipWidth <= 0 || clipHeight <= 0) return; if (offX < 0) offX = 0; if (offY < 0) offY = 0; if (clipWidth + offX >= src.w) clipWidth = src.w - offX; if (clipHeight + offY >= src.h) clipHeight = src.h - offY; if (clipWidth + x >= target.w) clipWidth = target.w - x; if (clipHeight + y >= target.h) clipHeight = target.h - y; if (x + clipWidth < 0 || y + clipHeight < 0) return; for (int row = 0; row < clipHeight; row++) { static if (mixOp == BlendOp.source) { target.pixels[(x + (y + row) * target.w) * 4 .. (x + (y + row) * target.w + clipWidth) * 4] = src.pixels[( offX + (offY + row) * src.w) * 4 .. (offX + (offY + row) * src.w + clipWidth) * 4]; } else { for (int col = 0; col < clipWidth; col++) { target.pixels[(x + col + (y + row) * target.w) * 4 .. (x + col + (y + row) * target.w) * 4 + 4][0 .. 4] = blend!mixOp( src.pixels[(offX + col + (offY + row) * src.w) * 4 .. ( offX + col + (offY + row) * src.w) * 4 + 4][0 .. 4], target.pixels[(x + col + (y + row) * target.w) * 4 .. (x + col + (y + row) * target.w) * 4 + 4][0 .. 4]); } } } } /// @safe unittest { RenderTarget image; image.w = 4; image.h = 4; image.pixels = new ubyte[4 * 4 * 4]; RenderTarget over; over.w = 2; over.h = 2; over.pixels = new ubyte[2 * 2 * 4]; over.fillRect!(BlendOp.source)(0, 0, 2, 2, col!"00FF00"); over.copyTo!(BlendOp.source)(image, 1, 1); //dfmt off enum w = 0xFF; assert(image.pixels == [ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,w,0,w, 0,w,0,w, 0,0,0,0, 0,0,0,0, 0,w,0,w, 0,w,0,w, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, ]); //dfmt on image.pixels[] = 0; over.copyTo!(BlendOp.over)(image, 1, 1); //dfmt off assert(image.pixels == [ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,w,0,w, 0,w,0,w, 0,0,0,0, 0,0,0,0, 0,w,0,w, 0,w,0,w, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, ]); //dfmt on } /// Fills a rectangle inside the image with a pattern. void fillPattern(alias patternFun, alias mixOp = BlendOp.over)( ref RenderTarget target, int x, int y, int w, int h) { if (w <= 0 || h <= 0) return; if (x + w < 0 || y + h < 0 || x >= target.w || y >= target.h) return; if (x < 0) { w += x; x = 0; } if (y < 0) { h += y; y = 0; } if (w <= 0 || h <= 0) return; if (x + w > target.w) w = target.w - x; if (y + h > target.h) h = target.h - y; for (int v; v < h; v++) { for (int c; c < w; c++) { static if (__traits(compiles, { patternFun(c, v, x + c, y + v, w, h); })) const rgba = patternFun(c, v, x + c, y + v, w, h); else static if (__traits(compiles, { patternFun(c, v, w, h); })) const rgba = patternFun(c, v, w, h); else static if (__traits(compiles, { patternFun(c, v); })) const rgba = patternFun(c, v); else static assert(false, "Can't use pattern function which doesn't take 2/4/6 arguments."); if (rgba == col!"FFFFFF00") continue; static if (mixOp == BlendOp.source) { (cast(uint[]) target.pixels)[x + c + (y + v) * target.w] = rgba.rgbaToMemory; } else { auto blended = blend!mixOp(rgba, target.pixels[( x + c + (y + v) * target.w) * 4 .. (x + c + (y + v) * target.w) * 4 + 4][0 .. 4]); target.pixels[(x + c + (y + v) * target.w) * 4 + 0] = blended[0]; target.pixels[(x + c + (y + v) * target.w) * 4 + 1] = blended[1]; target.pixels[(x + c + (y + v) * target.w) * 4 + 2] = blended[2]; target.pixels[(x + c + (y + v) * target.w) * 4 + 3] = blended[3]; } } } } /// Draws a rectangle border with a solid color. void drawBorder(alias mixOp = BlendOp.over)(ref RenderTarget target, int x, int y, int w, int h, in Color rgba) pure nothrow @safe { if (w <= 0 || h <= 0) return; if (x + w < 0 || y + h < 0 || x >= target.w || y >= target.h) return; if (x < 0) { w += x; x = 0; } if (y < 0) { h += y; y = 0; } if (w <= 0 || h <= 0) return; if (x + w > target.w) w = target.w - x; if (y + h > target.h) h = target.h - y; static if (mixOp == BlendOp.source) { uint color = rgba.rgbaToMemory; (cast(uint[]) target.pixels[(x + y * target.w) * 4 .. (x + w + y * target.w) * 4])[] = color; (cast(uint[]) target.pixels[(x + (y + h - 1) * target.w) * 4 .. (x + w + (y + h - 1) * target.w) * 4])[] = color; for (int v = 1; v < h - 1; v++) { (cast(uint[]) target.pixels)[x + (y + v) * target.w] = color; (cast(uint[]) target.pixels)[x + w - 1 + (y + v) * target.w] = color; } } else { foreach (v; [0, h - 1]) { for (int c; c < w; c++) { auto i = (x + c + (y + v) * target.w) * 4; auto blended = blend!mixOp(rgba, target.pixels[i .. i + 4][0 .. 4]); target.pixels[i + 0] = blended[0]; target.pixels[i + 1] = blended[1]; target.pixels[i + 2] = blended[2]; target.pixels[i + 3] = blended[3]; } } for (int v = 1; v < h - 1; v++) { { auto i = (x + (y + v) * target.w) * 4; auto blended = blend!mixOp(rgba, target.pixels[i .. i + 4][0 .. 4]); target.pixels[i + 0] = blended[0]; target.pixels[i + 1] = blended[1]; target.pixels[i + 2] = blended[2]; target.pixels[i + 3] = blended[3]; } { auto i = (x + w - 1 + (y + v) * target.w) * 4; auto blended = blend!mixOp(rgba, target.pixels[i .. i + 4][0 .. 4]); target.pixels[i + 0] = blended[0]; target.pixels[i + 1] = blended[1]; target.pixels[i + 2] = blended[2]; target.pixels[i + 3] = blended[3]; } } } } /// Fills a rectangle inside the image with a solid color. void fillRect(alias mixOp = BlendOp.over)(ref RenderTarget target, int x, int y, int w, int h, in Color rgba) pure nothrow @safe { if (w <= 0 || h <= 0) return; if (x + w < 0 || y + h < 0 || x >= target.w || y >= target.h) return; if (x < 0) { w += x; x = 0; } if (y < 0) { h += y; y = 0; } if (w <= 0 || h <= 0) return; if (x + w > target.w) w = target.w - x; if (y + h > target.h) h = target.h - y; static if (mixOp == BlendOp.source) uint color = rgba.rgbaToMemory; for (int v; v < h; v++) { static if (mixOp == BlendOp.source) (cast(uint[]) target.pixels[(x + (y + v) * target.w) * 4 .. (x + w + (y + v) * target.w) * 4])[] = color; else { for (int c; c < w; c++) { auto blended = blend!mixOp(rgba, target.pixels[( x + c + (y + v) * target.w) * 4 .. (x + c + (y + v) * target.w) * 4 + 4][0 .. 4]); target.pixels[(x + c + (y + v) * target.w) * 4 + 0] = blended[0]; target.pixels[(x + c + (y + v) * target.w) * 4 + 1] = blended[1]; target.pixels[(x + c + (y + v) * target.w) * 4 + 2] = blended[2]; target.pixels[(x + c + (y + v) * target.w) * 4 + 3] = blended[3]; } } } } /// Clears the buffer with one solid color using SSE. void clearFast(ref RenderTarget target, in Color rgba) pure nothrow @nogc @safe { (cast(uint[]) target.pixels)[] = rgba.rgbaToMemory; } /// Converts a Color value to the system dependent uint for SSE optimization. auto rgbaToMemory(inout Color rgba) pure nothrow @nogc @trusted { return *(cast(uint*) rgba.ptr); } /// @safe unittest { RenderTarget image; image.w = 2; image.h = 1; image.pixels = new ubyte[4 * 2]; immutable Color bg = [0x10, 0x20, 0x30, 0x40]; image.clearFast(bg); assert(image.pixels[0] == 0x10); assert(image.pixels[1] == 0x20); assert(image.pixels[2] == 0x30); assert(image.pixels[3] == 0x40); assert(image.pixels[4] == 0x10); assert(image.pixels[5] == 0x20); assert(image.pixels[6] == 0x30); assert(image.pixels[7] == 0x40); } /// @safe unittest { RenderTarget image; image.w = 4; image.h = 4; image.pixels = new ubyte[4 * 4 * 4]; image.fillRect!(BlendOp.source)(1, 1, 2, 2, col!"00FF00"); //dfmt off enum w = 0xFF; assert(image.pixels == [ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,w,0,w, 0,w,0,w, 0,0,0,0, 0,0,0,0, 0,w,0,w, 0,w,0,w, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, ]); //dfmt on } /// @safe unittest { RenderTarget image; image.w = 4; image.h = 4; image.pixels = new ubyte[4 * 4 * 4]; image.fillRect!(BlendOp.source)(-1, -1, 2, 2, col!"00FF00"); //dfmt off enum w = 0xFF; assert(image.pixels == [ 0,w,0,w, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, ]); //dfmt on }
D
/** * Compiler implementation of the * $(LINK2 http://www.dlang.org, D programming language). * * Copyright: Copyright (C) 1999-2018 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/tokens.d, _tokens.d) * Documentation: https://dlang.org/phobos/dmd_tokens.html * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/tokens.d */ module dmd.tokens; import core.stdc.ctype; import core.stdc.stdio; import core.stdc.string; import dmd.globals; import dmd.identifier; import dmd.root.ctfloat; import dmd.root.outbuffer; import dmd.root.rmem; import dmd.utf; enum TOK : int { reserved, // Other leftParentheses, rightParentheses, leftBracket, rightBracket, leftCurly, rightCurly, colon, negate, semicolon, dotDotDot, endOfFile, cast_, null_, assert_, true_, false_, array, call, address, type, throw_, new_, delete_, star, symbolOffset, variable, dotVariable, dotIdentifier, dotTemplateInstance, dotType, slice, arrayLength, version_, module_, dollar, template_, dotTemplateDeclaration, declaration, typeof_, pragma_, dSymbol, typeid_, uadd, remove, newAnonymousClass, comment, arrayLiteral, assocArrayLiteral, structLiteral, classReference, thrownException, delegatePointer, delegateFunctionPointer, // Operators lessThan = 54, greaterThan, lessOrEqual, greaterOrEqual, equal, notEqual, identity, notIdentity, index, is_, leftShift = 64, rightShift, leftShiftAssign, rightShiftAssign, unsignedRightShift, unsignedRightShiftAssign, concatenate, concatenateAssign, // ~= concatenateElemAssign, concatenateDcharAssign, add, min, addAssign, minAssign, mul, div, mod, mulAssign, divAssign, modAssign, and, or, xor, andAssign, orAssign, xorAssign, assign, not, tilde, plusPlus, minusMinus, construct, blit, dot, arrow, comma, question, andAnd, orOr, prePlusPlus, preMinusMinus, // Numeric literals int32Literal = 105, uns32Literal, int64Literal, uns64Literal, int128Literal, uns128Literal, float32Literal, float64Literal, float80Literal, imaginary32Literal, imaginary64Literal, imaginary80Literal, // Char constants charLiteral = 117, wcharLiteral, dcharLiteral, // Leaf operators identifier = 120, string_, hexadecimalString, this_, super_, halt, tuple, error, // Basic types void_ = 128, int8, uns8, int16, uns16, int32, uns32, int64, uns64, int128, uns128, float32, float64, float80, imaginary32, imaginary64, imaginary80, complex32, complex64, complex80, char_, wchar_, dchar_, bool_, // Aggregates struct_ = 152, class_, interface_, union_, enum_, import_, alias_, override_, delegate_, function_, mixin_, align_, extern_, private_, protected_, public_, export_, static_, final_, const_, abstract_, debug_, deprecated_, in_, out_, inout_, lazy_, auto_, package_, manifest, immutable_, // Statements if_ = 183, else_, while_, for_, do_, switch_, case_, default_, break_, continue_, with_, synchronized_, return_, goto_, try_, catch_, finally_, asm_, foreach_, foreach_reverse_, scope_, onScopeExit, onScopeFailure, onScopeSuccess, // Contracts invariant_ = 207, // Testing unittest_, // Added after 1.0 argumentTypes, ref_, macro_, parameters = 212, traits, overloadSet, pure_, nothrow_, gshared, line, file, fileFullPath, moduleString, functionString, prettyFunction, shared_, at, pow, powAssign, goesTo, vector, pound, interval = 231, voidExpression, cantExpression, objcClassReference, max_, } // Assert that all token enum members have consecutive values and // that none of them overlap static assert(() { foreach (idx, enumName; __traits(allMembers, TOK)) { static if (idx != __traits(getMember, TOK, enumName)) { pragma(msg, "Error: Expected TOK.", enumName, " to be ", idx, " but is ", __traits(getMember, TOK, enumName)); static assert(0); } } return true; }()); /**************************************** */ private immutable TOK[] keywords = [ TOK.this_, TOK.super_, TOK.assert_, TOK.null_, TOK.true_, TOK.false_, TOK.cast_, TOK.new_, TOK.delete_, TOK.throw_, TOK.module_, TOK.pragma_, TOK.typeof_, TOK.typeid_, TOK.template_, TOK.void_, TOK.int8, TOK.uns8, TOK.int16, TOK.uns16, TOK.int32, TOK.uns32, TOK.int64, TOK.uns64, TOK.int128, TOK.uns128, TOK.float32, TOK.float64, TOK.float80, TOK.bool_, TOK.char_, TOK.wchar_, TOK.dchar_, TOK.imaginary32, TOK.imaginary64, TOK.imaginary80, TOK.complex32, TOK.complex64, TOK.complex80, TOK.delegate_, TOK.function_, TOK.is_, TOK.if_, TOK.else_, TOK.while_, TOK.for_, TOK.do_, TOK.switch_, TOK.case_, TOK.default_, TOK.break_, TOK.continue_, TOK.synchronized_, TOK.return_, TOK.goto_, TOK.try_, TOK.catch_, TOK.finally_, TOK.with_, TOK.asm_, TOK.foreach_, TOK.foreach_reverse_, TOK.scope_, TOK.struct_, TOK.class_, TOK.interface_, TOK.union_, TOK.enum_, TOK.import_, TOK.mixin_, TOK.static_, TOK.final_, TOK.const_, TOK.alias_, TOK.override_, TOK.abstract_, TOK.debug_, TOK.deprecated_, TOK.in_, TOK.out_, TOK.inout_, TOK.lazy_, TOK.auto_, TOK.align_, TOK.extern_, TOK.private_, TOK.package_, TOK.protected_, TOK.public_, TOK.export_, TOK.invariant_, TOK.unittest_, TOK.version_, TOK.argumentTypes, TOK.parameters, TOK.ref_, TOK.macro_, TOK.pure_, TOK.nothrow_, TOK.gshared, TOK.traits, TOK.vector, TOK.overloadSet, TOK.file, TOK.fileFullPath, TOK.line, TOK.moduleString, TOK.functionString, TOK.prettyFunction, TOK.shared_, TOK.immutable_, ]; /*********************************************************** */ extern (C++) struct Token { Token* next; Loc loc; const(char)* ptr; // pointer to first character of this token within buffer TOK value; const(char)* blockComment; // doc comment string prior to this token const(char)* lineComment; // doc comment for previous token union { // Integers sinteger_t intvalue; uinteger_t unsvalue; // Floats real_t floatvalue; struct { const(char)* ustring; // UTF8 string uint len; ubyte postfix; // 'c', 'w', 'd' } Identifier ident; } extern (D) private __gshared immutable string[TOK.max_] tochars = [ // Keywords TOK.this_: "this", TOK.super_: "super", TOK.assert_: "assert", TOK.null_: "null", TOK.true_: "true", TOK.false_: "false", TOK.cast_: "cast", TOK.new_: "new", TOK.delete_: "delete", TOK.throw_: "throw", TOK.module_: "module", TOK.pragma_: "pragma", TOK.typeof_: "typeof", TOK.typeid_: "typeid", TOK.template_: "template", TOK.void_: "void", TOK.int8: "byte", TOK.uns8: "ubyte", TOK.int16: "short", TOK.uns16: "ushort", TOK.int32: "int", TOK.uns32: "uint", TOK.int64: "long", TOK.uns64: "ulong", TOK.int128: "cent", TOK.uns128: "ucent", TOK.float32: "float", TOK.float64: "double", TOK.float80: "real", TOK.bool_: "bool", TOK.char_: "char", TOK.wchar_: "wchar", TOK.dchar_: "dchar", TOK.imaginary32: "ifloat", TOK.imaginary64: "idouble", TOK.imaginary80: "ireal", TOK.complex32: "cfloat", TOK.complex64: "cdouble", TOK.complex80: "creal", TOK.delegate_: "delegate", TOK.function_: "function", TOK.is_: "is", TOK.if_: "if", TOK.else_: "else", TOK.while_: "while", TOK.for_: "for", TOK.do_: "do", TOK.switch_: "switch", TOK.case_: "case", TOK.default_: "default", TOK.break_: "break", TOK.continue_: "continue", TOK.synchronized_: "synchronized", TOK.return_: "return", TOK.goto_: "goto", TOK.try_: "try", TOK.catch_: "catch", TOK.finally_: "finally", TOK.with_: "with", TOK.asm_: "asm", TOK.foreach_: "foreach", TOK.foreach_reverse_: "foreach_reverse", TOK.scope_: "scope", TOK.struct_: "struct", TOK.class_: "class", TOK.interface_: "interface", TOK.union_: "union", TOK.enum_: "enum", TOK.import_: "import", TOK.mixin_: "mixin", TOK.static_: "static", TOK.final_: "final", TOK.const_: "const", TOK.alias_: "alias", TOK.override_: "override", TOK.abstract_: "abstract", TOK.debug_: "debug", TOK.deprecated_: "deprecated", TOK.in_: "in", TOK.out_: "out", TOK.inout_: "inout", TOK.lazy_: "lazy", TOK.auto_: "auto", TOK.align_: "align", TOK.extern_: "extern", TOK.private_: "private", TOK.package_: "package", TOK.protected_: "protected", TOK.public_: "public", TOK.export_: "export", TOK.invariant_: "invariant", TOK.unittest_: "unittest", TOK.version_: "version", TOK.argumentTypes: "__argTypes", TOK.parameters: "__parameters", TOK.ref_: "ref", TOK.macro_: "macro", TOK.pure_: "pure", TOK.nothrow_: "nothrow", TOK.gshared: "__gshared", TOK.traits: "__traits", TOK.vector: "__vector", TOK.overloadSet: "__overloadset", TOK.file: "__FILE__", TOK.fileFullPath: "__FILE_FULL_PATH__", TOK.line: "__LINE__", TOK.moduleString: "__MODULE__", TOK.functionString: "__FUNCTION__", TOK.prettyFunction: "__PRETTY_FUNCTION__", TOK.shared_: "shared", TOK.immutable_: "immutable", TOK.endOfFile: "End of File", TOK.leftCurly: "{", TOK.rightCurly: "}", TOK.leftParentheses: "(", TOK.rightParentheses: ")", TOK.leftBracket: "[", TOK.rightBracket: "]", TOK.semicolon: ";", TOK.colon: ":", TOK.comma: ",", TOK.dot: ".", TOK.xor: "^", TOK.xorAssign: "^=", TOK.assign: "=", TOK.construct: "=", TOK.blit: "=", TOK.lessThan: "<", TOK.greaterThan: ">", TOK.lessOrEqual: "<=", TOK.greaterOrEqual: ">=", TOK.equal: "==", TOK.notEqual: "!=", TOK.not: "!", TOK.leftShift: "<<", TOK.rightShift: ">>", TOK.unsignedRightShift: ">>>", TOK.add: "+", TOK.min: "-", TOK.mul: "*", TOK.div: "/", TOK.mod: "%", TOK.slice: "..", TOK.dotDotDot: "...", TOK.and: "&", TOK.andAnd: "&&", TOK.or: "|", TOK.orOr: "||", TOK.array: "[]", TOK.index: "[i]", TOK.address: "&", TOK.star: "*", TOK.tilde: "~", TOK.dollar: "$", TOK.plusPlus: "++", TOK.minusMinus: "--", TOK.prePlusPlus: "++", TOK.preMinusMinus: "--", TOK.type: "type", TOK.question: "?", TOK.negate: "-", TOK.uadd: "+", TOK.variable: "var", TOK.addAssign: "+=", TOK.minAssign: "-=", TOK.mulAssign: "*=", TOK.divAssign: "/=", TOK.modAssign: "%=", TOK.leftShiftAssign: "<<=", TOK.rightShiftAssign: ">>=", TOK.unsignedRightShiftAssign: ">>>=", TOK.andAssign: "&=", TOK.orAssign: "|=", TOK.concatenateAssign: "~=", TOK.concatenateElemAssign: "~=", TOK.concatenateDcharAssign: "~=", TOK.concatenate: "~", TOK.call: "call", TOK.identity: "is", TOK.notIdentity: "!is", TOK.identifier: "identifier", TOK.at: "@", TOK.pow: "^^", TOK.powAssign: "^^=", TOK.goesTo: "=>", TOK.pound: "#", // For debugging TOK.error: "error", TOK.dotIdentifier: "dotid", TOK.dotTemplateDeclaration: "dottd", TOK.dotTemplateInstance: "dotti", TOK.dotVariable: "dotvar", TOK.dotType: "dottype", TOK.symbolOffset: "symoff", TOK.arrayLength: "arraylength", TOK.arrayLiteral: "arrayliteral", TOK.assocArrayLiteral: "assocarrayliteral", TOK.structLiteral: "structliteral", TOK.string_: "string", TOK.dSymbol: "symbol", TOK.tuple: "tuple", TOK.declaration: "declaration", TOK.onScopeExit: "scope(exit)", TOK.onScopeSuccess: "scope(success)", TOK.onScopeFailure: "scope(failure)", TOK.delegatePointer: "delegateptr", // Finish up TOK.reserved: "reserved", TOK.remove: "remove", TOK.newAnonymousClass: "newanonclass", TOK.comment: "comment", TOK.classReference: "classreference", TOK.thrownException: "thrownexception", TOK.delegateFunctionPointer: "delegatefuncptr", TOK.arrow: "arrow", TOK.int32Literal: "int32v", TOK.uns32Literal: "uns32v", TOK.int64Literal: "int64v", TOK.uns64Literal: "uns64v", TOK.int128Literal: "int128v", TOK.uns128Literal: "uns128v", TOK.float32Literal: "float32v", TOK.float64Literal: "float64v", TOK.float80Literal: "float80v", TOK.imaginary32Literal: "imaginary32v", TOK.imaginary64Literal: "imaginary64v", TOK.imaginary80Literal: "imaginary80v", TOK.charLiteral: "charv", TOK.wcharLiteral: "wcharv", TOK.dcharLiteral: "dcharv", TOK.halt: "halt", TOK.hexadecimalString: "xstring", TOK.manifest: "manifest", TOK.interval: "interval", TOK.voidExpression: "voidexp", TOK.cantExpression: "cantexp", TOK.objcClassReference: "class", ]; static assert(() { foreach (s; tochars) assert(s.length); return true; }()); shared static this() { Identifier.initTable(); foreach (kw; keywords) { //printf("keyword[%d] = '%s'\n",kw, tochars[kw].ptr); Identifier.idPool(tochars[kw].ptr, tochars[kw].length, cast(uint)kw); } } __gshared Token* freelist = null; static Token* alloc() { if (Token.freelist) { Token* t = freelist; freelist = t.next; t.next = null; return t; } return new Token(); } void free() { next = freelist; freelist = &this; } int isKeyword() const { foreach (kw; keywords) { if (kw == value) return 1; } return 0; } debug { void print() { fprintf(stderr, "%s\n", toChars()); } } /**** * Set to contents of ptr[0..length] * Params: * ptr = pointer to string * length = length of string */ final void setString(const(char)* ptr, size_t length) { auto s = cast(char*)mem.xmalloc(length + 1); memcpy(s, ptr, length); s[length] = 0; ustring = s; len = cast(uint)length; postfix = 0; } /**** * Set to contents of buf * Params: * buf = string (not zero terminated) */ final void setString(const ref OutBuffer buf) { setString(cast(const(char)*)buf.data, buf.offset); } /**** * Set to empty string */ final void setString() { ustring = ""; len = 0; postfix = 0; } extern (C++) const(char)* toChars() const { __gshared char[3 + 3 * floatvalue.sizeof + 1] buffer; const(char)* p = &buffer[0]; switch (value) { case TOK.int32Literal: sprintf(&buffer[0], "%d", cast(d_int32)intvalue); break; case TOK.uns32Literal: case TOK.charLiteral: case TOK.wcharLiteral: case TOK.dcharLiteral: sprintf(&buffer[0], "%uU", cast(d_uns32)unsvalue); break; case TOK.int64Literal: sprintf(&buffer[0], "%lldL", cast(long)intvalue); break; case TOK.uns64Literal: sprintf(&buffer[0], "%lluUL", cast(ulong)unsvalue); break; case TOK.float32Literal: CTFloat.sprint(&buffer[0], 'g', floatvalue); strcat(&buffer[0], "f"); break; case TOK.float64Literal: CTFloat.sprint(&buffer[0], 'g', floatvalue); break; case TOK.float80Literal: CTFloat.sprint(&buffer[0], 'g', floatvalue); strcat(&buffer[0], "L"); break; case TOK.imaginary32Literal: CTFloat.sprint(&buffer[0], 'g', floatvalue); strcat(&buffer[0], "fi"); break; case TOK.imaginary64Literal: CTFloat.sprint(&buffer[0], 'g', floatvalue); strcat(&buffer[0], "i"); break; case TOK.imaginary80Literal: CTFloat.sprint(&buffer[0], 'g', floatvalue); strcat(&buffer[0], "Li"); break; case TOK.string_: { OutBuffer buf; buf.writeByte('"'); for (size_t i = 0; i < len;) { dchar c; utf_decodeChar(ustring, len, i, c); switch (c) { case 0: break; case '"': case '\\': buf.writeByte('\\'); goto default; default: if (c <= 0x7F) { if (isprint(c)) buf.writeByte(c); else buf.printf("\\x%02x", c); } else if (c <= 0xFFFF) buf.printf("\\u%04x", c); else buf.printf("\\U%08x", c); continue; } break; } buf.writeByte('"'); if (postfix) buf.writeByte(postfix); p = buf.extractString(); } break; case TOK.hexadecimalString: { OutBuffer buf; buf.writeByte('x'); buf.writeByte('"'); foreach (size_t i; 0 .. len) { if (i) buf.writeByte(' '); buf.printf("%02x", ustring[i]); } buf.writeByte('"'); if (postfix) buf.writeByte(postfix); buf.writeByte(0); p = buf.extractData(); break; } case TOK.identifier: case TOK.enum_: case TOK.struct_: case TOK.import_: case TOK.wchar_: case TOK.dchar_: case TOK.bool_: case TOK.char_: case TOK.int8: case TOK.uns8: case TOK.int16: case TOK.uns16: case TOK.int32: case TOK.uns32: case TOK.int64: case TOK.uns64: case TOK.int128: case TOK.uns128: case TOK.float32: case TOK.float64: case TOK.float80: case TOK.imaginary32: case TOK.imaginary64: case TOK.imaginary80: case TOK.complex32: case TOK.complex64: case TOK.complex80: case TOK.void_: p = ident.toChars(); break; default: p = toChars(value); break; } return p; } static const(char)* toChars(TOK value) { return toString(value).ptr; } extern (D) static string toString(TOK value) pure nothrow @nogc @safe { return tochars[value]; } }
D
import std.stdio, std.array, std.string, std.conv, std.algorithm; import std.typecons, std.range, std.random, std.math, std.container; import std.numeric, std.bigint, core.bitop, core.stdc.stdio; int gaussianElimination(ref real[][] org_mat, ref real[] ret) { int N = org_mat.length.to!int; auto mat = new real[][](N, N+1); foreach (i; 0..N) foreach (j; 0..N+1) mat[i][j] = org_mat[i][j]; foreach (i; 0..N) { real maxval = 0; int maxrow = -1; foreach (j; i..N) if (abs(mat[j][i]) > maxval) maxval = abs(mat[j][i]), maxrow = j; if (maxval == 0) return -1; swap(mat[i], mat[maxrow]); foreach (j; i+1..N+1) mat[i][j] /= mat[i][i]; mat[i][i] = 1; foreach (j; 0..N) { if (j == i) continue; real mul = mat[j][i]; foreach (k; i..N+1) mat[j][k] -= mul*mat[i][k]; } } foreach (i; 0..N) ret[i] = mat[i][N]; return 0; } void main() { real[6] E = [1.0000000000000000, 1.0833333333333333, 1.2569444444444444, 1.5353009259259260, 1.6915991512345676, 2.0513639724794235]; auto mat = new real[][](6, 7); foreach (i; 0..6) foreach(j; 0..7) mat[i][j] = 0; foreach (i; 0..6) { foreach (j; 1..7) { if (j >= i + 1) mat[i][j-1] += 1; else mat[i][j-1] += E[i-j]+1; } mat[i][6] = E[i]; } auto P = new real[](6); gaussianElimination(mat, P); auto T = readln.chomp.to!int; while (T--) { auto N = readln.chomp.to!int; auto dp = new real[](N+1); foreach (i; 0..N+1) dp[i] = 0; foreach (i; iota(N-1, -1, -1)) { foreach (j; 1..7) { if (i + j >= N) dp[i] += P[j-1]; else dp[i] += P[j-1] * (dp[i+j] + 1); } } writefln("%.10f", dp[0]); } }
D
/** Uses libasync Copyright: © 2014 RejectedSoftware e.K., GlobecSys Inc Authors: Sönke Ludwig, Etienne Cimon License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. */ module vibe.core.drivers.libasync; version(VibeLibasyncDriver): import vibe.core.core; import vibe.core.driver; import vibe.core.drivers.threadedfile; import vibe.core.drivers.timerqueue; import vibe.core.log; import vibe.utils.array : FixedRingBuffer; import libasync : AsyncDirectoryWatcher, AsyncDNS, AsyncFile, AsyncSignal, AsyncTimer, AsyncTCPConnection, AsyncTCPListener, AsyncUDPSocket, DWFileEvent, DWChangeInfo, EventLoop, NetworkAddressLA = NetworkAddress, UDPEvent, TCPEvent, TCPOption, fd_t, getThreadEventLoop; import libasync.internals.memory; import libasync.types : Status; import std.algorithm : min, max; import std.array; import std.container : Array; import std.conv; import std.datetime; import std.encoding; import std.exception; import std.string; import std.stdio : File; import std.typecons; import core.atomic; import core.memory; import core.thread; import core.sync.mutex; import core.stdc.stdio; import core.sys.posix.netinet.in_; version (Posix) import core.sys.posix.sys.socket; version (Windows) import core.sys.windows.winsock2; private __gshared EventLoop gs_evLoop; private EventLoop s_evLoop; private DriverCore s_driverCore; private shared int s_refCount; // will destroy async threads when 0 version(Windows) extern(C) { FILE* _wfopen(const(wchar)* filename, in wchar* mode); int _wchmod(in wchar*, int); } EventLoop getMainEventLoop() @trusted nothrow { if (s_evLoop is null) return gs_evLoop; return s_evLoop; } DriverCore getDriverCore() @safe nothrow { assert(s_driverCore !is null); return s_driverCore; } private struct TimerInfo { size_t refCount = 1; void delegate() callback; Task owner; this(void delegate() callback) { this.callback = callback; } } /// one per thread final class LibasyncDriver : EventDriver { @trusted: private { bool m_break = false; debug Thread m_ownerThread; AsyncTimer m_timerEvent; TimerQueue!TimerInfo m_timers; SysTime m_nextSched = SysTime.max; shared AsyncSignal m_exitSignal; } this(DriverCore core) nothrow { assert(!isControlThread, "Libasync driver created in control thread"); try { import core.atomic : atomicOp; s_refCount.atomicOp!"+="(1); if (!gs_mutex) { import core.sync.mutex; gs_mutex = new core.sync.mutex.Mutex; gs_availID.reserve(32); foreach (i; gs_availID.length .. gs_availID.capacity) { gs_availID.insertBack(i + 1); } gs_maxID = 32; } } catch (Throwable) { assert(false, "Couldn't reserve necessary space for available Manual Events"); } debug m_ownerThread = Thread.getThis(); s_driverCore = core; s_evLoop = getThreadEventLoop(); if (!gs_evLoop) gs_evLoop = s_evLoop; m_exitSignal = new shared AsyncSignal(getMainEventLoop()); m_exitSignal.run({ m_break = true; }); logTrace("Loaded libasync backend in thread %s", Thread.getThis().name); } static @property bool isControlThread() nothrow { scope(failure) assert(false); return Thread.getThis().isDaemon && Thread.getThis().name == "CmdProcessor"; } override void dispose() { logTrace("Deleting event driver"); m_break = true; getMainEventLoop().exit(); if (s_refCount.atomicOp!"-="(1) == 0) { import libasync.threads : destroyAsyncThreads; destroyAsyncThreads(); } } override int runEventLoop() { while(!m_break && getMainEventLoop().loop(int.max.msecs)){ processTimers(); getDriverCore().notifyIdle(); } m_break = false; logDebug("Event loop exit %d", m_break); return 0; } override int runEventLoopOnce() { getMainEventLoop().loop(int.max.msecs); processTimers(); getDriverCore().notifyIdle(); logTrace("runEventLoopOnce exit"); return 0; } override bool processEvents() { getMainEventLoop().loop(0.seconds); processTimers(); if (m_break) { m_break = false; return false; } return true; } override void exitEventLoop() { logDebug("Exiting (%s)", m_break); m_exitSignal.trigger(); } override LibasyncFileStream openFile(Path path, FileMode mode) { return new LibasyncFileStream(path, mode); } override DirectoryWatcher watchDirectory(Path path, bool recursive) { return new LibasyncDirectoryWatcher(path, recursive); } /** Resolves the given host name or IP address string. */ override NetworkAddress resolveHost(string host, ushort family = 2, bool use_dns = true) { import libasync.types : isIPv6; isIPv6 is_ipv6; if (family == AF_INET6) is_ipv6 = isIPv6.yes; else is_ipv6 = isIPv6.no; import std.regex : regex, Captures, Regex, matchFirst, ctRegex; import std.traits : ReturnType; auto IPv4Regex = ctRegex!(`^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}$`, ``); auto IPv6Regex = ctRegex!(`^([0-9A-Fa-f]{0,4}:){2,7}([0-9A-Fa-f]{1,4}$|((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4})$`, ``); auto ipv4 = matchFirst(host, IPv4Regex); auto ipv6 = matchFirst(host, IPv6Regex); if (!ipv4.empty) { if (!ipv4.empty) is_ipv6 = isIPv6.no; use_dns = false; } else if (!ipv6.empty) { // fixme: match host instead? is_ipv6 = isIPv6.yes; use_dns = false; } else { use_dns = true; } NetworkAddress ret; if (use_dns) { bool done; struct DNSCallback { Task waiter; NetworkAddress* address; bool* finished; void handler(NetworkAddressLA addr) { *address = NetworkAddress(addr); *finished = true; if (waiter != Task() && waiter != Task.getThis()) getDriverCore().resumeTask(waiter); } } DNSCallback* cb = FreeListObjectAlloc!DNSCallback.alloc(); cb.waiter = Task.getThis(); cb.address = &ret; cb.finished = &done; // todo: remove the shared attribute to avoid GC? shared AsyncDNS dns = new shared AsyncDNS(getMainEventLoop()); scope(exit) dns.destroy(); bool success = dns.handler(&cb.handler).resolveHost(host, is_ipv6); if (!success || dns.status.code != Status.OK) throw new Exception(dns.status.text); while(!done) getDriverCore.yieldForEvent(); if (dns.status.code != Status.OK) throw new Exception(dns.status.text); assert(ret != NetworkAddress.init); assert(ret.family != 0); logTrace("Async resolved address %s", ret.toString()); FreeListObjectAlloc!DNSCallback.free(cb); if (ret.family == 0) ret.family = family; return ret; } else { ret = NetworkAddress(getMainEventLoop().resolveIP(host, 0, is_ipv6)); if (ret.family == 0) ret.family = family; return ret; } } override LibasyncTCPConnection connectTCP(NetworkAddress addr, NetworkAddress bind_addr) { AsyncTCPConnection conn = new AsyncTCPConnection(getMainEventLoop()); LibasyncTCPConnection tcp_connection = new LibasyncTCPConnection(conn, (TCPConnection conn) { Task waiter = (cast(LibasyncTCPConnection) conn).m_settings.writer.task; if (waiter != Task()) { getDriverCore().resumeTask(waiter); } }); if (Task.getThis() != Task()) tcp_connection.m_settings.writer.acquire(); tcp_connection.m_tcpImpl.conn = conn; //conn.local = bind_addr; conn.ip(bind_addr.toAddressString(), bind_addr.port); conn.peer = cast(NetworkAddressLA)addr; enforce(conn.run(&tcp_connection.handler), "An error occured while starting a new connection: " ~ conn.error); while (!tcp_connection.connected && !tcp_connection.m_error) getDriverCore().yieldForEvent(); enforce(!tcp_connection.m_error, tcp_connection.m_error); tcp_connection.m_tcpImpl.localAddr = NetworkAddress(conn.local); if (Task.getThis() != Task()) tcp_connection.m_settings.writer.release(); return tcp_connection; } override LibasyncTCPListener listenTCP(ushort port, void delegate(TCPConnection conn) @safe conn_callback, string address, TCPListenOptions options) { NetworkAddress localaddr = getEventDriver().resolveHost(address); localaddr.port = port; return new LibasyncTCPListener(localaddr, conn_callback, options); } override LibasyncUDPConnection listenUDP(ushort port, string bind_address = "0.0.0.0") { NetworkAddress localaddr = getEventDriver().resolveHost(bind_address); localaddr.port = port; AsyncUDPSocket sock = new AsyncUDPSocket(getMainEventLoop()); sock.local = cast(NetworkAddressLA)localaddr; auto udp_connection = new LibasyncUDPConnection(sock); sock.run(&udp_connection.handler); return udp_connection; } override LibasyncManualEvent createManualEvent() { return new LibasyncManualEvent(this); } override FileDescriptorEvent createFileDescriptorEvent(int file_descriptor, FileDescriptorEvent.Trigger triggers, FileDescriptorEvent.Mode mode) { assert(false); } // The following timer implementation was adapted from the equivalent in libevent2.d override size_t createTimer(void delegate() @safe callback) { return m_timers.create(TimerInfo(callback)); } override void acquireTimer(size_t timer_id) { m_timers.getUserData(timer_id).refCount++; } override void releaseTimer(size_t timer_id) nothrow { debug assert(m_ownerThread is Thread.getThis()); logTrace("Releasing timer %s", timer_id); if (!--m_timers.getUserData(timer_id).refCount) m_timers.destroy(timer_id); } override bool isTimerPending(size_t timer_id) nothrow { return m_timers.isPending(timer_id); } override void rearmTimer(size_t timer_id, Duration dur, bool periodic) { debug assert(m_ownerThread is Thread.getThis()); if (!isTimerPending(timer_id)) acquireTimer(timer_id); m_timers.schedule(timer_id, dur, periodic); rescheduleTimerEvent(Clock.currTime(UTC())); } override void stopTimer(size_t timer_id) { logTrace("Stopping timer %s", timer_id); if (m_timers.isPending(timer_id)) { m_timers.unschedule(timer_id); releaseTimer(timer_id); } } override void waitTimer(size_t timer_id) { logTrace("Waiting for timer in %s", Task.getThis()); debug assert(m_ownerThread is Thread.getThis()); while (true) { assert(!m_timers.isPeriodic(timer_id), "Cannot wait for a periodic timer."); if (!m_timers.isPending(timer_id)) { // logTrace("Timer is not pending"); return; } auto data = &m_timers.getUserData(timer_id); assert(data.owner == Task.init, "Waiting for the same timer from multiple tasks is not supported."); data.owner = Task.getThis(); scope (exit) m_timers.getUserData(timer_id).owner = Task.init; getDriverCore().yieldForEvent(); } } /// If the timer has an owner, it will resume the task. /// if the timer has a callback, it will run a new task. private void processTimers() { if (!m_timers.anyPending) return; logTrace("Processing due timers"); // process all timers that have expired up to now auto now = Clock.currTime(UTC()); // event loop timer will need to be rescheduled because we'll process everything until now m_nextSched = SysTime.max; m_timers.consumeTimeouts(now, (timer, periodic, ref data) { Task owner = data.owner; auto callback = data.callback; logTrace("Timer %s fired (%s/%s)", timer, owner != Task.init, callback !is null); if (!periodic) releaseTimer(timer); if (owner && owner.running && owner != Task.getThis()) { if (Task.getThis == Task.init) getDriverCore().resumeTask(owner); else getDriverCore().yieldAndResumeTask(owner); } if (callback) runTask(callback); }); rescheduleTimerEvent(now); } private void rescheduleTimerEvent(SysTime now) { logTrace("Rescheduling timer event %s", Task.getThis()); // don't bother scheduling, the timers will be processed before leaving for the event loop if (m_nextSched <= Clock.currTime(UTC())) return; bool first; auto next = m_timers.getFirstTimeout(); Duration dur; if (next == SysTime.max) return; dur = max(1.msecs, next - now); if (m_nextSched != next) m_nextSched = next; else return; if (dur.total!"seconds"() >= int.max) return; // will never trigger, don't bother if (!m_timerEvent) { //logTrace("creating new async timer"); m_timerEvent = new AsyncTimer(getMainEventLoop()); bool success = m_timerEvent.duration(dur).run(&onTimerTimeout); assert(success, "Failed to run timer"); } else { //logTrace("rearming the same timer instance"); bool success = m_timerEvent.rearm(dur); assert(success, "Failed to rearm timer"); } //logTrace("Rescheduled timer event for %s seconds in thread '%s' :: task '%s'", dur.total!"usecs" * 1e-6, Thread.getThis().name, Task.getThis()); } private void onTimerTimeout() { import std.encoding : sanitize; logTrace("timer event fired"); try processTimers(); catch (Exception e) { logError("Failed to process timers: %s", e.msg); try logDiagnostic("Full error: %s", e.toString().sanitize); catch (Throwable) {} } } } /// Writes or reads asynchronously (in another thread) for sizes > 64kb to benefit from kernel page cache /// in lower size operations. final class LibasyncFileStream : FileStream { @trusted: import vibe.inet.path : Path; private { Path m_path; ulong m_size; ulong m_offset = 0; FileMode m_mode; Task m_task; Exception m_ex; shared AsyncFile m_impl; bool m_started; bool m_truncated; bool m_finished; } this(Path path, FileMode mode) { import std.file : getSize,exists; if (mode != FileMode.createTrunc) m_size = getSize(path.toNativeString()); else { auto path_str = path.toNativeString(); if (exists(path_str)) removeFile(path); { // touch import std.string : toStringz; version(Windows) { import std.utf : toUTF16z; auto path_str_utf = path_str.toUTF16z(); FILE* f = _wfopen(path_str_utf, "w"); _wchmod(path_str_utf, S_IREAD|S_IWRITE); } else FILE * f = fopen(path_str.toStringz, "w"); fclose(f); m_truncated = true; } } m_path = path; m_mode = mode; m_impl = new shared AsyncFile(getMainEventLoop()); m_impl.onReady(&handler); m_started = true; } ~this() { try close(); catch (Exception e) { assert(false, e.msg); } } override @property Path path() const { return m_path; } override @property bool isOpen() const { return m_started; } override @property ulong size() const { return m_size; } override @property bool readable() const { return m_mode != FileMode.append; } override @property bool writable() const { return m_mode != FileMode.read; } override void seek(ulong offset) { m_offset = offset; } override ulong tell() { return m_offset; } override void close() { if (m_impl) { m_impl.kill(); m_impl = null; } m_started = false; if (m_task != Task() && Task.getThis() != Task()) getDriverCore().yieldAndResumeTask(m_task, new Exception("The file was closed during an operation")); else if (m_task != Task() && Task.getThis() == Task()) getDriverCore().resumeTask(m_task, new Exception("The file was closed during an operation")); } override @property bool empty() const { assert(this.readable); return m_offset >= m_size; } override @property ulong leastSize() const { assert(this.readable); return m_size - m_offset; } override @property bool dataAvailableForRead() { return true; } override const(ubyte)[] peek() { return null; } override size_t read(scope ubyte[] dst, IOMode) { scope(failure) close(); assert(this.readable, "To read a file, it must be opened in a read-enabled mode."); shared ubyte[] bytes = cast(shared) dst; bool truncate_if_exists; if (!m_truncated && m_mode == FileMode.createTrunc) { truncate_if_exists = true; m_truncated = true; m_size = 0; } m_finished = false; enforce(dst.length <= leastSize); enforce(m_impl.read(m_path.toNativeString(), bytes, m_offset, true, truncate_if_exists), "Failed to read data from disk: " ~ m_impl.error); if (!m_finished) { acquire(); scope(exit) release(); getDriverCore().yieldForEvent(); } m_finished = false; if (m_ex) throw m_ex; m_offset += dst.length; assert(m_impl.offset == m_offset, "Incoherent offset returned from file reader: " ~ m_offset.to!string ~ "B assumed but the implementation is at: " ~ m_impl.offset.to!string ~ "B"); return dst.length; } alias Stream.write write; override size_t write(in ubyte[] bytes_, IOMode) { assert(this.writable, "To write to a file, it must be opened in a write-enabled mode."); shared const(ubyte)[] bytes = cast(shared const(ubyte)[]) bytes_; bool truncate_if_exists; if (!m_truncated && m_mode == FileMode.createTrunc) { truncate_if_exists = true; m_truncated = true; m_size = 0; } m_finished = false; if (m_mode == FileMode.append) enforce(m_impl.append(m_path.toNativeString(), cast(shared ubyte[]) bytes, true, truncate_if_exists), "Failed to write data to disk: " ~ m_impl.error); else enforce(m_impl.write(m_path.toNativeString(), bytes, m_offset, true, truncate_if_exists), "Failed to write data to disk: " ~ m_impl.error); if (!m_finished) { acquire(); scope(exit) release(); getDriverCore().yieldForEvent(); } m_finished = false; if (m_ex) throw m_ex; if (m_mode == FileMode.append) { m_size += bytes.length; } else { m_offset += bytes.length; if (m_offset >= m_size) m_size += m_offset - m_size; assert(m_impl.offset == m_offset, "Incoherent offset returned from file writer."); } //assert(getSize(m_path.toNativeString()) == m_size, "Incoherency between local size and filesize: " ~ m_size.to!string ~ "B assumed for a file of size " ~ getSize(m_path.toNativeString()).to!string ~ "B"); return bytes_.length; } override void flush() { assert(this.writable, "To write to a file, it must be opened in a write-enabled mode."); } override void finalize() { if (this.writable) flush(); } void release() { assert(Task.getThis() == Task() || m_task == Task.getThis(), "Releasing FileStream that is not owned by the calling task."); m_task = Task(); } void acquire() { assert(Task.getThis() == Task() || m_task == Task(), "Acquiring FileStream that is already owned."); m_task = Task.getThis(); } private void handler() { // This may be called by the event loop if read/write > 64kb and another thread was delegated Exception ex; if (m_impl.status.code != Status.OK) ex = new Exception(m_impl.error); m_finished = true; if (m_task != Task()) getDriverCore().resumeTask(m_task, ex); else m_ex = ex; } } final class LibasyncDirectoryWatcher : DirectoryWatcher { @trusted: private { Path m_path; bool m_recursive; Task m_task; AsyncDirectoryWatcher m_impl; Array!DirectoryChange m_changes; Exception m_error; } this(Path path, bool recursive) { m_impl = new AsyncDirectoryWatcher(getMainEventLoop()); m_impl.run(&handler); m_path = path; m_recursive = recursive; watch(path, recursive); // logTrace("DirectoryWatcher called with: %s", path.toNativeString()); } ~this() { m_impl.kill(); } override @property Path path() const { return m_path; } override @property bool recursive() const { return m_recursive; } void release() { assert(m_task == Task.getThis(), "Releasing FileStream that is not owned by the calling task."); m_task = Task(); } void acquire() { assert(m_task == Task(), "Acquiring FileStream that is already owned."); m_task = Task.getThis(); } bool amOwner() { return m_task == Task.getThis(); } override bool readChanges(ref DirectoryChange[] dst, Duration timeout) { dst.length = 0; assert(!amOwner()); if (m_error) throw m_error; acquire(); scope(exit) release(); void consumeChanges() { if (m_impl.status.code == Status.ERROR) { throw new Exception(m_impl.error); } foreach (ref change; m_changes[]) { //logTrace("Adding change: %s", change.to!string); dst ~= change; } //logTrace("Consumed change 1: %s", dst.to!string); import std.array : array; import std.algorithm : uniq; dst = cast(DirectoryChange[]) uniq!((a, b) => a.path == b.path && a.type == b.type)(dst).array; logTrace("Consumed change: %s", dst.to!string); m_changes.clear(); } if (!m_changes.empty) { consumeChanges(); return true; } auto tm = getEventDriver().createTimer(null); getEventDriver().m_timers.getUserData(tm).owner = Task.getThis(); getEventDriver().rearmTimer(tm, timeout, false); while (m_changes.empty) { getDriverCore().yieldForEvent(); if (!getEventDriver().isTimerPending(tm)) break; } if (!m_changes.empty) { consumeChanges(); return true; } return false; } private void watch(Path path, bool recursive) { m_impl.watchDir(path.toNativeString(), DWFileEvent.ALL, recursive); } private void handler() { import std.stdio; DWChangeInfo[] changes = allocArray!DWChangeInfo(manualAllocator(), 128); scope(exit) freeArray(manualAllocator(), changes); Exception ex; try { uint cnt; do { cnt = m_impl.readChanges(changes); size_t i; foreach (DWChangeInfo change; changes) { DirectoryChange dc; final switch (change.event){ case DWFileEvent.CREATED: dc.type = DirectoryChangeType.added; break; case DWFileEvent.DELETED: dc.type = DirectoryChangeType.removed; break; case DWFileEvent.MODIFIED: dc.type = DirectoryChangeType.modified; break; case DWFileEvent.MOVED_FROM: dc.type = DirectoryChangeType.removed; break; case DWFileEvent.MOVED_TO: dc.type = DirectoryChangeType.added; break; case DWFileEvent.ALL: break; // impossible case DWFileEvent.ERROR: throw new Exception(m_impl.error); } dc.path = Path(change.path); //logTrace("Inserted %s absolute %s", dc.to!string, dc.path.absolute.to!string); m_changes.insert(dc); i++; if (cnt == i) break; } } while(cnt == 0 && m_impl.status.code == Status.OK); if (m_impl.status.code == Status.ERROR) { ex = new Exception(m_impl.error); } } catch (Exception e) { ex = e; } if (m_task != Task()) getDriverCore().resumeTask(m_task, ex); else m_error = ex; } } final class LibasyncManualEvent : ManualEvent { @trusted: private { shared(int) m_emitCount = 0; shared(int) m_threadCount = 0; shared(size_t) m_instance; Array!(void*) ms_signals; core.sync.mutex.Mutex m_mutex; @property size_t instanceID() nothrow { return atomicLoad(m_instance); } @property void instanceID(size_t instance) nothrow{ atomicStore(m_instance, instance); } } this(LibasyncDriver driver) nothrow { m_mutex = new core.sync.mutex.Mutex; instanceID = generateID(); } ~this() { try { recycleID(instanceID); foreach (ref signal; ms_signals[]) { if (signal) { (cast(shared AsyncSignal) signal).kill(); signal = null; } } } catch (Exception e) { import std.stdio; writefln("Exception thrown while finalizing LibasyncManualEvent: %s", e.msg); } } override void emit() { scope (failure) assert(false); // synchronized is not nothrow on DMD 2.066 and below and Array is not nothrow at all logTrace("Emitting signal"); atomicOp!"+="(m_emitCount, 1); synchronized (m_mutex) { logTrace("Looping signals. found: " ~ ms_signals.length.to!string); foreach (ref signal; ms_signals[]) { auto evloop = getMainEventLoop(); shared AsyncSignal sig = cast(shared AsyncSignal) signal; if (!sig.trigger(evloop)) logError("Failed to trigger ManualEvent: %s", sig.error); } } } override void wait() { wait(m_emitCount); } override int wait(int reference_emit_count) { return doWait!true(reference_emit_count); } override int wait(Duration timeout, int reference_emit_count) { return doWait!true(timeout, reference_emit_count); } override int waitUninterruptible(int reference_emit_count) { return doWait!false(reference_emit_count); } override int waitUninterruptible(Duration timeout, int reference_emit_count) { return doWait!false(timeout, reference_emit_count); } void acquire() { auto task = Task.getThis(); bool signal_exists; size_t instance = instanceID; if (s_eventWaiters.length <= instance) expandWaiters(); logTrace("Acquire event ID#%d", instance); auto taskList = s_eventWaiters[instance]; if (taskList.length > 0) signal_exists = true; if (!signal_exists) { shared AsyncSignal sig = new shared AsyncSignal(getMainEventLoop()); sig.run(&onSignal); synchronized (m_mutex) ms_signals.insertBack(cast(void*)sig); } s_eventWaiters[instance].insertBack(Task.getThis()); } void release() { assert(amOwner(), "Releasing non-acquired signal."); import std.algorithm : countUntil; size_t instance = instanceID; auto taskList = s_eventWaiters[instance]; auto idx = taskList[].countUntil!((a, b) => a == b)(Task.getThis()); logTrace("Release event ID#%d", instance); s_eventWaiters[instance].linearRemove(taskList[idx .. idx+1]); if (s_eventWaiters[instance].empty) { removeMySignal(); } } bool amOwner() { import std.algorithm : countUntil; size_t instance = instanceID; if (s_eventWaiters.length <= instance) return false; auto taskList = s_eventWaiters[instance]; if (taskList.length == 0) return false; auto idx = taskList[].countUntil!((a, b) => a == b)(Task.getThis()); return idx != -1; } override @property int emitCount() const { return atomicLoad(m_emitCount); } private int doWait(bool INTERRUPTIBLE)(int reference_emit_count) { try { assert(!amOwner()); acquire(); scope(exit) release(); auto ec = this.emitCount; while( ec == reference_emit_count ){ //synchronized(m_mutex) logTrace("Waiting for event with signal count: " ~ ms_signals.length.to!string); static if (INTERRUPTIBLE) getDriverCore().yieldForEvent(); else getDriverCore().yieldForEventDeferThrow(); ec = this.emitCount; } return ec; } catch (Exception e) { static if (!INTERRUPTIBLE) assert(false, e.msg); // still some function calls not marked nothrow else throw e; } } private int doWait(bool INTERRUPTIBLE)(Duration timeout, int reference_emit_count) { static if (!INTERRUPTIBLE) scope (failure) assert(false); // still some function calls not marked nothrow assert(!amOwner()); acquire(); scope(exit) release(); auto tm = getEventDriver().createTimer(null); scope (exit) getEventDriver().releaseTimer(tm); getEventDriver().m_timers.getUserData(tm).owner = Task.getThis(); getEventDriver().rearmTimer(tm, timeout, false); auto ec = this.emitCount; while (ec == reference_emit_count) { static if (INTERRUPTIBLE) getDriverCore().yieldForEvent(); else getDriverCore().yieldForEventDeferThrow(); ec = this.emitCount; if (!getEventDriver().isTimerPending(tm)) break; } return ec; } private void removeMySignal() { import std.algorithm : countUntil; synchronized(m_mutex) { auto idx = ms_signals[].countUntil!((void* a, LibasyncManualEvent b) { return ((cast(shared AsyncSignal) a).owner == Thread.getThis() && this is b);})(this); ms_signals.linearRemove(ms_signals[idx .. idx+1]); } } private void expandWaiters() { size_t maxID; synchronized(gs_mutex) maxID = gs_maxID; s_eventWaiters.reserve(maxID); logTrace("gs_maxID: %d", maxID); size_t s_ev_len = s_eventWaiters.length; size_t s_ev_cap = s_eventWaiters.capacity; assert(maxID > s_eventWaiters.length); foreach (i; s_ev_len .. s_ev_cap) { s_eventWaiters.insertBack(Array!Task.init); } } private void onSignal() { logTrace("Got signal in onSignal"); try { auto thread = Thread.getThis(); auto core = getDriverCore(); size_t instance = instanceID; logTrace("Got context: %d", instance); foreach (Task task; s_eventWaiters[instance][]) { logTrace("Task Found"); core.resumeTask(task); } } catch (Exception e) { logError("Exception while handling signal event: %s", e.msg); try logDebug("Full error: %s", sanitize(e.msg)); catch (Exception) {} } } } final class LibasyncTCPListener : TCPListener { @trusted: private { NetworkAddress m_local; void delegate(TCPConnection conn) @safe m_connectionCallback; TCPListenOptions m_options; AsyncTCPListener[] m_listeners; fd_t socket; } this(NetworkAddress addr, void delegate(TCPConnection conn) @safe connection_callback, TCPListenOptions options) { m_connectionCallback = connection_callback; m_options = options; m_local = addr; void function(shared LibasyncTCPListener) init = (shared LibasyncTCPListener ctxt){ synchronized(ctxt) { LibasyncTCPListener ctxt2 = cast(LibasyncTCPListener)ctxt; AsyncTCPListener listener = new AsyncTCPListener(getMainEventLoop(), ctxt2.socket); listener.local = cast(NetworkAddressLA)ctxt2.m_local; enforce(listener.run(&ctxt2.initConnection), "Failed to start listening to local socket: " ~ listener.error); ctxt2.socket = listener.socket; ctxt2.m_listeners ~= listener; } }; if (options & TCPListenOptions.distribute) runWorkerTaskDist(init, cast(shared) this); else init(cast(shared) this); } override @property NetworkAddress bindAddress() { return m_local; } @property void delegate(TCPConnection) connectionCallback() { return m_connectionCallback; } private void delegate(TCPEvent) initConnection(AsyncTCPConnection conn) { logTrace("Connection initialized in thread: " ~ Thread.getThis().name); LibasyncTCPConnection native_conn = new LibasyncTCPConnection(conn, m_connectionCallback); native_conn.m_tcpImpl.conn = conn; native_conn.m_tcpImpl.localAddr = m_local; return &native_conn.handler; } override void stopListening() { synchronized(this) { foreach (listener; m_listeners) { listener.kill(); listener = null; } } } } final class LibasyncTCPConnection : TCPConnection/*, Buffered*/ { @trusted: private { FixedRingBuffer!ubyte m_readBuffer; ubyte[] m_buffer; ubyte[] m_slice; TCPConnectionImpl m_tcpImpl; Settings m_settings; bool m_closed = true; bool m_mustRecv = true; string m_error; // The socket descriptor is unavailable to motivate low-level/API feature additions // rather than high-lvl platform-dependent hacking // fd_t socket; } ubyte[] readChunk(ubyte[] buffer = null) { logTrace("readBuf TCP: %d", buffer.length); import std.algorithm : swap; ubyte[] ret; if (m_slice.length > 0) { swap(ret, m_slice); logTrace("readBuf returned instantly with slice length: %d", ret.length); return ret; } if (m_readBuffer.length > 0) { size_t amt = min(buffer.length, m_readBuffer.length); m_readBuffer.read(buffer[0 .. amt]); logTrace("readBuf returned with existing amount: %d", amt); return buffer[0 .. amt]; } if (buffer) { m_buffer = buffer; m_readBuffer.dispose(); } leastSize(); swap(ret, m_slice); logTrace("readBuf returned with buffered length: %d", ret.length); return ret; } this(AsyncTCPConnection conn, void delegate(TCPConnection) @safe cb) in { assert(conn !is null); } body { m_settings.onConnect = cb; m_readBuffer.capacity = 64*1024; } private @property AsyncTCPConnection conn() { return m_tcpImpl.conn; } // Using this setting completely disables the internal buffers as well override @property void tcpNoDelay(bool enabled) { m_settings.tcpNoDelay = enabled; conn.setOption(TCPOption.NODELAY, enabled); } override @property bool tcpNoDelay() const { return m_settings.tcpNoDelay; } override @property void readTimeout(Duration dur) { m_settings.readTimeout = dur; conn.setOption(TCPOption.TIMEOUT_RECV, dur); } override @property Duration readTimeout() const { return m_settings.readTimeout; } override @property void keepAlive(bool enabled) { m_settings.keepAlive = enabled; conn.setOption(TCPOption.KEEPALIVE_ENABLE, enabled); } override @property bool keepAlive() const { return m_settings.keepAlive; } override @property bool connected() const { return !m_closed && m_tcpImpl.conn && m_tcpImpl.conn.isConnected; } override @property bool dataAvailableForRead(){ logTrace("dataAvailableForRead"); m_settings.reader.acquire(); scope(exit) m_settings.reader.release(); return !readEmpty; } private @property bool readEmpty() { return (m_buffer && !m_slice) || (!m_buffer && m_readBuffer.empty); } override @property string peerAddress() const { return m_tcpImpl.conn.peer.toString(); } override @property NetworkAddress localAddress() const { return m_tcpImpl.localAddr; } override @property NetworkAddress remoteAddress() const { return NetworkAddress(m_tcpImpl.conn.peer); } override @property bool empty() { return leastSize == 0; } override @property ulong leastSize() { logTrace("leastSize TCP"); m_settings.reader.acquire(); scope(exit) m_settings.reader.release(); while( m_readBuffer.empty ){ if (!connected) return 0; m_settings.reader.noExcept = true; getDriverCore().yieldForEvent(); m_settings.reader.noExcept = false; } return (m_slice.length > 0) ? m_slice.length : m_readBuffer.length; } override void close() { logTrace("Close TCP enter"); // resume any reader, so that the read operation can be ended with a failure Task reader = m_settings.reader.task; while (m_settings.reader.isWaiting && reader.running) { logTrace("resuming reader first"); getDriverCore().yieldAndResumeTask(reader); } // test if the connection is already closed if (m_closed) { logTrace("connection already closed."); return; } //logTrace("closing"); m_settings.writer.acquire(); scope(exit) m_settings.writer.release(); // checkConnected(); m_readBuffer.dispose(); onClose(null, false); } override bool waitForData(Duration timeout = Duration.max) { // 0 seconds is max. CHanging this would be breaking, might as well use -1 for immediate if (timeout == 0.seconds) timeout = Duration.max; logTrace("WaitForData enter, timeout %s :: Ptr %s", timeout.toString(), (cast(void*)this).to!string); m_settings.reader.acquire(); auto _driver = getEventDriver(); auto tm = _driver.createTimer(null); scope(exit) { _driver.stopTimer(tm); _driver.releaseTimer(tm); m_settings.reader.release(); } _driver.m_timers.getUserData(tm).owner = Task.getThis(); if (timeout != Duration.max) _driver.rearmTimer(tm, timeout, false); logTrace("waitForData TCP"); while (m_readBuffer.empty) { if (!connected) return false; if (m_mustRecv) onRead(); else { //logTrace("Yielding for event in waitForData, waiting? %s", m_settings.reader.isWaiting); m_settings.reader.noExcept = true; getDriverCore().yieldForEvent(); m_settings.reader.noExcept = false; } if (timeout != Duration.max && !_driver.isTimerPending(tm)) { logTrace("WaitForData TCP: timer signal"); return false; } } if (m_readBuffer.empty && !connected) return false; logTrace("WaitForData exit: fiber resumed with read buffer"); return !m_readBuffer.empty; } override const(ubyte)[] peek() { logTrace("Peek TCP enter"); m_settings.reader.acquire(); scope(exit) m_settings.reader.release(); if (!readEmpty) return (m_slice.length > 0) ? cast(const(ubyte)[]) m_slice : m_readBuffer.peek(); else return null; } override size_t read(scope ubyte[] dst, IOMode) { if (!dst.length) return 0; assert(dst !is null && !m_slice); logTrace("Read TCP"); m_settings.reader.acquire(); size_t len = 0; scope(exit) m_settings.reader.release(); while( dst.length > 0 ){ while( m_readBuffer.empty ){ checkConnected(); if (m_mustRecv) onRead(); else { getDriverCore().yieldForEvent(); checkConnected(); } } size_t amt = min(dst.length, m_readBuffer.length); m_readBuffer.read(dst[0 .. amt]); dst = dst[amt .. $]; len += amt; } return len; } override size_t write(in ubyte[] bytes_, IOMode) { assert(bytes_ !is null); logTrace("%s", "write enter"); m_settings.writer.acquire(); scope(exit) m_settings.writer.release(); checkConnected(); const(ubyte)[] bytes = bytes_; logTrace("TCP write with %s bytes called", bytes.length); bool first = true; size_t offset; size_t len = bytes.length; do { if (!first) { getDriverCore().yieldForEvent(); } checkConnected(); offset += conn.send(bytes[offset .. $]); if (conn.hasError) { throw new Exception(conn.error); } first = false; } while (offset != len); return len; } override void flush() { logTrace("%s", "Flush"); m_settings.writer.acquire(); scope(exit) m_settings.writer.release(); checkConnected(); } override void finalize() { logTrace("%s", "finalize"); flush(); } private void checkConnected() { enforce(connected, "The remote peer has closed the connection."); logTrace("Check Connected"); } private bool tryReadBuf() { //logTrace("TryReadBuf with m_buffer: %s", m_buffer.length); if (m_buffer) { ubyte[] buf = m_buffer[m_slice.length .. $]; uint ret = conn.recv(buf); logTrace("Received: %s", buf[0 .. ret]); // check for overflow if (ret == buf.length) { logTrace("Overflow detected, revert to ring buffer"); m_slice = null; m_readBuffer.capacity = 64*1024; m_readBuffer.put(buf); m_buffer = null; return false; // cancel slices and revert to the fixed ring buffer } if (m_slice.length > 0) { //logDebug("post-assign m_slice "); m_slice = m_slice.ptr[0 .. m_slice.length + ret]; } else { //logDebug("using m_buffer"); m_slice = m_buffer[0 .. ret]; } return true; } logTrace("TryReadBuf exit with %d bytes in m_slice, %d bytes in m_readBuffer ", m_slice.length, m_readBuffer.length); return false; } private void onRead() { m_mustRecv = true; // assume we didn't receive everything if (tryReadBuf()) { m_mustRecv = false; return; } assert(!m_slice); logTrace("OnRead with %s", m_readBuffer.freeSpace); while( m_readBuffer.freeSpace > 0 ) { ubyte[] dst = m_readBuffer.peekDst(); assert(dst.length <= int.max); logTrace("Try to read up to bytes: %s", dst.length); bool read_more; do { uint ret = conn.recv(dst); if( ret > 0 ){ logTrace("received bytes: %s", ret); m_readBuffer.putN(ret); } read_more = ret == dst.length; // ret == 0! let's look for some errors if (read_more) { if (m_readBuffer.freeSpace == 0) m_readBuffer.capacity = m_readBuffer.capacity*2; dst = m_readBuffer.peekDst(); } } while( read_more ); if (conn.status.code == Status.ASYNC) { m_mustRecv = false; // we'll have to wait break; // the kernel's buffer is empty } // ret == 0! let's look for some errors else if (conn.status.code == Status.ASYNC) { m_mustRecv = false; // we'll have to wait break; // the kernel's buffer is empty } else if (conn.status.code != Status.OK) { // We have a read error and the socket may now even be closed... auto err = conn.error; logTrace("receive error %s %s", err, conn.status.code); throw new Exception("Socket error: " ~ conn.status.code.to!string); } else { m_mustRecv = false; break; } } logTrace("OnRead exit with free bytes: %s", m_readBuffer.freeSpace); } /* The AsyncTCPConnection object will be automatically disposed when this returns. * We're given some time to cleanup. */ private void onClose(in string msg = null, bool wake_ex = true) { logTrace("onClose"); if (msg) m_error = msg; if (!m_closed) { m_closed = true; if (m_tcpImpl.conn && m_tcpImpl.conn.isConnected) { m_tcpImpl.conn.kill(Task.getThis() != Task.init); // close the connection m_tcpImpl.conn = null; } } if (Task.getThis() != Task.init) { return; } Exception ex; if (!msg && wake_ex) ex = new Exception("Connection closed"); else if (wake_ex) ex = new Exception(msg); Task reader = m_settings.reader.task; Task writer = m_settings.writer.task; bool hasUniqueReader = m_settings.reader.isWaiting; bool hasUniqueWriter = m_settings.writer.isWaiting && reader != writer; if (hasUniqueWriter && Task.getThis() != writer && wake_ex) { getDriverCore().resumeTask(writer, ex); } if (hasUniqueReader && Task.getThis() != reader) { getDriverCore().resumeTask(reader, m_settings.reader.noExcept?null:ex); } } void onConnect() { scope(failure) onClose(); if (m_tcpImpl.conn && m_tcpImpl.conn.isConnected) { bool inbound = m_tcpImpl.conn.inbound; try m_settings.onConnect(this); catch ( Exception e) { //logError(e.toString); throw e; } catch ( Throwable e) { logError("%s", e.toString); throw e; } if (inbound) close(); } logTrace("Finished callback"); } void handler(TCPEvent ev) { logTrace("Handler"); Exception ex; final switch (ev) { case TCPEvent.CONNECT: m_closed = false; // read & write are guaranteed to be successful on any platform at this point if (m_tcpImpl.conn.inbound) runTask(&onConnect); else onConnect(); m_settings.onConnect = null; break; case TCPEvent.READ: // fill the read buffer and resume any task if waiting try onRead(); catch (Exception e) ex = e; if (m_settings.reader.isWaiting) getDriverCore().resumeTask(m_settings.reader.task, ex); goto case TCPEvent.WRITE; // sometimes the kernel notified write with read events case TCPEvent.WRITE: // The kernel is ready to have some more data written, all we need to do is wake up the writer if (m_settings.writer.isWaiting) getDriverCore().resumeTask(m_settings.writer.task, ex); break; case TCPEvent.CLOSE: m_closed = false; onClose(); if (m_settings.onConnect) m_settings.onConnect(this); m_settings.onConnect = null; break; case TCPEvent.ERROR: m_closed = false; onClose(conn.error); if (m_settings.onConnect) m_settings.onConnect(this); m_settings.onConnect = null; break; } return; } struct Waiter { Task task; // we can only have one task waiting for read/write operations bool isWaiting; // if a task is actively waiting bool noExcept; void acquire() { assert(!this.isWaiting, "Acquiring waiter that is already in use."); if (Task.getThis() == Task()) return; logTrace("%s", "Acquire waiter"); assert(!amOwner(), "Failed to acquire waiter in task: " ~ Task.getThis().fiber.to!string ~ ", it was busy with: " ~ this.task.to!string); this.task = Task.getThis(); this.isWaiting = true; } void release() { if (Task.getThis() == Task()) return; logTrace("%s", "Release waiter"); assert(amOwner()); this.isWaiting = false; } bool amOwner() const { if (this.isWaiting && this.task == Task.getThis()) return true; return false; } } struct Settings { void delegate(TCPConnection) onConnect; Duration readTimeout; bool keepAlive; bool tcpNoDelay; Waiter reader; Waiter writer; } struct TCPConnectionImpl { NetworkAddress localAddr; AsyncTCPConnection conn; } } int total_conn; final class LibasyncUDPConnection : UDPConnection { @trusted: private { Task m_task; AsyncUDPSocket m_udpImpl; bool m_canBroadcast; NetworkAddressLA m_peer; bool m_waiting; } private @property AsyncUDPSocket socket() { return m_udpImpl; } this(AsyncUDPSocket conn) in { assert(conn !is null); } body { m_udpImpl = conn; } override @property string bindAddress() const { return m_udpImpl.local.toAddressString(); } override @property NetworkAddress localAddress() const { return NetworkAddress(m_udpImpl.local); } override @property bool canBroadcast() const { return m_canBroadcast; } override @property void canBroadcast(bool val) { socket.broadcast(val); m_canBroadcast = val; } override void close() { socket.kill(); m_udpImpl = null; } bool amOwner() { return m_task != Task() && m_task == Task.getThis(); } void acquire() { assert(m_task == Task(), "Trying to acquire a UDP socket that is currently owned."); m_task = Task.getThis(); } void release() { assert(m_task != Task(), "Trying to release a UDP socket that is not owned."); assert(m_task == Task.getThis(), "Trying to release a foreign UDP socket."); m_task = Task(); } override void connect(string host, ushort port) { // assert(m_peer == NetworkAddress.init, "Cannot connect to another peer"); NetworkAddress addr = getEventDriver().resolveHost(host, localAddress.family, true); addr.port = port; connect(addr); } override void connect(NetworkAddress addr) { m_peer = cast(NetworkAddressLA)addr; } override void send(in ubyte[] data, in NetworkAddress* peer_address = null) { assert(data.length <= int.max); uint ret; size_t retries = 3; foreach (i; 0 .. retries) { if( peer_address ){ auto pa = cast(NetworkAddressLA)*cast(NetworkAddress*)peer_address; ret = socket.sendTo(data, pa); } else { ret = socket.sendTo(data, m_peer); } if (socket.status.code == Status.ASYNC) { m_waiting = true; getDriverCore().yieldForEvent(); } else break; } logTrace("send ret: %s, %s", ret, socket.status.text); enforce(socket.status.code == Status.OK, "Error sending UDP packet: " ~ socket.status.text); enforce(ret == data.length, "Unable to send full packet."); } override ubyte[] recv(ubyte[] buf = null, NetworkAddress* peer_address = null) { return recv(Duration.max, buf, peer_address); } override ubyte[] recv(Duration timeout, ubyte[] buf = null, NetworkAddress* peer_address = null) { size_t tm = size_t.max; auto m_driver = getEventDriver(); if (timeout != Duration.max && timeout > 0.seconds) { tm = m_driver.createTimer(null); m_driver.rearmTimer(tm, timeout, false); m_driver.acquireTimer(tm); } acquire(); scope(exit) { release(); if (tm != size_t.max) m_driver.releaseTimer(tm); } assert(buf.length <= int.max); if( buf.length == 0 ) buf.length = 65507; NetworkAddressLA from; from.family = localAddress.family; while(true){ auto ret = socket.recvFrom(buf, from); if( ret > 0 ){ if( peer_address ) *peer_address = NetworkAddress(from); return buf[0 .. ret]; } else if( socket.status.code != Status.OK ){ auto err = socket.status.text; logDebug("UDP recv err: %s", err); enforce(socket.status.code == Status.ASYNC, "Error receiving UDP packet"); if (timeout != Duration.max) { enforce(timeout > 0.seconds && m_driver.isTimerPending(tm), "UDP receive timeout."); } } m_waiting = true; getDriverCore().yieldForEvent(); } } private void handler(UDPEvent ev) { logTrace("UDPConnection %p event", this); Exception ex; final switch (ev) { case UDPEvent.READ: if (m_waiting) { m_waiting = false; getDriverCore().resumeTask(m_task, null); } break; case UDPEvent.WRITE: if (m_waiting) { m_waiting = false; getDriverCore().resumeTask(m_task, null); } break; case UDPEvent.ERROR: getDriverCore.resumeTask(m_task, new Exception(socket.error)); break; } } } /* The following is used for LibasyncManualEvent */ import std.container : Array; Array!(Array!Task) s_eventWaiters; // Task list in the current thread per instance ID __gshared Array!size_t gs_availID; __gshared size_t gs_maxID; __gshared core.sync.mutex.Mutex gs_mutex; private size_t generateID() nothrow @trusted { size_t idx; import std.algorithm : max; try { size_t getIdx() { if (!gs_availID.empty) { immutable size_t ret = gs_availID.back; gs_availID.removeBack(); return ret; } return 0; } synchronized(gs_mutex) { idx = getIdx(); if (idx == 0) { import std.range : iota; gs_availID.insert( iota(gs_maxID + 1, max(32, gs_maxID * 2 + 1), 1) ); gs_maxID = gs_availID[$-1]; idx = getIdx(); } } } catch (Exception e) { assert(false, "Failed to generate necessary ID for Manual Event waiters: " ~ e.msg); } return idx - 1; } void recycleID(size_t id) @trusted nothrow { try { synchronized(gs_mutex) gs_availID.insert(id+1); } catch (Exception e) { assert(false, "Error destroying Manual Event ID: " ~ id.to!string ~ " [" ~ e.msg ~ "]"); } }
D
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you 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 hunt.net.buffer.ByteBuf; import hunt.net.buffer.ByteBufAllocator; import hunt.net.buffer.ByteProcessor; import hunt.net.buffer.ReferenceCounted; import hunt.Byte; import hunt.collection.ByteBuffer; import hunt.Double; import hunt.Exceptions; import hunt.Float; import hunt.io.Common; import hunt.logging.ConsoleLogger; import hunt.text.Charset; import std.conv; alias CharSequence = string; /** * Checks that the given argument is not null. If it is, throws {@link NullPointerException}. * Otherwise, returns the argument. */ static T checkNotNull(T)(T arg, string text) { if (arg is null) { throw new NullPointerException(text); } return arg; } /** * Checks that the given argument is strictly positive. If it is not, throws {@link IllegalArgumentException}. * Otherwise, returns the argument. */ int checkPositive(int i, string name) { if (i <= 0) { throw new IllegalArgumentException(name ~ ": " ~ i.to!string() ~ " (expected: > 0)"); } return i; } /** * Checks that the given argument is strictly positive. If it is not, throws {@link IllegalArgumentException}. * Otherwise, returns the argument. */ long checkPositive(long i, string name) { if (i <= 0) { throw new IllegalArgumentException(name ~ ": " ~ i.to!string() ~ " (expected: > 0)"); } return i; } /** * Checks that the given argument is positive or zero. If it is not , throws {@link IllegalArgumentException}. * Otherwise, returns the argument. */ int checkPositiveOrZero(int i, string name) { if (i < 0) { throw new IllegalArgumentException(name ~ ": " ~ i.to!string() ~ " (expected: >= 0)"); } return i; } /** * Determine if the requested {@code index} and {@code length} will fit within {@code capacity}. * @param index The starting index. * @param length The length which will be utilized (starting from {@code index}). * @param capacity The capacity that {@code index + length} is allowed to be within. * @return {@code true} if the requested {@code index} and {@code length} will fit within {@code capacity}. * {@code false} if this would result in an index out of bounds exception. */ bool isOutOfBounds(int index, int length, int capacity) { return (index | length | (index + length) | (capacity - (index + length))) < 0; } void throwException(Throwable ex) { // version(HUNT_DEBUG){ warning(ex); } else { warning(ex.msg); } } /** * A random and sequential accessible sequence of zero or more bytes (octets). * This interface provides an abstract view for one or more primitive byte * arrays ({@code byte[]}) and {@linkplain ByteBuffer NIO buffers}. * * <h3>Creation of a buffer</h3> * * It is recommended to create a new buffer using the helper methods in * {@link Unpooled} rather than calling an individual implementation's * constructor. * * <h3>Random Access Indexing</h3> * * Just like an ordinary primitive byte array, {@link ByteBuf} uses * <a href="http://en.wikipedia.org/wiki/Zero-based_numbering">zero-based indexing</a>. * It means the index of the first byte is always {@code 0} and the index of the last byte is * always {@link #capacity() capacity - 1}. For example, to iterate all bytes of a buffer, you * can do the following, regardless of its internal implementation: * * <pre> * {@link ByteBuf} buffer = ...; * for (int i = 0; i &lt; buffer.capacity(); i ++) { * byte b = buffer.getByte(i); * System.out.println((char) b); * } * </pre> * * <h3>Sequential Access Indexing</h3> * * {@link ByteBuf} provides two pointer variables to support sequential * read and write operations - {@link #readerIndex() readerIndex} for a read * operation and {@link #writerIndex() writerIndex} for a write operation * respectively. The following diagram shows how a buffer is segmented into * three areas by the two pointers: * * <pre> * +-------------------+------------------+------------------+ * | discardable bytes | readable bytes | writable bytes | * | | (CONTENT) | | * +-------------------+------------------+------------------+ * | | | | * 0 <= readerIndex <= writerIndex <= capacity * </pre> * * <h4>Readable bytes (the actual content)</h4> * * This segment is where the actual data is stored. Any operation whose name * starts with {@code read} or {@code skip} will get or skip the data at the * current {@link #readerIndex() readerIndex} and increase it by the number of * read bytes. If the argument of the read operation is also a * {@link ByteBuf} and no destination index is specified, the specified * buffer's {@link #writerIndex() writerIndex} is increased together. * <p> * If there's not enough content left, {@link IndexOutOfBoundsException} is * raised. The default value of newly allocated, wrapped or copied buffer's * {@link #readerIndex() readerIndex} is {@code 0}. * * <pre> * // Iterates the readable bytes of a buffer. * {@link ByteBuf} buffer = ...; * while (buffer.isReadable()) { * System.out.println(buffer.readByte()); * } * </pre> * * <h4>Writable bytes</h4> * * This segment is a undefined space which needs to be filled. Any operation * whose name starts with {@code write} will write the data at the current * {@link #writerIndex() writerIndex} and increase it by the number of written * bytes. If the argument of the write operation is also a {@link ByteBuf}, * and no source index is specified, the specified buffer's * {@link #readerIndex() readerIndex} is increased together. * <p> * If there's not enough writable bytes left, {@link IndexOutOfBoundsException} * is raised. The default value of newly allocated buffer's * {@link #writerIndex() writerIndex} is {@code 0}. The default value of * wrapped or copied buffer's {@link #writerIndex() writerIndex} is the * {@link #capacity() capacity} of the buffer. * * <pre> * // Fills the writable bytes of a buffer with random integers. * {@link ByteBuf} buffer = ...; * while (buffer.maxWritableBytes() >= 4) { * buffer.writeInt(random.nextInt()); * } * </pre> * * <h4>Discardable bytes</h4> * * This segment contains the bytes which were read already by a read operation. * Initially, the size of this segment is {@code 0}, but its size increases up * to the {@link #writerIndex() writerIndex} as read operations are executed. * The read bytes can be discarded by calling {@link #discardReadBytes()} to * reclaim unused area as depicted by the following diagram: * * <pre> * BEFORE discardReadBytes() * * +-------------------+------------------+------------------+ * | discardable bytes | readable bytes | writable bytes | * +-------------------+------------------+------------------+ * | | | | * 0 <= readerIndex <= writerIndex <= capacity * * * AFTER discardReadBytes() * * +------------------+--------------------------------------+ * | readable bytes | writable bytes (got more space) | * +------------------+--------------------------------------+ * | | | * readerIndex (0) <= writerIndex (decreased) <= capacity * </pre> * * Please note that there is no guarantee about the content of writable bytes * after calling {@link #discardReadBytes()}. The writable bytes will not be * moved in most cases and could even be filled with completely different data * depending on the underlying buffer implementation. * * <h4>Clearing the buffer indexes</h4> * * You can set both {@link #readerIndex() readerIndex} and * {@link #writerIndex() writerIndex} to {@code 0} by calling {@link #clear()}. * It does not clear the buffer content (e.g. filling with {@code 0}) but just * clears the two pointers. Please also note that the semantic of this * operation is different from {@link ByteBuffer#clear()}. * * <pre> * BEFORE clear() * * +-------------------+------------------+------------------+ * | discardable bytes | readable bytes | writable bytes | * +-------------------+------------------+------------------+ * | | | | * 0 <= readerIndex <= writerIndex <= capacity * * * AFTER clear() * * +---------------------------------------------------------+ * | writable bytes (got more space) | * +---------------------------------------------------------+ * | | * 0 = readerIndex = writerIndex <= capacity * </pre> * * <h3>Search operations</h3> * * For simple single-byte searches, use {@link #indexOf(int, int, byte)} and {@link #bytesBefore(int, int, byte)}. * {@link #bytesBefore(byte)} is especially useful when you deal with a {@code NUL}-terminated string. * For complicated searches, use {@link #forEachByte(int, int, ByteProcessor)} with a {@link ByteProcessor} * implementation. * * <h3>Mark and reset</h3> * * There are two marker indexes in every buffer. One is for storing * {@link #readerIndex() readerIndex} and the other is for storing * {@link #writerIndex() writerIndex}. You can always reposition one of the * two indexes by calling a reset method. It works in a similar fashion to * the mark and reset methods in {@link InputStream} except that there's no * {@code readlimit}. * * <h3>Derived buffers</h3> * * You can create a view of an existing buffer by calling one of the following methods: * <ul> * <li>{@link #duplicate()}</li> * <li>{@link #slice()}</li> * <li>{@link #slice(int, int)}</li> * <li>{@link #readSlice(int)}</li> * <li>{@link #retainedDuplicate()}</li> * <li>{@link #retainedSlice()}</li> * <li>{@link #retainedSlice(int, int)}</li> * <li>{@link #readRetainedSlice(int)}</li> * </ul> * A derived buffer will have an independent {@link #readerIndex() readerIndex}, * {@link #writerIndex() writerIndex} and marker indexes, while it shares * other internal data representation, just like a NIO buffer does. * <p> * In case a completely fresh copy of an existing buffer is required, please * call {@link #copy()} method instead. * * <h4>Non-retained and retained derived buffers</h4> * * Note that the {@link #duplicate()}, {@link #slice()}, {@link #slice(int, int)} and {@link #readSlice(int)} does NOT * call {@link #retain()} on the returned derived buffer, and thus its reference count will NOT be increased. If you * need to create a derived buffer with increased reference count, consider using {@link #retainedDuplicate()}, * {@link #retainedSlice()}, {@link #retainedSlice(int, int)} and {@link #readRetainedSlice(int)} which may return * a buffer implementation that produces less garbage. * * <h3>Conversion to existing JDK types</h3> * * <h4>Byte array</h4> * * If a {@link ByteBuf} is backed by a byte array (i.e. {@code byte[]}), * you can access it directly via the {@link #array()} method. To determine * if a buffer is backed by a byte array, {@link #hasArray()} should be used. * * <h4>NIO Buffers</h4> * * If a {@link ByteBuf} can be converted into an NIO {@link ByteBuffer} which shares its * content (i.e. view buffer), you can get it via the {@link #nioBuffer()} method. To determine * if a buffer can be converted into an NIO buffer, use {@link #nioBufferCount()}. * * <h4>Strings</h4> * * Various {@link #toString(Charset)} methods convert a {@link ByteBuf} * into a {@link string}. Please note that {@link #toString()} is not a * conversion method. * * <h4>I/O Streams</h4> * * Please refer to {@link ByteBufInputStream} and * {@link ByteBufOutputStream}. */ abstract class ByteBuf : ReferenceCounted { // implements ReferenceCounted, Comparable<ByteBuf> /** * Returns the number of bytes (octets) this buffer can contain. */ abstract int capacity(); /** * Adjusts the capacity of this buffer. If the {@code newCapacity} is less than the current * capacity, the content of this buffer is truncated. If the {@code newCapacity} is greater * than the current capacity, the buffer is appended with unspecified data whose length is * {@code (newCapacity - currentCapacity)}. * * @throws IllegalArgumentException if the {@code newCapacity} is greater than {@link #maxCapacity()} */ abstract ByteBuf capacity(int newCapacity); /** * Returns the maximum allowed capacity of this buffer. This value provides an upper * bound on {@link #capacity()}. */ abstract int maxCapacity(); /** * Returns the {@link ByteBufAllocator} which created this buffer. */ abstract ByteBufAllocator alloc(); /** * Returns the <a href="http://en.wikipedia.org/wiki/Endianness">endianness</a> * of this buffer. * * @deprecated use the Little Endian accessors, e.g. {@code getShortLE}, {@code getIntLE} * instead of creating a buffer with swapped {@code endianness}. */ // @Deprecated abstract ByteOrder order(); /** * Returns a buffer with the specified {@code endianness} which shares the whole region, * indexes, and marks of this buffer. Modifying the content, the indexes, or the marks of the * returned buffer or this buffer affects each other's content, indexes, and marks. If the * specified {@code endianness} is identical to this buffer's byte order, this method can * return {@code this}. This method does not modify {@code readerIndex} or {@code writerIndex} * of this buffer. * * @deprecated use the Little Endian accessors, e.g. {@code getShortLE}, {@code getIntLE} * instead of creating a buffer with swapped {@code endianness}. */ // @Deprecated // abstract ByteBuf order(ByteOrder endianness); /** * Return the underlying buffer instance if this buffer is a wrapper of another buffer. * * @return {@code null} if this buffer is not a wrapper */ abstract ByteBuf unwrap(); /** * Returns {@code true} if and only if this buffer is backed by an * NIO direct buffer. */ abstract bool isDirect(); /** * Returns {@code true} if and only if this buffer is read-only. */ abstract bool isReadOnly(); /** * Returns a read-only version of this buffer. */ abstract ByteBuf asReadOnly(); /** * Returns the {@code readerIndex} of this buffer. */ abstract int readerIndex(); /** * Sets the {@code readerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code readerIndex} is * less than {@code 0} or * greater than {@code this.writerIndex} */ abstract ByteBuf readerIndex(int readerIndex); /** * Returns the {@code writerIndex} of this buffer. */ abstract int writerIndex(); /** * Sets the {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code writerIndex} is * less than {@code this.readerIndex} or * greater than {@code this.capacity} */ abstract ByteBuf writerIndex(int writerIndex); /** * Sets the {@code readerIndex} and {@code writerIndex} of this buffer * in one shot. This method is useful when you have to worry about the * invocation order of {@link #readerIndex(int)} and {@link #writerIndex(int)} * methods. For example, the following code will fail: * * <pre> * // Create a buffer whose readerIndex, writerIndex and capacity are * // 0, 0 and 8 respectively. * {@link ByteBuf} buf = {@link Unpooled}.buffer(8); * * // IndexOutOfBoundsException is thrown because the specified * // readerIndex (2) cannot be greater than the current writerIndex (0). * buf.readerIndex(2); * buf.writerIndex(4); * </pre> * * The following code will also fail: * * <pre> * // Create a buffer whose readerIndex, writerIndex and capacity are * // 0, 8 and 8 respectively. * {@link ByteBuf} buf = {@link Unpooled}.wrappedBuffer(new byte[8]); * * // readerIndex becomes 8. * buf.readLong(); * * // IndexOutOfBoundsException is thrown because the specified * // writerIndex (4) cannot be less than the current readerIndex (8). * buf.writerIndex(4); * buf.readerIndex(2); * </pre> * * By contrast, this method guarantees that it never * throws an {@link IndexOutOfBoundsException} as long as the specified * indexes meet basic constraints, regardless what the current index * values of the buffer are: * * <pre> * // No matter what the current state of the buffer is, the following * // call always succeeds as long as the capacity of the buffer is not * // less than 4. * buf.setIndex(2, 4); * </pre> * * @throws IndexOutOfBoundsException * if the specified {@code readerIndex} is less than 0, * if the specified {@code writerIndex} is less than the specified * {@code readerIndex} or if the specified {@code writerIndex} is * greater than {@code this.capacity} */ abstract ByteBuf setIndex(int readerIndex, int writerIndex); /** * Returns the number of readable bytes which is equal to * {@code (this.writerIndex - this.readerIndex)}. */ abstract int readableBytes(); /** * Returns the number of writable bytes which is equal to * {@code (this.capacity - this.writerIndex)}. */ abstract int writableBytes(); /** * Returns the maximum possible number of writable bytes, which is equal to * {@code (this.maxCapacity - this.writerIndex)}. */ abstract int maxWritableBytes(); /** * Returns the maximum number of bytes which can be written for certain without involving * an internal reallocation or data-copy. The returned value will be &ge; {@link #writableBytes()} * and &le; {@link #maxWritableBytes()}. */ int maxFastWritableBytes() { return writableBytes(); } /** * Returns {@code true} * if and only if {@code (this.writerIndex - this.readerIndex)} is greater * than {@code 0}. */ abstract bool isReadable(); /** * Returns {@code true} if and only if this buffer contains equal to or more than the specified number of elements. */ abstract bool isReadable(int size); /** * Returns {@code true} * if and only if {@code (this.capacity - this.writerIndex)} is greater * than {@code 0}. */ abstract bool isWritable(); /** * Returns {@code true} if and only if this buffer has enough room to allow writing the specified number of * elements. */ abstract bool isWritable(int size); /** * Sets the {@code readerIndex} and {@code writerIndex} of this buffer to * {@code 0}. * This method is identical to {@link #setIndex(int, int) setIndex(0, 0)}. * <p> * Please note that the behavior of this method is different * from that of NIO buffer, which sets the {@code limit} to * the {@code capacity} of the buffer. */ abstract ByteBuf clear(); /** * Marks the current {@code readerIndex} in this buffer. You can * reposition the current {@code readerIndex} to the marked * {@code readerIndex} by calling {@link #resetReaderIndex()}. * The initial value of the marked {@code readerIndex} is {@code 0}. */ abstract ByteBuf markReaderIndex(); /** * Repositions the current {@code readerIndex} to the marked * {@code readerIndex} in this buffer. * * @throws IndexOutOfBoundsException * if the current {@code writerIndex} is less than the marked * {@code readerIndex} */ abstract ByteBuf resetReaderIndex(); /** * Marks the current {@code writerIndex} in this buffer. You can * reposition the current {@code writerIndex} to the marked * {@code writerIndex} by calling {@link #resetWriterIndex()}. * The initial value of the marked {@code writerIndex} is {@code 0}. */ abstract ByteBuf markWriterIndex(); /** * Repositions the current {@code writerIndex} to the marked * {@code writerIndex} in this buffer. * * @throws IndexOutOfBoundsException * if the current {@code readerIndex} is greater than the marked * {@code writerIndex} */ abstract ByteBuf resetWriterIndex(); /** * Discards the bytes between the 0th index and {@code readerIndex}. * It moves the bytes between {@code readerIndex} and {@code writerIndex} * to the 0th index, and sets {@code readerIndex} and {@code writerIndex} * to {@code 0} and {@code oldWriterIndex - oldReaderIndex} respectively. * <p> * Please refer to the class documentation for more detailed explanation. */ abstract ByteBuf discardReadBytes(); /** * Similar to {@link ByteBuf#discardReadBytes()} except that this method might discard * some, all, or none of read bytes depending on its internal implementation to reduce * overall memory bandwidth consumption at the cost of potentially additional memory * consumption. */ abstract ByteBuf discardSomeReadBytes(); /** * Expands the buffer {@link #capacity()} to make sure the number of * {@linkplain #writableBytes() writable bytes} is equal to or greater than the * specified value. If there are enough writable bytes in this buffer, this method * returns with no side effect. * * @param minWritableBytes * the expected minimum number of writable bytes * @throws IndexOutOfBoundsException * if {@link #writerIndex()} + {@code minWritableBytes} &gt; {@link #maxCapacity()}. * @see #capacity(int) */ abstract ByteBuf ensureWritable(int minWritableBytes); /** * Expands the buffer {@link #capacity()} to make sure the number of * {@linkplain #writableBytes() writable bytes} is equal to or greater than the * specified value. Unlike {@link #ensureWritable(int)}, this method returns a status code. * * @param minWritableBytes * the expected minimum number of writable bytes * @param force * When {@link #writerIndex()} + {@code minWritableBytes} &gt; {@link #maxCapacity()}: * <ul> * <li>{@code true} - the capacity of the buffer is expanded to {@link #maxCapacity()}</li> * <li>{@code false} - the capacity of the buffer is unchanged</li> * </ul> * @return {@code 0} if the buffer has enough writable bytes, and its capacity is unchanged. * {@code 1} if the buffer does not have enough bytes, and its capacity is unchanged. * {@code 2} if the buffer has enough writable bytes, and its capacity has been increased. * {@code 3} if the buffer does not have enough bytes, but its capacity has been * increased to its maximum. */ abstract int ensureWritable(int minWritableBytes, bool force); /** * Gets a bool at the specified absolute (@code index) in this buffer. * This method does not modify the {@code readerIndex} or {@code writerIndex} * of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 1} is greater than {@code this.capacity} */ abstract bool getBoolean(int index); /** * Gets a byte at the specified absolute {@code index} in this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 1} is greater than {@code this.capacity} */ abstract byte getByte(int index); /** * Gets an unsigned byte at the specified absolute {@code index} in this * buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 1} is greater than {@code this.capacity} */ abstract short getUnsignedByte(int index); /** * Gets a 16-bit short integer at the specified absolute {@code index} in * this buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ abstract short getShort(int index); /** * Gets a 16-bit short integer at the specified absolute {@code index} in * this buffer in Little Endian Byte Order. This method does not modify * {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ abstract short getShortLE(int index); /** * Gets an unsigned 16-bit short integer at the specified absolute * {@code index} in this buffer. This method does not modify * {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ abstract int getUnsignedShort(int index); /** * Gets an unsigned 16-bit short integer at the specified absolute * {@code index} in this buffer in Little Endian Byte Order. * This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ abstract int getUnsignedShortLE(int index); /** * Gets a 24-bit medium integer at the specified absolute {@code index} in * this buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 3} is greater than {@code this.capacity} */ abstract int getMedium(int index); /** * Gets a 24-bit medium integer at the specified absolute {@code index} in * this buffer in the Little Endian Byte Order. This method does not * modify {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 3} is greater than {@code this.capacity} */ abstract int getMediumLE(int index); /** * Gets an unsigned 24-bit medium integer at the specified absolute * {@code index} in this buffer. This method does not modify * {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 3} is greater than {@code this.capacity} */ abstract int getUnsignedMedium(int index); /** * Gets an unsigned 24-bit medium integer at the specified absolute * {@code index} in this buffer in Little Endian Byte Order. * This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 3} is greater than {@code this.capacity} */ abstract int getUnsignedMediumLE(int index); /** * Gets a 32-bit integer at the specified absolute {@code index} in * this buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ abstract int getInt(int index); /** * Gets a 32-bit integer at the specified absolute {@code index} in * this buffer with Little Endian Byte Order. This method does not * modify {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ abstract int getIntLE(int index); /** * Gets an unsigned 32-bit integer at the specified absolute {@code index} * in this buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ abstract long getUnsignedInt(int index); /** * Gets an unsigned 32-bit integer at the specified absolute {@code index} * in this buffer in Little Endian Byte Order. This method does not * modify {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ abstract long getUnsignedIntLE(int index); /** * Gets a 64-bit long integer at the specified absolute {@code index} in * this buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ abstract long getLong(int index); /** * Gets a 64-bit long integer at the specified absolute {@code index} in * this buffer in Little Endian Byte Order. This method does not * modify {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ abstract long getLongLE(int index); /** * Gets a 2-byte UTF-16 character at the specified absolute * {@code index} in this buffer. This method does not modify * {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ abstract char getChar(int index); /** * Gets a 32-bit floating point number at the specified absolute * {@code index} in this buffer. This method does not modify * {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ abstract float getFloat(int index); /** * Gets a 32-bit floating point number at the specified absolute * {@code index} in this buffer in Little Endian Byte Order. * This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ float getFloatLE(int index) { return Float.intBitsToFloat(getIntLE(index)); } /** * Gets a 64-bit floating point number at the specified absolute * {@code index} in this buffer. This method does not modify * {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ abstract double getDouble(int index); /** * Gets a 64-bit floating point number at the specified absolute * {@code index} in this buffer in Little Endian Byte Order. * This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ double getDoubleLE(int index) { return Double.longBitsToDouble(getLongLE(index)); } /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index} until the destination becomes * non-writable. This method is basically same with * {@link #getBytes(int, ByteBuf, int, int)}, except that this * method increases the {@code writerIndex} of the destination by the * number of the transferred bytes while * {@link #getBytes(int, ByteBuf, int, int)} does not. * This method does not modify {@code readerIndex} or {@code writerIndex} of * the source buffer (i.e. {@code this}). * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + dst.writableBytes} is greater than * {@code this.capacity} */ abstract ByteBuf getBytes(int index, ByteBuf dst); /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index}. This method is basically same * with {@link #getBytes(int, ByteBuf, int, int)}, except that this * method increases the {@code writerIndex} of the destination by the * number of the transferred bytes while * {@link #getBytes(int, ByteBuf, int, int)} does not. * This method does not modify {@code readerIndex} or {@code writerIndex} of * the source buffer (i.e. {@code this}). * * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code length} is greater than {@code dst.writableBytes} */ abstract ByteBuf getBytes(int index, ByteBuf dst, int length); /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} * of both the source (i.e. {@code this}) and the destination. * * @param dstIndex the first index of the destination * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if the specified {@code dstIndex} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code dstIndex + length} is greater than * {@code dst.capacity} */ abstract ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length); /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + dst.length} is greater than * {@code this.capacity} */ abstract ByteBuf getBytes(int index, byte[] dst); /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} * of this buffer. * * @param dstIndex the first index of the destination * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if the specified {@code dstIndex} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code dstIndex + length} is greater than * {@code dst.length} */ abstract ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length); /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index} until the destination's position * reaches its limit. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer while the destination's {@code position} will be increased. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + dst.remaining()} is greater than * {@code this.capacity} */ abstract ByteBuf getBytes(int index, ByteBuffer dst); /** * Transfers this buffer's data to the specified stream starting at the * specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than * {@code this.capacity} * @throws IOException * if the specified stream threw an exception during I/O */ abstract ByteBuf getBytes(int index, OutputStream outStream, int length); /** * Transfers this buffer's data to the specified channel starting at the * specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @param length the maximum number of bytes to transfer * * @return the actual number of bytes written out to the specified channel * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than * {@code this.capacity} * @throws IOException * if the specified channel threw an exception during I/O */ // abstract int getBytes(int index, GatheringByteChannel out, int length); /** * Transfers this buffer's data starting at the specified absolute {@code index} * to the specified channel starting at the given file position. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. This method does not modify the channel's position. * * @param position the file position at which the transfer is to begin * @param length the maximum number of bytes to transfer * * @return the actual number of bytes written out to the specified channel * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than * {@code this.capacity} * @throws IOException * if the specified channel threw an exception during I/O */ // abstract int getBytes(int index, FileChannel out, long position, int length); /** * Gets a {@link CharSequence} with the given length at the given index. * * @param length the length to read * @param charset that should be used * @return the sequence * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} */ abstract CharSequence getCharSequence(int index, int length, Charset charset); /** * Sets the specified bool at the specified absolute {@code index} in this * buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 1} is greater than {@code this.capacity} */ abstract ByteBuf setBoolean(int index, bool value); /** * Sets the specified byte at the specified absolute {@code index} in this * buffer. The 24 high-order bits of the specified value are ignored. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 1} is greater than {@code this.capacity} */ abstract ByteBuf setByte(int index, int value); /** * Sets the specified 16-bit short integer at the specified absolute * {@code index} in this buffer. The 16 high-order bits of the specified * value are ignored. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ abstract ByteBuf setShort(int index, int value); /** * Sets the specified 16-bit short integer at the specified absolute * {@code index} in this buffer with the Little Endian Byte Order. * The 16 high-order bits of the specified value are ignored. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ abstract ByteBuf setShortLE(int index, int value); /** * Sets the specified 24-bit medium integer at the specified absolute * {@code index} in this buffer. Please note that the most significant * byte is ignored in the specified value. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 3} is greater than {@code this.capacity} */ abstract ByteBuf setMedium(int index, int value); /** * Sets the specified 24-bit medium integer at the specified absolute * {@code index} in this buffer in the Little Endian Byte Order. * Please note that the most significant byte is ignored in the * specified value. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 3} is greater than {@code this.capacity} */ abstract ByteBuf setMediumLE(int index, int value); /** * Sets the specified 32-bit integer at the specified absolute * {@code index} in this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ abstract ByteBuf setInt(int index, int value); /** * Sets the specified 32-bit integer at the specified absolute * {@code index} in this buffer with Little Endian byte order * . * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ abstract ByteBuf setIntLE(int index, int value); /** * Sets the specified 64-bit long integer at the specified absolute * {@code index} in this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ abstract ByteBuf setLong(int index, long value); /** * Sets the specified 64-bit long integer at the specified absolute * {@code index} in this buffer in Little Endian Byte Order. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ abstract ByteBuf setLongLE(int index, long value); /** * Sets the specified 2-byte UTF-16 character at the specified absolute * {@code index} in this buffer. * The 16 high-order bits of the specified value are ignored. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ abstract ByteBuf setChar(int index, int value); /** * Sets the specified 32-bit floating-point number at the specified * absolute {@code index} in this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ abstract ByteBuf setFloat(int index, float value); /** * Sets the specified 32-bit floating-point number at the specified * absolute {@code index} in this buffer in Little Endian Byte Order. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ ByteBuf setFloatLE(int index, float value) { return setIntLE(index, Float.floatToRawIntBits(value)); } /** * Sets the specified 64-bit floating-point number at the specified * absolute {@code index} in this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ abstract ByteBuf setDouble(int index, double value); /** * Sets the specified 64-bit floating-point number at the specified * absolute {@code index} in this buffer in Little Endian Byte Order. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ ByteBuf setDoubleLE(int index, double value) { return setLongLE(index, Double.doubleToRawLongBits(value)); } /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index} until the source buffer becomes * unreadable. This method is basically same with * {@link #setBytes(int, ByteBuf, int, int)}, except that this * method increases the {@code readerIndex} of the source buffer by * the number of the transferred bytes while * {@link #setBytes(int, ByteBuf, int, int)} does not. * This method does not modify {@code readerIndex} or {@code writerIndex} of * the source buffer (i.e. {@code this}). * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + src.readableBytes} is greater than * {@code this.capacity} */ abstract ByteBuf setBytes(int index, ByteBuf src); /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index}. This method is basically same * with {@link #setBytes(int, ByteBuf, int, int)}, except that this * method increases the {@code readerIndex} of the source buffer by * the number of the transferred bytes while * {@link #setBytes(int, ByteBuf, int, int)} does not. * This method does not modify {@code readerIndex} or {@code writerIndex} of * the source buffer (i.e. {@code this}). * * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code length} is greater than {@code src.readableBytes} */ abstract ByteBuf setBytes(int index, ByteBuf src, int length); /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} * of both the source (i.e. {@code this}) and the destination. * * @param srcIndex the first index of the source * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if the specified {@code srcIndex} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code srcIndex + length} is greater than * {@code src.capacity} */ abstract ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length); /** * Transfers the specified source array's data to this buffer starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + src.length} is greater than * {@code this.capacity} */ abstract ByteBuf setBytes(int index, byte[] src); /** * Transfers the specified source array's data to this buffer starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if the specified {@code srcIndex} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code srcIndex + length} is greater than {@code src.length} */ abstract ByteBuf setBytes(int index, byte[] src, int srcIndex, int length); /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index} until the source buffer's position * reaches its limit. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + src.remaining()} is greater than * {@code this.capacity} */ abstract ByteBuf setBytes(int index, ByteBuffer src); /** * Transfers the content of the specified source stream to this buffer * starting at the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @param length the number of bytes to transfer * * @return the actual number of bytes read in from the specified channel. * {@code -1} if the specified channel is closed. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than {@code this.capacity} * @throws IOException * if the specified stream threw an exception during I/O */ abstract int setBytes(int index, InputStream inStream, int length); /** * Transfers the content of the specified source channel to this buffer * starting at the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @param length the maximum number of bytes to transfer * * @return the actual number of bytes read in from the specified channel. * {@code -1} if the specified channel is closed. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than {@code this.capacity} * @throws IOException * if the specified channel threw an exception during I/O */ // abstract int setBytes(int index, ScatteringByteChannel in, int length); /** * Transfers the content of the specified source channel starting at the given file position * to this buffer starting at the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. This method does not modify the channel's position. * * @param position the file position at which the transfer is to begin * @param length the maximum number of bytes to transfer * * @return the actual number of bytes read in from the specified channel. * {@code -1} if the specified channel is closed. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than {@code this.capacity} * @throws IOException * if the specified channel threw an exception during I/O */ // abstract int setBytes(int index, FileChannel in, long position, int length); /** * Fills this buffer with <tt>NUL (0x00)</tt> starting at the specified * absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @param length the number of <tt>NUL</tt>s to write to the buffer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than {@code this.capacity} */ abstract ByteBuf setZero(int index, int length); /** * Writes the specified {@link CharSequence} at the current {@code writerIndex} and increases * the {@code writerIndex} by the written bytes. * * @param index on which the sequence should be written * @param sequence to write * @param charset that should be used. * @return the written number of bytes. * @throws IndexOutOfBoundsException * if {@code this.writableBytes} is not large enough to write the whole sequence */ abstract int setCharSequence(int index, CharSequence sequence, Charset charset); /** * Gets a bool at the current {@code readerIndex} and increases * the {@code readerIndex} by {@code 1} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 1} */ abstract bool readBoolean(); /** * Gets a byte at the current {@code readerIndex} and increases * the {@code readerIndex} by {@code 1} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 1} */ abstract byte readByte(); /** * Gets an unsigned byte at the current {@code readerIndex} and increases * the {@code readerIndex} by {@code 1} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 1} */ abstract short readUnsignedByte(); /** * Gets a 16-bit short integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 2} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 2} */ abstract short readShort(); /** * Gets a 16-bit short integer at the current {@code readerIndex} * in the Little Endian Byte Order and increases the {@code readerIndex} * by {@code 2} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 2} */ abstract short readShortLE(); /** * Gets an unsigned 16-bit short integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 2} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 2} */ abstract int readUnsignedShort(); /** * Gets an unsigned 16-bit short integer at the current {@code readerIndex} * in the Little Endian Byte Order and increases the {@code readerIndex} * by {@code 2} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 2} */ abstract int readUnsignedShortLE(); /** * Gets a 24-bit medium integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 3} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 3} */ abstract int readMedium(); /** * Gets a 24-bit medium integer at the current {@code readerIndex} * in the Little Endian Byte Order and increases the * {@code readerIndex} by {@code 3} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 3} */ abstract int readMediumLE(); /** * Gets an unsigned 24-bit medium integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 3} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 3} */ abstract int readUnsignedMedium(); /** * Gets an unsigned 24-bit medium integer at the current {@code readerIndex} * in the Little Endian Byte Order and increases the {@code readerIndex} * by {@code 3} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 3} */ abstract int readUnsignedMediumLE(); /** * Gets a 32-bit integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 4} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 4} */ abstract int readInt(); /** * Gets a 32-bit integer at the current {@code readerIndex} * in the Little Endian Byte Order and increases the {@code readerIndex} * by {@code 4} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 4} */ abstract int readIntLE(); /** * Gets an unsigned 32-bit integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 4} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 4} */ abstract long readUnsignedInt(); /** * Gets an unsigned 32-bit integer at the current {@code readerIndex} * in the Little Endian Byte Order and increases the {@code readerIndex} * by {@code 4} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 4} */ abstract long readUnsignedIntLE(); /** * Gets a 64-bit integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 8} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 8} */ abstract long readLong(); /** * Gets a 64-bit integer at the current {@code readerIndex} * in the Little Endian Byte Order and increases the {@code readerIndex} * by {@code 8} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 8} */ abstract long readLongLE(); /** * Gets a 2-byte UTF-16 character at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 2} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 2} */ abstract char readChar(); /** * Gets a 32-bit floating point number at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 4} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 4} */ abstract float readFloat(); /** * Gets a 32-bit floating point number at the current {@code readerIndex} * in Little Endian Byte Order and increases the {@code readerIndex} * by {@code 4} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 4} */ float readFloatLE() { return Float.intBitsToFloat(readIntLE()); } /** * Gets a 64-bit floating point number at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 8} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 8} */ abstract double readDouble(); /** * Gets a 64-bit floating point number at the current {@code readerIndex} * in Little Endian Byte Order and increases the {@code readerIndex} * by {@code 8} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 8} */ double readDoubleLE() { return Double.longBitsToDouble(readLongLE()); } /** * Transfers this buffer's data to a newly created buffer starting at * the current {@code readerIndex} and increases the {@code readerIndex} * by the number of the transferred bytes (= {@code length}). * The returned buffer's {@code readerIndex} and {@code writerIndex} are * {@code 0} and {@code length} respectively. * * @param length the number of bytes to transfer * * @return the newly created buffer which contains the transferred bytes * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} */ abstract ByteBuf readBytes(int length); /** * Returns a new slice of this buffer's sub-region starting at the current * {@code readerIndex} and increases the {@code readerIndex} by the size * of the new slice (= {@code length}). * <p> * Also be aware that this method will NOT call {@link #retain()} and so the * reference count will NOT be increased. * * @param length the size of the new slice * * @return the newly created slice * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} */ abstract ByteBuf readSlice(int length); /** * Returns a new retained slice of this buffer's sub-region starting at the current * {@code readerIndex} and increases the {@code readerIndex} by the size * of the new slice (= {@code length}). * <p> * Note that this method returns a {@linkplain #retain() retained} buffer unlike {@link #readSlice(int)}. * This method behaves similarly to {@code readSlice(...).retain()} except that this method may return * a buffer implementation that produces less garbage. * * @param length the size of the new slice * * @return the newly created slice * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} */ abstract ByteBuf readRetainedSlice(int length); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} until the destination becomes * non-writable, and increases the {@code readerIndex} by the number of the * transferred bytes. This method is basically same with * {@link #readBytes(ByteBuf, int, int)}, except that this method * increases the {@code writerIndex} of the destination by the number of * the transferred bytes while {@link #readBytes(ByteBuf, int, int)} * does not. * * @throws IndexOutOfBoundsException * if {@code dst.writableBytes} is greater than * {@code this.readableBytes} */ abstract ByteBuf readBytes(ByteBuf dst); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} and increases the {@code readerIndex} * by the number of the transferred bytes (= {@code length}). This method * is basically same with {@link #readBytes(ByteBuf, int, int)}, * except that this method increases the {@code writerIndex} of the * destination by the number of the transferred bytes (= {@code length}) * while {@link #readBytes(ByteBuf, int, int)} does not. * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} or * if {@code length} is greater than {@code dst.writableBytes} */ abstract ByteBuf readBytes(ByteBuf dst, int length); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} and increases the {@code readerIndex} * by the number of the transferred bytes (= {@code length}). * * @param dstIndex the first index of the destination * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code dstIndex} is less than {@code 0}, * if {@code length} is greater than {@code this.readableBytes}, or * if {@code dstIndex + length} is greater than * {@code dst.capacity} */ abstract ByteBuf readBytes(ByteBuf dst, int dstIndex, int length); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} and increases the {@code readerIndex} * by the number of the transferred bytes (= {@code dst.length}). * * @throws IndexOutOfBoundsException * if {@code dst.length} is greater than {@code this.readableBytes} */ abstract ByteBuf readBytes(byte[] dst); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} and increases the {@code readerIndex} * by the number of the transferred bytes (= {@code length}). * * @param dstIndex the first index of the destination * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code dstIndex} is less than {@code 0}, * if {@code length} is greater than {@code this.readableBytes}, or * if {@code dstIndex + length} is greater than {@code dst.length} */ abstract ByteBuf readBytes(byte[] dst, int dstIndex, int length); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} until the destination's position * reaches its limit, and increases the {@code readerIndex} by the * number of the transferred bytes. * * @throws IndexOutOfBoundsException * if {@code dst.remaining()} is greater than * {@code this.readableBytes} */ abstract ByteBuf readBytes(ByteBuffer dst); /** * Transfers this buffer's data to the specified stream starting at the * current {@code readerIndex}. * * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} * @throws IOException * if the specified stream threw an exception during I/O */ abstract ByteBuf readBytes(OutputStream outStream, int length); /** * Transfers this buffer's data to the specified stream starting at the * current {@code readerIndex}. * * @param length the maximum number of bytes to transfer * * @return the actual number of bytes written out to the specified channel * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} * @throws IOException * if the specified channel threw an exception during I/O */ // abstract int readBytes(GatheringByteChannel out, int length); /** * Gets a {@link CharSequence} with the given length at the current {@code readerIndex} * and increases the {@code readerIndex} by the given length. * * @param length the length to read * @param charset that should be used * @return the sequence * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} */ abstract CharSequence readCharSequence(int length, Charset charset); /** * Transfers this buffer's data starting at the current {@code readerIndex} * to the specified channel starting at the given file position. * This method does not modify the channel's position. * * @param position the file position at which the transfer is to begin * @param length the maximum number of bytes to transfer * * @return the actual number of bytes written out to the specified channel * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} * @throws IOException * if the specified channel threw an exception during I/O */ // abstract int readBytes(FileChannel out, long position, int length); /** * Increases the current {@code readerIndex} by the specified * {@code length} in this buffer. * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} */ abstract ByteBuf skipBytes(int length); /** * Sets the specified bool at the current {@code writerIndex} * and increases the {@code writerIndex} by {@code 1} in this buffer. * If {@code this.writableBytes} is less than {@code 1}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ abstract ByteBuf writeBoolean(bool value); /** * Sets the specified byte at the current {@code writerIndex} * and increases the {@code writerIndex} by {@code 1} in this buffer. * The 24 high-order bits of the specified value are ignored. * If {@code this.writableBytes} is less than {@code 1}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ abstract ByteBuf writeByte(int value); /** * Sets the specified 16-bit short integer at the current * {@code writerIndex} and increases the {@code writerIndex} by {@code 2} * in this buffer. The 16 high-order bits of the specified value are ignored. * If {@code this.writableBytes} is less than {@code 2}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ abstract ByteBuf writeShort(int value); /** * Sets the specified 16-bit short integer in the Little Endian Byte * Order at the current {@code writerIndex} and increases the * {@code writerIndex} by {@code 2} in this buffer. * The 16 high-order bits of the specified value are ignored. * If {@code this.writableBytes} is less than {@code 2}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ abstract ByteBuf writeShortLE(int value); /** * Sets the specified 24-bit medium integer at the current * {@code writerIndex} and increases the {@code writerIndex} by {@code 3} * in this buffer. * If {@code this.writableBytes} is less than {@code 3}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ abstract ByteBuf writeMedium(int value); /** * Sets the specified 24-bit medium integer at the current * {@code writerIndex} in the Little Endian Byte Order and * increases the {@code writerIndex} by {@code 3} in this * buffer. * If {@code this.writableBytes} is less than {@code 3}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ abstract ByteBuf writeMediumLE(int value); /** * Sets the specified 32-bit integer at the current {@code writerIndex} * and increases the {@code writerIndex} by {@code 4} in this buffer. * If {@code this.writableBytes} is less than {@code 4}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ abstract ByteBuf writeInt(int value); /** * Sets the specified 32-bit integer at the current {@code writerIndex} * in the Little Endian Byte Order and increases the {@code writerIndex} * by {@code 4} in this buffer. * If {@code this.writableBytes} is less than {@code 4}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ abstract ByteBuf writeIntLE(int value); /** * Sets the specified 64-bit long integer at the current * {@code writerIndex} and increases the {@code writerIndex} by {@code 8} * in this buffer. * If {@code this.writableBytes} is less than {@code 8}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ abstract ByteBuf writeLong(long value); /** * Sets the specified 64-bit long integer at the current * {@code writerIndex} in the Little Endian Byte Order and * increases the {@code writerIndex} by {@code 8} * in this buffer. * If {@code this.writableBytes} is less than {@code 8}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ abstract ByteBuf writeLongLE(long value); /** * Sets the specified 2-byte UTF-16 character at the current * {@code writerIndex} and increases the {@code writerIndex} by {@code 2} * in this buffer. The 16 high-order bits of the specified value are ignored. * If {@code this.writableBytes} is less than {@code 2}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ abstract ByteBuf writeChar(int value); /** * Sets the specified 32-bit floating point number at the current * {@code writerIndex} and increases the {@code writerIndex} by {@code 4} * in this buffer. * If {@code this.writableBytes} is less than {@code 4}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ abstract ByteBuf writeFloat(float value); /** * Sets the specified 32-bit floating point number at the current * {@code writerIndex} in Little Endian Byte Order and increases * the {@code writerIndex} by {@code 4} in this buffer. * If {@code this.writableBytes} is less than {@code 4}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ ByteBuf writeFloatLE(float value) { return writeIntLE(Float.floatToRawIntBits(value)); } /** * Sets the specified 64-bit floating point number at the current * {@code writerIndex} and increases the {@code writerIndex} by {@code 8} * in this buffer. * If {@code this.writableBytes} is less than {@code 8}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ abstract ByteBuf writeDouble(double value); /** * Sets the specified 64-bit floating point number at the current * {@code writerIndex} in Little Endian Byte Order and increases * the {@code writerIndex} by {@code 8} in this buffer. * If {@code this.writableBytes} is less than {@code 8}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ ByteBuf writeDoubleLE(double value) { return writeLongLE(Double.doubleToRawLongBits(value)); } /** * Transfers the specified source buffer's data to this buffer starting at * the current {@code writerIndex} until the source buffer becomes * unreadable, and increases the {@code writerIndex} by the number of * the transferred bytes. This method is basically same with * {@link #writeBytes(ByteBuf, int, int)}, except that this method * increases the {@code readerIndex} of the source buffer by the number of * the transferred bytes while {@link #writeBytes(ByteBuf, int, int)} * does not. * If {@code this.writableBytes} is less than {@code src.readableBytes}, * {@link #ensureWritable(int)} will be called in an attempt to expand * capacity to accommodate. */ abstract ByteBuf writeBytes(ByteBuf src); /** * Transfers the specified source buffer's data to this buffer starting at * the current {@code writerIndex} and increases the {@code writerIndex} * by the number of the transferred bytes (= {@code length}). This method * is basically same with {@link #writeBytes(ByteBuf, int, int)}, * except that this method increases the {@code readerIndex} of the source * buffer by the number of the transferred bytes (= {@code length}) while * {@link #writeBytes(ByteBuf, int, int)} does not. * If {@code this.writableBytes} is less than {@code length}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. * * @param length the number of bytes to transfer * @throws IndexOutOfBoundsException if {@code length} is greater then {@code src.readableBytes} */ abstract ByteBuf writeBytes(ByteBuf src, int length); /** * Transfers the specified source buffer's data to this buffer starting at * the current {@code writerIndex} and increases the {@code writerIndex} * by the number of the transferred bytes (= {@code length}). * If {@code this.writableBytes} is less than {@code length}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. * * @param srcIndex the first index of the source * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code srcIndex} is less than {@code 0}, or * if {@code srcIndex + length} is greater than {@code src.capacity} */ abstract ByteBuf writeBytes(ByteBuf src, int srcIndex, int length); /** * Transfers the specified source array's data to this buffer starting at * the current {@code writerIndex} and increases the {@code writerIndex} * by the number of the transferred bytes (= {@code src.length}). * If {@code this.writableBytes} is less than {@code src.length}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. */ abstract ByteBuf writeBytes(byte[] src); /** * Transfers the specified source array's data to this buffer starting at * the current {@code writerIndex} and increases the {@code writerIndex} * by the number of the transferred bytes (= {@code length}). * If {@code this.writableBytes} is less than {@code length}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. * * @param srcIndex the first index of the source * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code srcIndex} is less than {@code 0}, or * if {@code srcIndex + length} is greater than {@code src.length} */ abstract ByteBuf writeBytes(byte[] src, int srcIndex, int length); /** * Transfers the specified source buffer's data to this buffer starting at * the current {@code writerIndex} until the source buffer's position * reaches its limit, and increases the {@code writerIndex} by the * number of the transferred bytes. * If {@code this.writableBytes} is less than {@code src.remaining()}, * {@link #ensureWritable(int)} will be called in an attempt to expand * capacity to accommodate. */ abstract ByteBuf writeBytes(ByteBuffer src); /** * Transfers the content of the specified stream to this buffer * starting at the current {@code writerIndex} and increases the * {@code writerIndex} by the number of the transferred bytes. * If {@code this.writableBytes} is less than {@code length}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. * * @param length the number of bytes to transfer * * @return the actual number of bytes read in from the specified stream * * @throws IOException if the specified stream threw an exception during I/O */ abstract int writeBytes(InputStream inStream, int length); /** * Transfers the content of the specified channel to this buffer * starting at the current {@code writerIndex} and increases the * {@code writerIndex} by the number of the transferred bytes. * If {@code this.writableBytes} is less than {@code length}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. * * @param length the maximum number of bytes to transfer * * @return the actual number of bytes read in from the specified channel * * @throws IOException * if the specified channel threw an exception during I/O */ // abstract int writeBytes(ScatteringByteChannel in, int length); /** * Transfers the content of the specified channel starting at the given file position * to this buffer starting at the current {@code writerIndex} and increases the * {@code writerIndex} by the number of the transferred bytes. * This method does not modify the channel's position. * If {@code this.writableBytes} is less than {@code length}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. * * @param position the file position at which the transfer is to begin * @param length the maximum number of bytes to transfer * * @return the actual number of bytes read in from the specified channel * * @throws IOException * if the specified channel threw an exception during I/O */ // abstract int writeBytes(FileChannel in, long position, int length); /** * Fills this buffer with <tt>NUL (0x00)</tt> starting at the current * {@code writerIndex} and increases the {@code writerIndex} by the * specified {@code length}. * If {@code this.writableBytes} is less than {@code length}, {@link #ensureWritable(int)} * will be called in an attempt to expand capacity to accommodate. * * @param length the number of <tt>NUL</tt>s to write to the buffer */ abstract ByteBuf writeZero(int length); /** * Writes the specified {@link CharSequence} at the current {@code writerIndex} and increases * the {@code writerIndex} by the written bytes. * in this buffer. * If {@code this.writableBytes} is not large enough to write the whole sequence, * {@link #ensureWritable(int)} will be called in an attempt to expand capacity to accommodate. * * @param sequence to write * @param charset that should be used * @return the written number of bytes */ abstract int writeCharSequence(CharSequence sequence, Charset charset); /** * Locates the first occurrence of the specified {@code value} in this * buffer. The search takes place from the specified {@code fromIndex} * (inclusive) to the specified {@code toIndex} (exclusive). * <p> * If {@code fromIndex} is greater than {@code toIndex}, the search is * performed in a reversed order. * <p> * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @return the absolute index of the first occurrence if found. * {@code -1} otherwise. */ abstract int indexOf(int fromIndex, int toIndex, byte value); /** * Locates the first occurrence of the specified {@code value} in this * buffer. The search takes place from the current {@code readerIndex} * (inclusive) to the current {@code writerIndex} (exclusive). * <p> * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @return the number of bytes between the current {@code readerIndex} * and the first occurrence if found. {@code -1} otherwise. */ abstract int bytesBefore(byte value); /** * Locates the first occurrence of the specified {@code value} in this * buffer. The search starts from the current {@code readerIndex} * (inclusive) and lasts for the specified {@code length}. * <p> * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @return the number of bytes between the current {@code readerIndex} * and the first occurrence if found. {@code -1} otherwise. * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} */ abstract int bytesBefore(int length, byte value); /** * Locates the first occurrence of the specified {@code value} in this * buffer. The search starts from the specified {@code index} (inclusive) * and lasts for the specified {@code length}. * <p> * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @return the number of bytes between the specified {@code index} * and the first occurrence if found. {@code -1} otherwise. * * @throws IndexOutOfBoundsException * if {@code index + length} is greater than {@code this.capacity} */ abstract int bytesBefore(int index, int length, byte value); /** * Iterates over the readable bytes of this buffer with the specified {@code processor} in ascending order. * * @return {@code -1} if the processor iterated to or beyond the end of the readable bytes. * The last-visited index If the {@link ByteProcessor#process(byte)} returned {@code false}. */ abstract int forEachByte(ByteProcessor processor); /** * Iterates over the specified area of this buffer with the specified {@code processor} in ascending order. * (i.e. {@code index}, {@code (index + 1)}, .. {@code (index + length - 1)}) * * @return {@code -1} if the processor iterated to or beyond the end of the specified area. * The last-visited index If the {@link ByteProcessor#process(byte)} returned {@code false}. */ abstract int forEachByte(int index, int length, ByteProcessor processor); /** * Iterates over the readable bytes of this buffer with the specified {@code processor} in descending order. * * @return {@code -1} if the processor iterated to or beyond the beginning of the readable bytes. * The last-visited index If the {@link ByteProcessor#process(byte)} returned {@code false}. */ abstract int forEachByteDesc(ByteProcessor processor); /** * Iterates over the specified area of this buffer with the specified {@code processor} in descending order. * (i.e. {@code (index + length - 1)}, {@code (index + length - 2)}, ... {@code index}) * * * @return {@code -1} if the processor iterated to or beyond the beginning of the specified area. * The last-visited index If the {@link ByteProcessor#process(byte)} returned {@code false}. */ abstract int forEachByteDesc(int index, int length, ByteProcessor processor); /** * Returns a copy of this buffer's readable bytes. Modifying the content * of the returned buffer or this buffer does not affect each other at all. * This method is identical to {@code buf.copy(buf.readerIndex(), buf.readableBytes())}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. */ abstract ByteBuf copy(); /** * Returns a copy of this buffer's sub-region. Modifying the content of * the returned buffer or this buffer does not affect each other at all. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. */ abstract ByteBuf copy(int index, int length); /** * Returns a slice of this buffer's readable bytes. Modifying the content * of the returned buffer or this buffer affects each other's content * while they maintain separate indexes and marks. This method is * identical to {@code buf.slice(buf.readerIndex(), buf.readableBytes())}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * <p> * Also be aware that this method will NOT call {@link #retain()} and so the * reference count will NOT be increased. */ abstract ByteBuf slice(); /** * Returns a retained slice of this buffer's readable bytes. Modifying the content * of the returned buffer or this buffer affects each other's content * while they maintain separate indexes and marks. This method is * identical to {@code buf.slice(buf.readerIndex(), buf.readableBytes())}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * <p> * Note that this method returns a {@linkplain #retain() retained} buffer unlike {@link #slice()}. * This method behaves similarly to {@code slice().retain()} except that this method may return * a buffer implementation that produces less garbage. */ abstract ByteBuf retainedSlice(); /** * Returns a slice of this buffer's sub-region. Modifying the content of * the returned buffer or this buffer affects each other's content while * they maintain separate indexes and marks. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * <p> * Also be aware that this method will NOT call {@link #retain()} and so the * reference count will NOT be increased. */ abstract ByteBuf slice(int index, int length); /** * Returns a retained slice of this buffer's sub-region. Modifying the content of * the returned buffer or this buffer affects each other's content while * they maintain separate indexes and marks. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * <p> * Note that this method returns a {@linkplain #retain() retained} buffer unlike {@link #slice(int, int)}. * This method behaves similarly to {@code slice(...).retain()} except that this method may return * a buffer implementation that produces less garbage. */ abstract ByteBuf retainedSlice(int index, int length); /** * Returns a buffer which shares the whole region of this buffer. * Modifying the content of the returned buffer or this buffer affects * each other's content while they maintain separate indexes and marks. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * <p> * The reader and writer marks will not be duplicated. Also be aware that this method will * NOT call {@link #retain()} and so the reference count will NOT be increased. * @return A buffer whose readable content is equivalent to the buffer returned by {@link #slice()}. * However this buffer will share the capacity of the underlying buffer, and therefore allows access to all of the * underlying content if necessary. */ abstract ByteBuf duplicate(); /** * Returns a retained buffer which shares the whole region of this buffer. * Modifying the content of the returned buffer or this buffer affects * each other's content while they maintain separate indexes and marks. * This method is identical to {@code buf.slice(0, buf.capacity())}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * <p> * Note that this method returns a {@linkplain #retain() retained} buffer unlike {@link #slice(int, int)}. * This method behaves similarly to {@code duplicate().retain()} except that this method may return * a buffer implementation that produces less garbage. */ abstract ByteBuf retainedDuplicate(); /** * Returns the maximum number of NIO {@link ByteBuffer}s that consist this buffer. Note that {@link #nioBuffers()} * or {@link #nioBuffers(int, int)} might return a less number of {@link ByteBuffer}s. * * @return {@code -1} if this buffer has no underlying {@link ByteBuffer}. * the number of the underlying {@link ByteBuffer}s if this buffer has at least one underlying * {@link ByteBuffer}. Note that this method does not return {@code 0} to avoid confusion. * * @see #nioBuffer() * @see #nioBuffer(int, int) * @see #nioBuffers() * @see #nioBuffers(int, int) */ abstract int nioBufferCount(); /** * Exposes this buffer's readable bytes as an NIO {@link ByteBuffer}. The returned buffer * either share or contains the copied content of this buffer, while changing the position * and limit of the returned NIO buffer does not affect the indexes and marks of this buffer. * This method is identical to {@code buf.nioBuffer(buf.readerIndex(), buf.readableBytes())}. * This method does not modify {@code readerIndex} or {@code writerIndex} of this buffer. * Please note that the returned NIO buffer will not see the changes of this buffer if this buffer * is a dynamic buffer and it adjusted its capacity. * * @throws UnsupportedOperationException * if this buffer cannot create a {@link ByteBuffer} that shares the content with itself * * @see #nioBufferCount() * @see #nioBuffers() * @see #nioBuffers(int, int) */ abstract ByteBuffer nioBuffer(); /** * Exposes this buffer's sub-region as an NIO {@link ByteBuffer}. The returned buffer * either share or contains the copied content of this buffer, while changing the position * and limit of the returned NIO buffer does not affect the indexes and marks of this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of this buffer. * Please note that the returned NIO buffer will not see the changes of this buffer if this buffer * is a dynamic buffer and it adjusted its capacity. * * @throws UnsupportedOperationException * if this buffer cannot create a {@link ByteBuffer} that shares the content with itself * * @see #nioBufferCount() * @see #nioBuffers() * @see #nioBuffers(int, int) */ abstract ByteBuffer nioBuffer(int index, int length); /** * Internal use only: Exposes the internal NIO buffer. */ abstract ByteBuffer internalNioBuffer(int index, int length); /** * Exposes this buffer's readable bytes as an NIO {@link ByteBuffer}'s. The returned buffer * either share or contains the copied content of this buffer, while changing the position * and limit of the returned NIO buffer does not affect the indexes and marks of this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of this buffer. * Please note that the returned NIO buffer will not see the changes of this buffer if this buffer * is a dynamic buffer and it adjusted its capacity. * * * @throws UnsupportedOperationException * if this buffer cannot create a {@link ByteBuffer} that shares the content with itself * * @see #nioBufferCount() * @see #nioBuffer() * @see #nioBuffer(int, int) */ abstract ByteBuffer[] nioBuffers(); /** * Exposes this buffer's bytes as an NIO {@link ByteBuffer}'s for the specified index and length * The returned buffer either share or contains the copied content of this buffer, while changing * the position and limit of the returned NIO buffer does not affect the indexes and marks of this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of this buffer. Please note that the * returned NIO buffer will not see the changes of this buffer if this buffer is a dynamic * buffer and it adjusted its capacity. * * @throws UnsupportedOperationException * if this buffer cannot create a {@link ByteBuffer} that shares the content with itself * * @see #nioBufferCount() * @see #nioBuffer() * @see #nioBuffer(int, int) */ abstract ByteBuffer[] nioBuffers(int index, int length); /** * Returns {@code true} if and only if this buffer has a backing byte array. * If this method returns true, you can safely call {@link #array()} and * {@link #arrayOffset()}. */ abstract bool hasArray(); /** * Returns the backing byte array of this buffer. * * @throws UnsupportedOperationException * if there no accessible backing byte array */ abstract byte[] array(); abstract byte[] getReadableBytes(); /** * Returns the offset of the first byte within the backing byte array of * this buffer. * * @throws UnsupportedOperationException * if there no accessible backing byte array */ abstract int arrayOffset(); /** * Returns {@code true} if and only if this buffer has a reference to the low-level memory address that points * to the backing data. */ abstract bool hasMemoryAddress(); /** * Returns the low-level memory address that point to the first byte of ths backing data. * * @throws UnsupportedOperationException * if this buffer does not support accessing the low-level memory address */ abstract long memoryAddress(); /** * Decodes this buffer's readable bytes into a string with the specified * character set name. This method is identical to * {@code buf.toString(buf.readerIndex(), buf.readableBytes(), charsetName)}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws UnsupportedCharsetException * if the specified character set name is not supported by the * current VM */ abstract string toString(Charset charset); /** * Decodes this buffer's sub-region into a string with the specified * character set. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. */ abstract string toString(int index, int length, Charset charset); /** * Returns a hash code which was calculated from the content of this * buffer. If there's a byte array which is * {@linkplain #equals(Object) equal to} this array, both arrays should * return the same value. */ override abstract size_t toHash() @trusted nothrow; /** * Determines if the content of the specified buffer is identical to the * content of this array. 'Identical' here means: * <ul> * <li>the size of the contents of the two buffers are same and</li> * <li>every single byte of the content of the two buffers are same.</li> * </ul> * Please note that it does not compare {@link #readerIndex()} nor * {@link #writerIndex()}. This method also returns {@code false} for * {@code null} and an object which is not an instance of * {@link ByteBuf} type. */ override abstract bool opEquals(Object obj); /** * Compares the content of the specified buffer to the content of this * buffer. Comparison is performed in the same manner with the string * comparison functions of various languages such as {@code strcmp}, * {@code memcmp} and {@link string#compareTo(string)}. */ // override abstract int compareTo(ByteBuf buffer); /** * Returns the string representation of this buffer. This method does not * necessarily return the whole content of the buffer but returns * the values of the key properties such as {@link #readerIndex()}, * {@link #writerIndex()} and {@link #capacity()}. */ override abstract string toString(); abstract ByteBuf retain(int increment); abstract ByteBuf retain(); abstract ByteBuf touch(); abstract ByteBuf touch(Object hint); /** * Used internally by {@link AbstractByteBuf#ensureAccessible()} to try to guard * against using the buffer after it was released (best-effort). */ bool isAccessible() { return refCnt() != 0; } }
D
module test; import std.process; import std.file : rmdirRecurse; import Path = tango.io.Path; import mambo.core._; int main () { return TestRunner().run; } struct TestRunner { private string wd; int run () { int result = 0; auto matrix = setup(); activate(matrix.clangs.first); build(); foreach (const clang ; matrix.clangs) { activate(clang); println("Testing with libclang version ", clang.version_); result += test(); } return result; } string workingDirectory () { import tango.sys.Environment; if (wd.any) return wd; return wd = Environment.cwd.assumeUnique; } auto setup () { auto matrix = ClangMatrix(workingDirectory, clangBasePath); matrix.downloadAll; matrix.extractAll; return matrix; } string clangBasePath () { return Path.join(workingDirectory, "clangs").assumeUnique; } void activate (const Clang clang) { auto src = Path.join(workingDirectory, clang.versionedLibclang); auto dest = Path.join(workingDirectory, clang.libclang); if (Path.exists(dest)) Path.remove(dest); Path.copy(src, dest); } int test () { auto result = execute("cucumber"); if (result.status != 0) println(result.output); return result.status; } void build () { auto result = executeShell("dub build"); if (result.status != 0) { println(result.output); throw new Exception("Failed to build DStep"); } } } struct Clang { string version_; string baseUrl; string filename; version (linux) { enum extension = ".so"; enum prefix = "lib"; } else version (OSX) { enum extension = ".dylib"; enum prefix = "lib"; } else version (Windows) { enum extension = ".dll"; enum prefix = ""; } else version (FreeBSD) { enum extension = ".so"; enum prefix = "lib"; } else static assert(false, "Unsupported platform"); string libclang () const { return Clang.prefix ~ "clang" ~ Clang.extension; } string versionedLibclang () const { return Clang.prefix ~ "clang-" ~ version_ ~ Clang.extension; } } struct ClangMatrix { import Path = tango.io.Path; private { string basePath; string workingDirectory; string clangPath_; immutable Clang[] clangs; } this (string workingDirectory, string basePath) { clangs = getClangs(); this.workingDirectory = workingDirectory; this.basePath = basePath; } void downloadAll () { foreach (clang ; ClangMatrix.clangs) { if (libclangExists(clang)) continue; println("Downloading clang ", clang.version_); Path.createPath(basePath); download(clang); } } void extractAll () { foreach (clang ; ClangMatrix.clangs) { if (libclangExists(clang)) continue; println("Extracting clang ", clang.version_); extractArchive(clang); extractLibclang(clang); clean(); } } private: bool libclangExists (const ref Clang clang) { auto libclangPath = Path.join(workingDirectory, clang.versionedLibclang); return Path.exists(libclangPath); } void download (const ref Clang clang) { auto url = clang.baseUrl ~ clang.filename; auto dest = archivePath(clang.filename); if (!Path.exists(dest)) Http.download(url, dest); } void extractArchive (const ref Clang clang) { auto src = archivePath(clang.filename); auto dest = clangPath(); Path.createPath(dest); auto result = execute(["tar", "--strip-components=1", "-C", dest, "-xf", src]); if (result.status != 0) throw new ProcessException("Failed to extract archive"); } string archivePath (string filename) { return Path.join(basePath, filename).assumeUnique; } string clangPath () { if (clangPath_.any) return clangPath_; return clangPath_ = Path.join(basePath, "clang").assumeUnique; } void extractLibclang (const ref Clang clang) { auto src = Path.join(clangPath, "lib", clang.libclang); auto dest = Path.join(workingDirectory, clang.versionedLibclang); Path.copy(src, dest); } void clean () { rmdirRecurse(clangPath); } immutable(Clang[]) getClangs () { version (FreeBSD) { version (D_LP64) return [ // Clang("3.7.1", "http://llvm.org/releases/3.7.1/", "clang+llvm-3.7.1-amd64-unknown-freebsd10.tar.xz"), // Clang("3.7.0", "http://llvm.org/releases/3.7.0/", "clang+llvm-3.7.0-amd64-unknown-freebsd10.tar.xz"), // Clang("3.6.2", "http://llvm.org/releases/3.6.2/", "clang+llvm-3.6.2-amd64-unknown-freebsd10.tar.xz"), // Clang("3.6.1", "http://llvm.org/releases/3.6.1/", "clang+llvm-3.6.1-amd64-unknown-freebsd10.tar.xz"), // Clang("3.6.0", "http://llvm.org/releases/3.6.0/", "clang+llvm-3.6.0-amd64-unknown-freebsd10.tar.xz"), // Clang("3.5.0", "http://llvm.org/releases/3.5.0/", "clang+llvm-3.5.0-amd64-unknown-freebsd10.tar.xz"), Clang("3.4", "http://llvm.org/releases/3.4/", "clang+llvm-3.4-amd64-unknown-freebsd9.2.tar.xz"), Clang("3.3", "http://llvm.org/releases/3.3/", "clang+llvm-3.3-amd64-freebsd9.tar.xz"), Clang("3.2", "http://llvm.org/releases/3.2/", "clang+llvm-3.2-amd64-freebsd9.tar.gz"), Clang("3.1", "http://llvm.org/releases/3.1/", "clang+llvm-3.1-amd64-freebsd9.tar.bz2") ]; else return [ // Clang("3.7.1", "http://llvm.org/releases/3.7.1/", "clang+llvm-3.7.1-i386-unknown-freebsd10.tar.xz"), // Clang("3.7.0", "http://llvm.org/releases/3.7.1/", "clang+llvm-3.7.0-i386-unknown-freebsd10.tar.xz"), // Clang("3.6.2", "http://llvm.org/releases/3.6.2/", "clang+llvm-3.6.2-i386-unknown-freebsd10.tar.xz"), // Clang("3.6.1", "http://llvm.org/releases/3.6.1/", "clang+llvm-3.6.1-i386-unknown-freebsd10.tar.xz"), // Clang("3.6.0", "http://llvm.org/releases/3.6.0/", "clang+llvm-3.6.0-i386-unknown-freebsd10.tar.xz"), // Clang("3.5.0", "http://llvm.org/releases/3.5.0/", "clang+llvm-3.5.0-i386-unknown-freebsd10.tar.xz"), Clang("3.4", "http://llvm.org/releases/3.4/", "clang+llvm-3.4-i386-unknown-freebsd9.2.tar.xz"), Clang("3.3", "http://llvm.org/releases/3.3/", "clang+llvm-3.3-i386-freebsd9.tar.xz"), Clang("3.2", "http://llvm.org/releases/3.2/", "clang+llvm-3.2-i386-freebsd9.tar.gz"), Clang("3.1", "http://llvm.org/releases/3.1/", "clang+llvm-3.1-i386-freebsd9.tar.bz2") ]; } else version (linux) { if (System.isTravis) { return [ // Clang("3.5.1", "http://llvm.org/releases/3.5.1/", "clang+llvm-3.5.1-x86_64-linux-gnu.tar.xz"), // Clang("3.5.0", "http://llvm.org/releases/3.5.0/", "clang+llvm-3.5.0-x86_64-linux-gnu-ubuntu-14.04.tar.xz"), Clang("3.4.2", "http://llvm.org/releases/3.4.2/", "clang+llvm-3.4.2-x86_64-unknown-ubuntu12.04.xz"), Clang("3.4.1", "http://llvm.org/releases/3.4.1/", "clang+llvm-3.4.1-x86_64-unknown-ubuntu12.04.tar.xz"), Clang("3.4", "http://llvm.org/releases/3.4/", "clang+llvm-3.4-x86_64-unknown-ubuntu12.04.tar.xz"), Clang("3.3", "http://llvm.org/releases/3.3/", "clang+llvm-3.3-amd64-Ubuntu-12.04.2.tar.gz"), Clang("3.2", "http://llvm.org/releases/3.2/", "clang+llvm-3.2-x86_64-linux-ubuntu-12.04.tar.gz"), Clang("3.1", "http://llvm.org/releases/3.1/", "clang+llvm-3.1-x86_64-linux-ubuntu_12.04.tar.gz") ]; } else if (System.isUbuntu) { version (D_LP64) return [ Clang("3.5.1", "http://llvm.org/releases/3.5.1/", "clang+llvm-3.5.1-x86_64-linux-gnu.tar.xz"), Clang("3.5.0", "http://llvm.org/releases/3.5.0/", "clang+llvm-3.5.0-x86_64-linux-gnu-ubuntu-14.04.tar.xz"), Clang("3.4.2", "http://llvm.org/releases/3.4.2/", "clang+llvm-3.4.2-x86_64-unknown-ubuntu12.04.xz"), Clang("3.4.1", "http://llvm.org/releases/3.4.1/", "clang+llvm-3.4.1-x86_64-unknown-ubuntu12.04.tar.xz"), Clang("3.4", "http://llvm.org/releases/3.4/", "clang+llvm-3.4-x86_64-unknown-ubuntu12.04.tar.xz"), Clang("3.3", "http://llvm.org/releases/3.3/", "clang+llvm-3.3-amd64-Ubuntu-12.04.2.tar.gz"), Clang("3.2", "http://llvm.org/releases/3.2/", "clang+llvm-3.2-x86_64-linux-ubuntu-12.04.tar.gz"), Clang("3.1", "http://llvm.org/releases/3.1/", "clang+llvm-3.1-x86_64-linux-ubuntu_12.04.tar.gz") ]; else return [ Clang("3.2", "http://llvm.org/releases/3.2/", "clang+llvm-3.2-x86-linux-ubuntu-12.04.tar.gz"), Clang("3.1", "http://llvm.org/releases/3.1/", "clang+llvm-3.1-x86-linux-ubuntu_12.04.tar.gz") ]; } else if (System.isDebian) { version (D_LP64) return [ Clang("3.3", "http://llvm.org/releases/3.3/", "clang+llvm-3.3-amd64-debian6.tar.bz2") ]; else return [ Clang("3.3", "http://llvm.org/releases/3.3/", "clang+llvm-3.3-i386-debian6.tar.bz2"), ]; } else if (System.isFedora) { version (D_LP64) return [ Clang("3.5.1", "http://llvm.org/releases/3.5.1/", "clang+llvm-3.5.1-x86_64-fedora20.tar.xz"), Clang("3.5.0", "http://llvm.org/releases/3.5.0/", "clang+llvm-3.5.0-x86_64-fedora20.tar.xz"), Clang("3.4", "http://llvm.org/releases/3.4/", "clang+llvm-3.4-x86_64-fedora19.tar.gz"), Clang("3.3", "http://llvm.org/releases/3.3/", "clang+llvm-3.3-x86_64-fedora18.tar.bz2") ]; else return [ Clang("3.5.1", "http://llvm.org/releases/3.5.1/", "clang+llvm-3.5.1-i686-fedora20.tar.xz"), Clang("3.5.0", "http://llvm.org/releases/3.5.0/", "clang+llvm-3.5.0-i686-fedora20.tar.xz"), Clang("3.4.2", "http://llvm.org/releases/3.4.2/", "clang+llvm-3.4.2-i686-fedora20.xz"), Clang("3.4.1", "http://llvm.org/releases/3.4.1/", "clang+llvm-3.4.1-i686-fedora20.tar.xz"), Clang("3.4", "http://llvm.org/releases/3.4/", "clang+llvm-3.4-i686-fedora19.tar.gz"), Clang("3.3", "http://llvm.org/releases/3.3/", "clang+llvm-3.3-i686-fedora18.tar.bz2") ]; } else throw new Exception("Current Linux distribution '" ~ System.update ~ "' is not supported"); } else version (OSX) { version (D_LP64) { if (System.isTravis) return [ Clang("3.7.0", "http://llvm.org/releases/3.7.0/", "clang+llvm-3.7.0-x86_64-apple-darwin.tar.xz"), Clang("3.6.2", "http://llvm.org/releases/3.6.2/", "clang+llvm-3.6.2-x86_64-apple-darwin.tar.xz"), Clang("3.6.1", "http://llvm.org/releases/3.6.1/", "clang+llvm-3.6.1-x86_64-apple-darwin.tar.xz"), Clang("3.6.0", "http://llvm.org/releases/3.6.0/", "clang+llvm-3.6.0-x86_64-apple-darwin.tar.xz"), Clang("3.5.0", "http://llvm.org/releases/3.5.0/", "clang+llvm-3.5.0-macosx-apple-darwin.tar.xz"), // Clang("3.4.2", "http://llvm.org/releases/3.4.2/", "clang+llvm-3.4.2-x86_64-apple-darwin10.9.xz"), // Clang("3.4.1", "http://llvm.org/releases/3.4.1/", "clang+llvm-3.4.1-x86_64-apple-darwin10.9.tar.xz"), // Clang("3.4", "http://llvm.org/releases/3.4/", "clang+llvm-3.4-x86_64-apple-darwin10.9.tar.gz"), Clang("3.3", "http://llvm.org/releases/3.3/", "clang+llvm-3.3-x86_64-apple-darwin12.tar.gz"), Clang("3.2", "http://llvm.org/releases/3.2/", "clang+llvm-3.2-x86_64-apple-darwin11.tar.gz"), Clang("3.1", "http://llvm.org/releases/3.1/", "clang+llvm-3.1-x86_64-apple-darwin11.tar.gz") ]; else return [ Clang("3.7.0", "http://llvm.org/releases/3.7.0/", "clang+llvm-3.7.0-x86_64-apple-darwin.tar.xz"), Clang("3.6.2", "http://llvm.org/releases/3.6.2/", "clang+llvm-3.6.2-x86_64-apple-darwin.tar.xz"), Clang("3.6.1", "http://llvm.org/releases/3.6.1/", "clang+llvm-3.6.1-x86_64-apple-darwin.tar.xz"), Clang("3.6.0", "http://llvm.org/releases/3.6.0/", "clang+llvm-3.6.0-x86_64-apple-darwin.tar.xz"), Clang("3.5.0", "http://llvm.org/releases/3.5.0/", "clang+llvm-3.5.0-macosx-apple-darwin.tar.xz"), Clang("3.4.2", "http://llvm.org/releases/3.4.2/", "clang+llvm-3.4.2-x86_64-apple-darwin10.9.xz"), // Clang("3.4.1", "http://llvm.org/releases/3.4.1/", "clang+llvm-3.4.1-x86_64-apple-darwin10.9.tar.xz"), // Clang("3.4", "http://llvm.org/releases/3.4/", "clang+llvm-3.4-x86_64-apple-darwin10.9.tar.gz"), Clang("3.3", "http://llvm.org/releases/3.3/", "clang+llvm-3.3-x86_64-apple-darwin12.tar.gz"), Clang("3.2", "http://llvm.org/releases/3.2/", "clang+llvm-3.2-x86_64-apple-darwin11.tar.gz"), Clang("3.1", "http://llvm.org/releases/3.1/", "clang+llvm-3.1-x86_64-apple-darwin11.tar.gz") ]; } else static assert(false, "Only 64bit versions of OS X are supported"); } else version (Windows) { return [ Clang("3.5.0", "http://llvm.org/releases/3.5.0/", "LLVM-3.5.0-win32.exe"), Clang("3.4.1", "http://llvm.org/releases/3.4.1/", "LLVM-3.4.1-win32.exe"), Clang("3.4", "http://llvm.org/releases/3.4/", "LLVM-3.4-win32.exe") ]; } else static assert(false, "Unsupported platform"); } } struct System { static: version (D_LP64) bool isTravis () { return environment.get("TRAVIS", "false") == "true"; } else bool isTravis () { return false; } version (linux): import core.sys.posix.sys.utsname; private { utsname data_; string update_; string nodename_; } bool isFedora () { return nodename.contains("fedora"); } bool isUbuntu () { return nodename.contains("ubuntu"); } bool isDebian () { return nodename.contains("debian"); } private utsname data() { import std.exception; if (data_ != data_.init) return data_; errnoEnforce(!uname(&data_)); return data_; } string update () { if (update_.any) return update_; return update_ = data.update.ptr.toString.toLower; } string nodename () { if (nodename_.any) return nodename_; return nodename_ = data.nodename.ptr.toString.toLower; } } struct Http { import tango.io.device.File; import tango.io.model.IConduit; import tango.net.device.Socket; import tango.net.http.HttpGet; import tango.net.http.HttpConst; static: void download (string url, string destination, float timeout = 30f, ProgressHandler progress = new CliProgressHandler) { auto data = download(url, timeout, progress); writeFile(data, destination); } void[] download (string url, float timeout = 30f, ProgressHandler progress = new CliProgressHandler) { scope page = new HttpGet(url); page.setTimeout(timeout); auto buffer = page.open; checkPageStatus(page, url); auto contentLength = page.getResponseHeaders.getInt(HttpHeader.ContentLength); enum width = 40; int bytesLeft = contentLength; int chunkSize = bytesLeft / width; progress.start(contentLength, chunkSize, width); while (bytesLeft > 0) { buffer.load(chunkSize > bytesLeft ? bytesLeft : chunkSize); bytesLeft -= chunkSize; progress(bytesLeft); } progress.end(); return buffer.slice; } bool exists (string url) { scope resource = new HttpGet(url); resource.open; return resource.isResponseOK; } private: void checkPageStatus (HttpGet page, string url) { import tango.core.Exception; if (page.getStatus == 404) throw new IOException(format(`The resource with URL "{}" could not be found.`, url)); else if (!page.isResponseOK) throw new IOException(format(`An unexpected error occurred. The resource "{}" responded with the message "{}" and the status code {}.`, url, page.getResponse.getReason, page.getResponse.getStatus)); } void writeFile (void[] data, string filename) { scope file = new File(filename, File.WriteCreate); file.write(data); } } abstract class ProgressHandler { void start (int length, int chunkSize, int width); void opCall (int bytesLeft); void end (); } class CliProgressHandler : ProgressHandler { private { int num; int width; int chunkSize; int contentLength; version (Posix) enum { clearLine = "\033[1K", // clear backwards saveCursor = "\0337", restoreCursor = "\0338" } else enum { clearLine = "\r", saveCursor = "", restoreCursor = "" } } override void start (int contentLength, int chunkSize, int width) { this.chunkSize = chunkSize; this.contentLength = contentLength; this.width = width; this.num = width; print(saveCursor); } override void opCall (int bytesLeft) { int i = 0; print(clearLine ~ restoreCursor ~ saveCursor); print("["); for ( ; i < (width - num); i++) print("="); print(">"); for ( ; i < width; i++) print(" "); print("]"); print(format(" {}/{} KB", (contentLength - bytesLeft) / 1024, contentLength / 1024).assumeUnique); num--; } override void end () { println(restoreCursor); println(); } }
D
/Users/matsuoka/projects/rust/mandelbrot/conrod_mandelbrot/target/debug/build/rayon-b350abe044ebf374/build_script_build-b350abe044ebf374: /Users/matsuoka/.cargo/registry/src/github.com-1ecc6299db9ec823/rayon-1.0.2/build.rs /Users/matsuoka/projects/rust/mandelbrot/conrod_mandelbrot/target/debug/build/rayon-b350abe044ebf374/build_script_build-b350abe044ebf374.d: /Users/matsuoka/.cargo/registry/src/github.com-1ecc6299db9ec823/rayon-1.0.2/build.rs /Users/matsuoka/.cargo/registry/src/github.com-1ecc6299db9ec823/rayon-1.0.2/build.rs:
D
/** * Consoleur: a package for interaction with character-oriented terminal emulators * * Copyright: Maxim Freck, 2017. * Authors: Maxim Freck <maxim@freck.pp.ru> * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0) */ module consoleur.input.key; version(Posix) { import consoleur.core; import consoleur.core.termparam; import consoleur.terminfo; public import consoleur.input.types; import consoleur.input.util; /******* * Synchronously reads Key from STDIN. * Returns: Key structure * * Params: * escDelay = The escape key detection delay. The default value is -1, * this means that the function always waits for two \x1b * characters from STDIN. */ Key getKeyPressed(int escDelay = -1) @safe { immutable tparam = setTermparam(Term.quiet|Term.raw); return processKeyPressed(escDelay); } /******* * Asynchronously reads Key from STDIN. * Returns: Key structure or Command.empty if STDIN is empty * * Params: * escDelay = The escape key detection delay. The default value is -1, * this means that the function always waits for two \x1b * characters from STDIN. */ Key peekKeyPressed(int escDelay = -1) @safe { immutable tparam = setTermparam(Term.quiet|Term.raw|Term.async); return processKeyPressed(escDelay); } private Key processKeyPressed(int escDelay) @safe { ubyte b; if (!popStdin(b)) { return Key(KeyType.COMMAND, KeyValue(Command.empty)); } if (b == 0x1b) { if (escDelay == -1) { immutable tparam = setTermparam(Term.quiet|Term.raw); popStdin(b); } else { immutable tparam = setTermparam(Term.quiet|Term.raw|Term.async, cast(ubyte)(escDelay)); if (!popStdin(b)) return Key(KeyType.COMMAND, KeyValue(Command.escape)); } pushStdin(b); return readCommandSequence(); } version(WithSuperKey) { if (b == 0x18) { return readSuperKey(); } } if (b > 128) { return readUtf8Char(Key(KeyType.UTF8, KeyValue(cast(ubyte[6])[b,0,0,0,0,0]))); } if (b < 0x20 || b == 0x7f) { return Key(KeyType.COMMAND, KeyValue(cast(Command)b)); } return Key(KeyType.ASCII, KeyValue(cast(char)b)); } private Key readCommandSequence() @safe { ubyte b; popStdin(b); if (b == 0x1b) { auto tparam = setTermparam(Term.quiet|Term.raw|Term.async, 0); if (!popStdin(b)) { //C0 return Key(KeyType.COMMAND, KeyValue(cast(Command)0x1b)); } if (b == 0x5b) { //alt + CSI tparam.restoreBack(); auto key = mapSequence(readCsiSequence()); key.modifier |= KeyModifier.alt; return key; } if (b == 0x4f) { //alt + SS3 tparam.restoreBack(); auto key = mapSequence(readSs3Sequence()); key.modifier |= KeyModifier.alt; return key; } pushStdin(b); return Key(KeyType.COMMAND, KeyValue(cast(Command)0x1b)); } if (b == 0x5b) { return mapSequence(readCsiSequence()); } if (b == 0x4f) { return mapSequence(readSs3Sequence()); } if (b < 0x20 || b == 0x7f) { return Key(KeyType.COMMAND, KeyValue(cast(Command)b), KeyModifier.alt); } if (b < 128) { return Key(KeyType.ASCII, KeyValue(b), KeyModifier.alt); } if (b > 128) { return readUtf8Char(Key(KeyType.UTF8, KeyValue(cast(ubyte[6])[b,0,0,0,0,0]), KeyModifier.alt)); } return Key(KeyType.COMMAND, KeyValue(cast(Command)-1)); } private Key mapSequence(string sequence) @safe { auto cmd = (sequence in keyMap); if (cmd is null) return Key(KeyType.RAW, KeyValue(sequence)); return *cmd; } private string readCsiSequence() @safe { string csi; ubyte b; while (popStdin(b)) { csi~=b; if (b == 0x24 || (b >= 0x40 && b <= 0x7e && b != 0x5b)) break; } return "\x1b["~csi; } private string readSs3Sequence() @safe { string ss3; ubyte b; while (popStdin(b)) { ss3 ~= b; if (b < 0x30 || b > 0x39) break; } return "\x1bO"~ss3; } version(WithSuperKey) { private Key readSuperKey() @safe { immutable tparam = setTermparam(Term.quiet|Term.raw|Term.async, 0); int modifier = KeyModifier.supr; ubyte b1, b2, b3; if (!popStdin(b1)) return Key(KeyType.COMMAND, KeyValue(cast(Command)0x18)); if (b1 != 0x40) { pushStdin(b1); return Key(KeyType.COMMAND, KeyValue(cast(Command)0x18)); } if (!popStdin(b2)) { pushStdin(b1); return Key(KeyType.COMMAND, KeyValue(cast(Command)0x18)); } if (b2 != 0x73) { pushStdin(b1); pushStdin(b2); return Key(KeyType.COMMAND, KeyValue(cast(Command)0x18)); } if (!popStdin(b3)) { pushStdin(b1); pushStdin(b2); return Key(KeyType.COMMAND, KeyValue(cast(Command)0x18)); } if (b3 == 0x1b) { if (!popStdin(b3)) return Key(KeyType.COMMAND, KeyValue(cast(Command)b3), modifier); modifier |= KeyModifier.alt; } if (b3 < 0x20 || b3 == 0x7f) { return Key(KeyType.COMMAND, KeyValue(cast(Command)b3), modifier); } if (b3 > 128) { return readUtf8Char(Key(KeyType.UTF8, KeyValue(cast(ubyte[6])[b3,0,0,0,0,0]), modifier)); } return Key(KeyType.ASCII, KeyValue(cast(char)b3), modifier); } } private Key readUtf8Char(Key ch) @safe { foreach (size_t n; 1 .. ch.content.utf[0].codepointLength) { popStdin(ch.content.utf[n]); } return ch; } // ubyte codepointLength(ubyte src) @safe // { // if ((src & 0b11111100) == 0b11111100) return 6; // if ((src & 0b11111000) == 0b11111000) return 5; // if ((src & 0b11110000) == 0b11110000) return 4; // if ((src & 0b11100000) == 0b11100000) return 3; // if ((src & 0b11000000) == 0b11000000) return 2; // if ((src & 0b10000000) == 0b10000000) return 1; // return 0; // } private static Key[string] keyMap; shared static this() { addCommonKeys(); version (WithSuperKey) addSuperKeys(); } private void addCommonKeys() { import std.process: environment, get; // Relying on the terminfo database is dangerous: the environment variable $TERM can often be set incorrectly (e.g. // during PuTTY sessions), and many escape sequences are not listed in the database file. Therefore, we simply // collect all the most common sequences. keyMap = [ "\x1b[[A": Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.none), //Linux "\x1b[[B": Key(KeyType.COMMAND, KeyValue(Command.keyF2), KeyModifier.none), //Linux "\x1b[[C": Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.none), //Linux "\x1b[[D": Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.none), //Linux "\x1b[[E": Key(KeyType.COMMAND, KeyValue(Command.keyF5), KeyModifier.none), //Linux "\x1b[1;2A": Key(KeyType.COMMAND, KeyValue(Command.keyUp), KeyModifier.shift), //Konsole "\x1b[1;2B": Key(KeyType.COMMAND, KeyValue(Command.keyDown), KeyModifier.shift), //Konsole "\x1b[1;2C": Key(KeyType.COMMAND, KeyValue(Command.keyRight), KeyModifier.shift), //Konsole, Xterm "\x1b[1;2D": Key(KeyType.COMMAND, KeyValue(Command.keyLeft), KeyModifier.shift), //Konsole, Xterm "\x1b[1;2F": Key(KeyType.COMMAND, KeyValue(Command.keyEnd), KeyModifier.shift), //Konsole, Xterm "\x1b[1;2H": Key(KeyType.COMMAND, KeyValue(Command.keyHome), KeyModifier.shift), //Konsole, Xterm "\x1b[1;2P": Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.shift), //Xterm "\x1b[1;2Q": Key(KeyType.COMMAND, KeyValue(Command.keyF2), KeyModifier.shift), //Xterm "\x1b[1;2R": Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.shift), //Xterm "\x1b[1;2S": Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.shift), //Xterm "\x1b[1;3A": Key(KeyType.COMMAND, KeyValue(Command.keyUp), KeyModifier.alt), //Konsole, Xterm "\x1b[1;3B": Key(KeyType.COMMAND, KeyValue(Command.keyDown), KeyModifier.alt), //Konsole, Xterm "\x1b[1;3C": Key(KeyType.COMMAND, KeyValue(Command.keyRight), KeyModifier.alt), //Konsole, Xterm "\x1b[1;3D": Key(KeyType.COMMAND, KeyValue(Command.keyLeft), KeyModifier.alt), //Konsole, Xterm "\x1b[1;3E": Key(KeyType.COMMAND, KeyValue(Command.keyB2), KeyModifier.alt), //Xterm "\x1b[1;3F": Key(KeyType.COMMAND, KeyValue(Command.keyEnd), KeyModifier.alt), //Konsole, Xterm "\x1b[1;3H": Key(KeyType.COMMAND, KeyValue(Command.keyHome), KeyModifier.alt), //Konsole, Xterm "\x1b[1;3P": Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.alt), //Xterm "\x1b[1;3Q": Key(KeyType.COMMAND, KeyValue(Command.keyF2), KeyModifier.alt), //Xterm "\x1b[1;3R": Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.alt), //Xterm "\x1b[1;3S": Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.alt), //Xterm "\x1b[1;4A": Key(KeyType.COMMAND, KeyValue(Command.keyUp), KeyModifier.shift|KeyModifier.alt), //Konsole, Xterm "\x1b[1;4B": Key(KeyType.COMMAND, KeyValue(Command.keyDown), KeyModifier.shift|KeyModifier.alt), //Konsole, Xterm "\x1b[1;4C": Key(KeyType.COMMAND, KeyValue(Command.keyRight), KeyModifier.shift|KeyModifier.alt), //Konsole, Xterm "\x1b[1;4D": Key(KeyType.COMMAND, KeyValue(Command.keyLeft), KeyModifier.shift|KeyModifier.alt), //Konsole, Xterm "\x1b[1;4E": Key(KeyType.COMMAND, KeyValue(Command.keyB2), KeyModifier.shift|KeyModifier.alt), //Xterm "\x1b[1;4F": Key(KeyType.COMMAND, KeyValue(Command.keyEnd), KeyModifier.shift|KeyModifier.alt), //Konsole, Xterm "\x1b[1;4H": Key(KeyType.COMMAND, KeyValue(Command.keyHome), KeyModifier.shift|KeyModifier.alt), //Konsole, Xterm "\x1b[1;4P": Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.shift|KeyModifier.alt), //Xterm "\x1b[1;4R": Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.shift|KeyModifier.alt), //Xterm "\x1b[1;4S": Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.shift|KeyModifier.alt), //Xterm "\x1b[1;5A": Key(KeyType.COMMAND, KeyValue(Command.keyUp), KeyModifier.control), //Konsole, Xterm "\x1b[1;5B": Key(KeyType.COMMAND, KeyValue(Command.keyDown), KeyModifier.control), //Konsole, Xterm "\x1b[1;5C": Key(KeyType.COMMAND, KeyValue(Command.keyRight), KeyModifier.control), //Konsole, Xterm "\x1b[1;5D": Key(KeyType.COMMAND, KeyValue(Command.keyLeft), KeyModifier.control), //Konsole, Xterm "\x1b[1;5E": Key(KeyType.COMMAND, KeyValue(Command.keyB2), KeyModifier.control), //Xterm "\x1b[1;5F": Key(KeyType.COMMAND, KeyValue(Command.keyEnd), KeyModifier.control), //Konsole, Xterm "\x1b[1;5H": Key(KeyType.COMMAND, KeyValue(Command.keyHome), KeyModifier.control), //Konsole, Xterm "\x1b[1;5P": Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.control), //Xterm "\x1b[1;5Q": Key(KeyType.COMMAND, KeyValue(Command.keyF2), KeyModifier.control), //Xterm "\x1b[1;5R": Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.control), //Xterm "\x1b[1;5S": Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.control), //Xterm "\x1b[1;6A": Key(KeyType.COMMAND, KeyValue(Command.keyUp), KeyModifier.shift|KeyModifier.control), //Konsole, Xterm "\x1b[1;6B": Key(KeyType.COMMAND, KeyValue(Command.keyDown), KeyModifier.shift|KeyModifier.control), //Konsole, Xterm "\x1b[1;6C": Key(KeyType.COMMAND, KeyValue(Command.keyRight), KeyModifier.shift|KeyModifier.control), //Xterm "\x1b[1;6D": Key(KeyType.COMMAND, KeyValue(Command.keyLeft), KeyModifier.shift|KeyModifier.control), //Xterm "\x1b[1;6E": Key(KeyType.COMMAND, KeyValue(Command.keyB2), KeyModifier.shift|KeyModifier.control), //Xterm "\x1b[1;6F": Key(KeyType.COMMAND, KeyValue(Command.keyEnd), KeyModifier.shift|KeyModifier.control), //Konsole, Xterm "\x1b[1;6H": Key(KeyType.COMMAND, KeyValue(Command.keyHome), KeyModifier.shift|KeyModifier.control), //Konsole, Xterm "\x1b[1;6P": Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.shift|KeyModifier.control), //Xterm "\x1b[1;6P": Key(KeyType.COMMAND, KeyValue(Command.keyF2), KeyModifier.shift|KeyModifier.control), //Xterm "\x1b[1;6R": Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.shift|KeyModifier.control), //Xterm "\x1b[1;6S": Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.shift|KeyModifier.control), //Xterm "\x1b[1;7A": Key(KeyType.COMMAND, KeyValue(Command.keyUp), KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[1;7B": Key(KeyType.COMMAND, KeyValue(Command.keyDown), KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[1;7C": Key(KeyType.COMMAND, KeyValue(Command.keyRight), KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[1;7D": Key(KeyType.COMMAND, KeyValue(Command.keyLeft), KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[1;7E": Key(KeyType.COMMAND, KeyValue(Command.keyB2), KeyModifier.alt|KeyModifier.control), //Xterm "\x1b[1;7F": Key(KeyType.COMMAND, KeyValue(Command.keyEnd), KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[1;7H": Key(KeyType.COMMAND, KeyValue(Command.keyHome), KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[1;8A": Key(KeyType.COMMAND, KeyValue(Command.keyUp), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[1;8B": Key(KeyType.COMMAND, KeyValue(Command.keyDown), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[1;8C": Key(KeyType.COMMAND, KeyValue(Command.keyRight), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[1;8D": Key(KeyType.COMMAND, KeyValue(Command.keyLeft), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[1;8F": Key(KeyType.COMMAND, KeyValue(Command.keyEnd), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[1;8H": Key(KeyType.COMMAND, KeyValue(Command.keyHome), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[1;8P": Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Xterm "\x1b[1;8Q": Key(KeyType.COMMAND, KeyValue(Command.keyF2), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Xterm "\x1b[1;8R": Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Xterm "\x1b[1;8S": Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Xterm "\x1b[1~": Key(KeyType.COMMAND, KeyValue(Command.keyHome), KeyModifier.none), //PuTTY, Linux "\x1b[11^": Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.control), //rxvt "\x1b[11~": Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.none), //PuTTY, rxvt "\x1b[12^": Key(KeyType.COMMAND, KeyValue(Command.keyF2), KeyModifier.control), //rxvt "\x1b[12~": Key(KeyType.COMMAND, KeyValue(Command.keyF2), KeyModifier.none), //PuTTY, rxvt "\x1b[13^": Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.control), //rxvt "\x1b[13~": Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.none), //PuTTY, rxvt "\x1b[14^": Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.control), //rxvt "\x1b[14~": Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.none), //PuTTY, rxvt "\x1b[15;2~": Key(KeyType.COMMAND, KeyValue(Command.keyF5), KeyModifier.shift), //Konsole, Xterm "\x1b[15;3": Key(KeyType.COMMAND, KeyValue(Command.keyF5), KeyModifier.alt), //Konsole, Xterm "\x1b[15;4~": Key(KeyType.COMMAND, KeyValue(Command.keyF5), KeyModifier.shift|KeyModifier.alt), //Konsole, Xterm "\x1b[15;5~": Key(KeyType.COMMAND, KeyValue(Command.keyF5), KeyModifier.control), //Konsole, Xterm "\x1b[15;6~": Key(KeyType.COMMAND, KeyValue(Command.keyF5), KeyModifier.shift|KeyModifier.control), //Konsole, Xterm "\x1b[15;8~": Key(KeyType.COMMAND, KeyValue(Command.keyF5), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[15^": Key(KeyType.COMMAND, KeyValue(Command.keyF5), KeyModifier.control), //rxvt "\x1b[15~": Key(KeyType.COMMAND, KeyValue(Command.keyF5), KeyModifier.none), //PuTTY, Konsole, Xterm, rxvt "\x1b[17;2~": Key(KeyType.COMMAND, KeyValue(Command.keyF6), KeyModifier.shift), //Konsole, Xterm "\x1b[17;3~": Key(KeyType.COMMAND, KeyValue(Command.keyF6), KeyModifier.alt), //Konsole, Xterm "\x1b[17;4~": Key(KeyType.COMMAND, KeyValue(Command.keyF6), KeyModifier.shift|KeyModifier.alt), //Konsole, Xterm "\x1b[17;5~": Key(KeyType.COMMAND, KeyValue(Command.keyF6), KeyModifier.control), //Konsole, Xterm "\x1b[17;6~": Key(KeyType.COMMAND, KeyValue(Command.keyF6), KeyModifier.shift|KeyModifier.control), //Konsole, Xterm "\x1b[17;8~": Key(KeyType.COMMAND, KeyValue(Command.keyF6), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[17^": Key(KeyType.COMMAND, KeyValue(Command.keyF6), KeyModifier.control), //rxvt "\x1b[17~": Key(KeyType.COMMAND, KeyValue(Command.keyF6), KeyModifier.none), //PuTTY, Konsole, Xterm, rxvt, Linux "\x1b[18;2~": Key(KeyType.COMMAND, KeyValue(Command.keyF7), KeyModifier.shift), //Konsole, Xterm "\x1b[18;3~": Key(KeyType.COMMAND, KeyValue(Command.keyF7), KeyModifier.alt), //Konsole, Xterm "\x1b[18;4~": Key(KeyType.COMMAND, KeyValue(Command.keyF7), KeyModifier.shift|KeyModifier.alt), //Konsole, Xterm "\x1b[18;5~": Key(KeyType.COMMAND, KeyValue(Command.keyF7), KeyModifier.control), //Konsole "\x1b[18;6~": Key(KeyType.COMMAND, KeyValue(Command.keyF7), KeyModifier.shift|KeyModifier.control), //Konsole, Xterm "\x1b[18;8~": Key(KeyType.COMMAND, KeyValue(Command.keyF7), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[18^": Key(KeyType.COMMAND, KeyValue(Command.keyF7), KeyModifier.control), //rxvt "\x1b[18~": Key(KeyType.COMMAND, KeyValue(Command.keyF7), KeyModifier.none), //PuTTY, Konsole, Xterm, rxvt, Linux "\x1b[19;2~": Key(KeyType.COMMAND, KeyValue(Command.keyF8), KeyModifier.shift), //Konsole, Xterm "\x1b[19;3~": Key(KeyType.COMMAND, KeyValue(Command.keyF8), KeyModifier.alt), //Konsole, Xterm "\x1b[19;4~": Key(KeyType.COMMAND, KeyValue(Command.keyF8), KeyModifier.shift|KeyModifier.alt), //Konsole, Xterm "\x1b[19;5~": Key(KeyType.COMMAND, KeyValue(Command.keyF8), KeyModifier.control), //Konsole "\x1b[19;6~": Key(KeyType.COMMAND, KeyValue(Command.keyF8), KeyModifier.shift|KeyModifier.control), //Konsole, Xterm "\x1b[19;8~": Key(KeyType.COMMAND, KeyValue(Command.keyF8), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[19^": Key(KeyType.COMMAND, KeyValue(Command.keyF8), KeyModifier.control), //rxvt "\x1b[19~": Key(KeyType.COMMAND, KeyValue(Command.keyF8), KeyModifier.none), //PuTTY, Konsole, Xterm, rxvt, Linux "\x1b[2;3~": Key(KeyType.COMMAND, KeyValue(Command.keyInsert), KeyModifier.alt), //Konsole, Xterm "\x1b[2;4~": Key(KeyType.COMMAND, KeyValue(Command.keyInsert), KeyModifier.shift|KeyModifier.alt), //Konsole "\x1b[2;5~": Key(KeyType.COMMAND, KeyValue(Command.keyInsert), KeyModifier.control), //Konsole, Xterm "\x1b[2;7~": Key(KeyType.COMMAND, KeyValue(Command.keyInsert), KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[2;8~": Key(KeyType.COMMAND, KeyValue(Command.keyInsert), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole "\x1b[2@": Key(KeyType.COMMAND, KeyValue(Command.keyInsert), KeyModifier.shift|KeyModifier.control), //rxvt "\x1b[2^": Key(KeyType.COMMAND, KeyValue(Command.keyInsert), KeyModifier.control), //rxvt "\x1b[2~": Key(KeyType.COMMAND, KeyValue(Command.keyInsert), KeyModifier.none), //PuTTY, Konsole, Xterm, rxvt, Linux "\x1b[20;2~": Key(KeyType.COMMAND, KeyValue(Command.keyF9), KeyModifier.shift), //Konsole, Xterm "\x1b[20;3~": Key(KeyType.COMMAND, KeyValue(Command.keyF9), KeyModifier.alt), //Konsole, Xterm "\x1b[20;4~": Key(KeyType.COMMAND, KeyValue(Command.keyF9), KeyModifier.shift|KeyModifier.alt), //Konsole, Xterm "\x1b[20;5~": Key(KeyType.COMMAND, KeyValue(Command.keyF9), KeyModifier.control), //Konsole "\x1b[20;6~": Key(KeyType.COMMAND, KeyValue(Command.keyF9), KeyModifier.shift|KeyModifier.control), //Konsole, Xterm "\x1b[20;8~": Key(KeyType.COMMAND, KeyValue(Command.keyF9), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[20^": Key(KeyType.COMMAND, KeyValue(Command.keyF9), KeyModifier.control), //rxvt "\x1b[20~": Key(KeyType.COMMAND, KeyValue(Command.keyF9), KeyModifier.none), //PuTTY, Konsole, Xterm, rxvt, Linux "\x1b[21;2~": Key(KeyType.COMMAND, KeyValue(Command.keyF10), KeyModifier.shift), //Konsole, Xterm "\x1b[21;3~": Key(KeyType.COMMAND, KeyValue(Command.keyF10), KeyModifier.alt), //Konsole, Xterm "\x1b[21;4~": Key(KeyType.COMMAND, KeyValue(Command.keyF10), KeyModifier.shift|KeyModifier.alt), //Konsole, Xterm "\x1b[21;5~": Key(KeyType.COMMAND, KeyValue(Command.keyF10), KeyModifier.control), //Konsole "\x1b[21;6~": Key(KeyType.COMMAND, KeyValue(Command.keyF10), KeyModifier.shift|KeyModifier.control), //Konsole, Xterm "\x1b[21;8~": Key(KeyType.COMMAND, KeyValue(Command.keyF10), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[21^": Key(KeyType.COMMAND, KeyValue(Command.keyF10), KeyModifier.control), //rxvt "\x1b[21~": Key(KeyType.COMMAND, KeyValue(Command.keyF10), KeyModifier.none), //PuTTY, Konsole, Xterm, rxvt, Linux "\x1b[23;2~": Key(KeyType.COMMAND, KeyValue(Command.keyF11), KeyModifier.shift), //Konsole, Xterm "\x1b[23;3~": Key(KeyType.COMMAND, KeyValue(Command.keyF11), KeyModifier.alt), //Konsole, Xterm "\x1b[23;4~": Key(KeyType.COMMAND, KeyValue(Command.keyF11), KeyModifier.shift|KeyModifier.alt), //Konsole, Xterm "\x1b[23;5~": Key(KeyType.COMMAND, KeyValue(Command.keyF11), KeyModifier.control), //Konsole, Xterm "\x1b[23;6~": Key(KeyType.COMMAND, KeyValue(Command.keyF11), KeyModifier.shift|KeyModifier.control), //Konsole, Xterm "\x1b[23;8~": Key(KeyType.COMMAND, KeyValue(Command.keyF11), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[23@": Key(KeyType.COMMAND, KeyValue(Command.keyF11), KeyModifier.shift|KeyModifier.control), //rxvt "\x1b[23^": Key(KeyType.COMMAND, KeyValue(Command.keyF11), KeyModifier.control), //rxvt "\x1b[23~": Key(KeyType.COMMAND, KeyValue(Command.keyF11), KeyModifier.none), //PuTTY, Konsole, Xterm, rxvt, Linux "\x1b[23$": Key(KeyType.COMMAND, KeyValue(Command.keyF11), KeyModifier.shift), //rxvt "\x1b[24;2~": Key(KeyType.COMMAND, KeyValue(Command.keyF12), KeyModifier.shift), //Konsole, Xterm "\x1b[24;3~": Key(KeyType.COMMAND, KeyValue(Command.keyF12), KeyModifier.alt), //Konsole, Xterm "\x1b[24;6~": Key(KeyType.COMMAND, KeyValue(Command.keyF12), KeyModifier.shift|KeyModifier.control), //Konsole, Xterm "\x1b[24;8~": Key(KeyType.COMMAND, KeyValue(Command.keyF12), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[24@": Key(KeyType.COMMAND, KeyValue(Command.keyF12), KeyModifier.shift|KeyModifier.control), //rxvt "\x1b[24^": Key(KeyType.COMMAND, KeyValue(Command.keyF12), KeyModifier.control), //rxvt "\x1b[24~": Key(KeyType.COMMAND, KeyValue(Command.keyF12), KeyModifier.none), //PuTTY, Konsole, Xterm, rxvt, Linux "\x1b[24$": Key(KeyType.COMMAND, KeyValue(Command.keyF12), KeyModifier.shift), //rxvt "\x1b[25^": Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.shift|KeyModifier.control), //rxvt "\x1b[26^": Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.shift|KeyModifier.control), //rxvt "\x1b[28^": Key(KeyType.COMMAND, KeyValue(Command.keyF5), KeyModifier.shift|KeyModifier.control), //rxvt "\x1b[29^": Key(KeyType.COMMAND, KeyValue(Command.keyF6), KeyModifier.shift|KeyModifier.control), //rxvt "\x1b[3;2~": Key(KeyType.COMMAND, KeyValue(Command.keyDelete), KeyModifier.shift), //Konsole, Xterm "\x1b[3;3~": Key(KeyType.COMMAND, KeyValue(Command.keyDelete), KeyModifier.alt), //Konsole, Xterm "\x1b[3;4~": Key(KeyType.COMMAND, KeyValue(Command.keyDelete), KeyModifier.shift|KeyModifier.alt), //Konsole, Xterm "\x1b[3;5~": Key(KeyType.COMMAND, KeyValue(Command.keyDelete), KeyModifier.control), //Konsole, Xterm "\x1b[3;6~": Key(KeyType.COMMAND, KeyValue(Command.keyDelete), KeyModifier.shift|KeyModifier.control), //Konsole, Xterm "\x1b[3@": Key(KeyType.COMMAND, KeyValue(Command.keyDelete), KeyModifier.shift|KeyModifier.control), //rxvt "\x1b[3^": Key(KeyType.COMMAND, KeyValue(Command.keyDelete), KeyModifier.control), //rxvt "\x1b[3~": Key(KeyType.COMMAND, KeyValue(Command.keyDelete), KeyModifier.none), //PuTTY, Konsole, Xterm, rxvt, Linux "\x1b[3$": Key(KeyType.COMMAND, KeyValue(Command.keyDelete), KeyModifier.shift), //rxvt "\x1b[31^": Key(KeyType.COMMAND, KeyValue(Command.keyF7), KeyModifier.shift|KeyModifier.control), //rxvt "\x1b[32^": Key(KeyType.COMMAND, KeyValue(Command.keyF8), KeyModifier.shift|KeyModifier.control), //rxvt "\x1b[33^": Key(KeyType.COMMAND, KeyValue(Command.keyF9), KeyModifier.shift|KeyModifier.control), //rxvt "\x1b[34^": Key(KeyType.COMMAND, KeyValue(Command.keyF10), KeyModifier.shift|KeyModifier.control), //rxvt "\x1b[4~": Key(KeyType.COMMAND, KeyValue(Command.keyEnd), KeyModifier.none), //PuTTY, Linux "\x1b[5;3~": Key(KeyType.COMMAND, KeyValue(Command.keyPageUp), KeyModifier.alt), //Konsole, Xterm "\x1b[5;5~": Key(KeyType.COMMAND, KeyValue(Command.keyPageUp), KeyModifier.control), //Konsole, Xterm "\x1b[5;7~": Key(KeyType.COMMAND, KeyValue(Command.keyPageUp), KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[5@": Key(KeyType.COMMAND, KeyValue(Command.keyPageUp), KeyModifier.shift|KeyModifier.control), //rxvt "\x1b[5^": Key(KeyType.COMMAND, KeyValue(Command.keyPageUp), KeyModifier.control), //rxvt "\x1b[5~": Key(KeyType.COMMAND, KeyValue(Command.keyPageUp), KeyModifier.none), //PuTTY, Konsole, Xterm, rxvt, Linux "\x1b[6;3~": Key(KeyType.COMMAND, KeyValue(Command.keyPageDown), KeyModifier.alt), //Konsole, Xterm "\x1b[6;5~": Key(KeyType.COMMAND, KeyValue(Command.keyPageDown), KeyModifier.control), //Konsole, Xterm "\x1b[6;7~": Key(KeyType.COMMAND, KeyValue(Command.keyPageDown), KeyModifier.alt|KeyModifier.control), //Konsole, Xterm "\x1b[6@": Key(KeyType.COMMAND, KeyValue(Command.keyPageDown), KeyModifier.shift|KeyModifier.control), //rxvt "\x1b[6^": Key(KeyType.COMMAND, KeyValue(Command.keyPageDown), KeyModifier.control), //rxvt "\x1b[6~": Key(KeyType.COMMAND, KeyValue(Command.keyPageDown), KeyModifier.none), //PuTTY, Konsole, Xterm, rxvt, Linux "\x1b[7@": Key(KeyType.COMMAND, KeyValue(Command.keyHome), KeyModifier.shift|KeyModifier.control), //rxvt "\x1b[7^": Key(KeyType.COMMAND, KeyValue(Command.keyHome), KeyModifier.control), //rxvt "\x1b[7~": Key(KeyType.COMMAND, KeyValue(Command.keyHome), KeyModifier.none), //rxvt "\x1b[7$": Key(KeyType.COMMAND, KeyValue(Command.keyHome), KeyModifier.shift), //rxvt "\x1b[8@": Key(KeyType.COMMAND, KeyValue(Command.keyEnd), KeyModifier.shift|KeyModifier.control), //rxvt "\x1b[8^": Key(KeyType.COMMAND, KeyValue(Command.keyEnd), KeyModifier.control), //rxvt "\x1b[8~": Key(KeyType.COMMAND, KeyValue(Command.keyEnd), KeyModifier.none), //rxvt "\x1b[8$": Key(KeyType.COMMAND, KeyValue(Command.keyEnd), KeyModifier.shift), //rxvt "\x1b[A": Key(KeyType.COMMAND, KeyValue(Command.keyUp), KeyModifier.none), //PuTTY, Konsole, Xterm, rxvt, Linux "\x1b[a": Key(KeyType.COMMAND, KeyValue(Command.keyUp), KeyModifier.shift), //rxvt "\x1b[B": Key(KeyType.COMMAND, KeyValue(Command.keyDown), KeyModifier.none), //PuTTY, Konsole, Xterm, rxvt, Linux "\x1b[b": Key(KeyType.COMMAND, KeyValue(Command.keyDown), KeyModifier.shift), //rxvt "\x1b[C": Key(KeyType.COMMAND, KeyValue(Command.keyRight), KeyModifier.none), //PuTTY, Konsole, Xterm, rxvt, Linux "\x1b[c": Key(KeyType.COMMAND, KeyValue(Command.keyRight), KeyModifier.shift), //rxvt "\x1b[D": Key(KeyType.COMMAND, KeyValue(Command.keyLeft), KeyModifier.none), //PuTTY, Konsole, Xterm, rxvt, Linux "\x1b[d": Key(KeyType.COMMAND, KeyValue(Command.keyLeft), KeyModifier.shift), //rxvt "\x1b[E": Key(KeyType.COMMAND, KeyValue(Command.keyB2), KeyModifier.none), //Xterm "\x1b[F": Key(KeyType.COMMAND, KeyValue(Command.keyEnd), KeyModifier.none), //Konsole, Xterm "\x1b[G": Key(KeyType.COMMAND, KeyValue(Command.keyB2), KeyModifier.none), //PuTTY, Linux "\x1b[H": Key(KeyType.COMMAND, KeyValue(Command.keyHome), KeyModifier.none), //Konsole, Xterm "\x1b[Z": Key(KeyType.COMMAND, KeyValue(Command.horizontalTabulation), KeyModifier.shift), //PuTTY, Konsole, Xterm, rxvt "\x1bO2P": Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.shift), //Konsole "\x1bO2Q": Key(KeyType.COMMAND, KeyValue(Command.keyF2), KeyModifier.shift), //Konsole "\x1bO2R": Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.shift), //Konsole "\x1bO2S": Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.shift), //Konsole "\x1bO3P": Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.alt), //Konsole "\x1bO3Q": Key(KeyType.COMMAND, KeyValue(Command.keyF2), KeyModifier.alt), //Konsole "\x1bO3R": Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.alt), //Konsole "\x1bO4P": Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.shift|KeyModifier.alt), //Konsole "\x1bO4Q": Key(KeyType.COMMAND, KeyValue(Command.keyF2), KeyModifier.shift|KeyModifier.alt), //Konsole "\x1bO4R": Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.shift|KeyModifier.alt), //Konsole "\x1bO4S": Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.shift|KeyModifier.alt), //Konsole "\x1bO5P": Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.control), //Konsole "\x1bO5Q": Key(KeyType.COMMAND, KeyValue(Command.keyF2), KeyModifier.control), //Konsole "\x1bO5R": Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.control), //Konsole "\x1bO5R": Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.control), //Konsole "\x1bO6P": Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.shift|KeyModifier.control), //Konsole "\x1bO6Q": Key(KeyType.COMMAND, KeyValue(Command.keyF2), KeyModifier.shift|KeyModifier.control), //Konsole "\x1bO6R": Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.shift|KeyModifier.control), //Konsole "\x1bO6S": Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.shift|KeyModifier.control), //Konsole "\x1bO8P": Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole "\x1bO8Q": Key(KeyType.COMMAND, KeyValue(Command.keyF2), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole "\x1bO8R": Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole "\x1bO8S": Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.shift|KeyModifier.alt|KeyModifier.control), //Konsole "\x1bOA": Key(KeyType.COMMAND, KeyValue(Command.keyUp), KeyModifier.shift), //PuTTY "\x1bOa": Key(KeyType.COMMAND, KeyValue(Command.keyUp), KeyModifier.control), //rxvt "\x1bOB": Key(KeyType.COMMAND, KeyValue(Command.keyDown), KeyModifier.shift), //PuTTY "\x1bOb": Key(KeyType.COMMAND, KeyValue(Command.keyDown), KeyModifier.control), //rxvt "\x1bOC": Key(KeyType.COMMAND, KeyValue(Command.keyRight), KeyModifier.shift), //PuTTY "\x1bOc": Key(KeyType.COMMAND, KeyValue(Command.keyRight), KeyModifier.control), //rxvt "\x1bOD": Key(KeyType.COMMAND, KeyValue(Command.keyLeft), KeyModifier.shift), //PuTTY "\x1bOd": Key(KeyType.COMMAND, KeyValue(Command.keyLeft), KeyModifier.control), //rxvt "\x1bOG": Key(KeyType.COMMAND, KeyValue(Command.keyB2), KeyModifier.shift), //PuTTY "\x1bOP": Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.none), //Konsole, Xterm "\x1bOQ": Key(KeyType.COMMAND, KeyValue(Command.keyF2), KeyModifier.none), //Konsole, Xterm "\x1bOR": Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.none), //Konsole, Xterm "\x1bOS": Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.none), //Konsole, Xterm "\x1bOu": Key(KeyType.COMMAND, KeyValue(Command.keyB2), KeyModifier.shift), //rxvt ]; //rxvt and Linux terminal assign the same escape sequences to different keyboard shortcuts immutable term = environment.get("TERM", "unknown"); if (term == "linux" || term == "screen") { keyMap["\x1b[25~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.shift); keyMap["\x1b[26~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF2), KeyModifier.shift); keyMap["\x1b[28~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.shift); keyMap["\x1b[29~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.shift); keyMap["\x1b[31~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF5), KeyModifier.shift); keyMap["\x1b[32~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF6), KeyModifier.shift); keyMap["\x1b[33~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF7), KeyModifier.shift); keyMap["\x1b[34~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF8), KeyModifier.shift); } else { keyMap["\x1b[25~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.shift); keyMap["\x1b[26~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.shift); keyMap["\x1b[28~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF5), KeyModifier.shift); keyMap["\x1b[29~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF6), KeyModifier.shift); keyMap["\x1b[31~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF7), KeyModifier.shift); keyMap["\x1b[32~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF8), KeyModifier.shift); keyMap["\x1b[33~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF9), KeyModifier.shift); keyMap["\x1b[34~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF10), KeyModifier.shift); } //Some service escape sequences //During terminal resize Consoleur generates this sequence keyMap["\x1b[480w"] = Key(KeyType.COMMAND, KeyValue(Command.winch), KeyModifier.none); //Bracketed Pasting keyMap["\x1b[200~"] = Key(KeyType.COMMAND, KeyValue(Command.pasteStart), KeyModifier.none); keyMap["\x1b[201~"] = Key(KeyType.COMMAND, KeyValue(Command.pasteEnd), KeyModifier.none); } version (WithSuperKey) { private void addSuperKeys() { keyMap["\x1b[1;1A"] = Key(KeyType.COMMAND, KeyValue(Command.keyUp), KeyModifier.supr); keyMap["\x1b[1;1B"] = Key(KeyType.COMMAND, KeyValue(Command.keyDown), KeyModifier.supr); keyMap["\x1b[1;1C"] = Key(KeyType.COMMAND, KeyValue(Command.keyRight), KeyModifier.supr); keyMap["\x1b[1;1D"] = Key(KeyType.COMMAND, KeyValue(Command.keyLeft), KeyModifier.supr); keyMap["\x1b[2;1~"] = Key(KeyType.COMMAND, KeyValue(Command.keyInsert), KeyModifier.supr); keyMap["\x1b[3;1~"] = Key(KeyType.COMMAND, KeyValue(Command.keyDelete), KeyModifier.supr); keyMap["\x1b[1;1F"] = Key(KeyType.COMMAND, KeyValue(Command.keyEnd), KeyModifier.supr); keyMap["\x1b[1;1H"] = Key(KeyType.COMMAND, KeyValue(Command.keyHome), KeyModifier.supr); keyMap["\x1b[5;1~"] = Key(KeyType.COMMAND, KeyValue(Command.keyPageUp), KeyModifier.supr); keyMap["\x1b[6;1~"] = Key(KeyType.COMMAND, KeyValue(Command.keyPageDown), KeyModifier.supr); keyMap["\x1bO1P"] = Key(KeyType.COMMAND, KeyValue(Command.keyF1), KeyModifier.supr); keyMap["\x1bO1Q"] = Key(KeyType.COMMAND, KeyValue(Command.keyF2), KeyModifier.supr); keyMap["\x1bO1R"] = Key(KeyType.COMMAND, KeyValue(Command.keyF3), KeyModifier.supr); keyMap["\x1bO1S"] = Key(KeyType.COMMAND, KeyValue(Command.keyF4), KeyModifier.supr); keyMap["\x1b[15;1~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF5), KeyModifier.supr); keyMap["\x1b[17;1~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF6), KeyModifier.supr); keyMap["\x1b[18;1~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF7), KeyModifier.supr); keyMap["\x1b[19;1~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF8), KeyModifier.supr); keyMap["\x1b[20;1~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF9), KeyModifier.supr); keyMap["\x1b[21;1~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF10), KeyModifier.supr); keyMap["\x1b[23;1~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF11), KeyModifier.supr); keyMap["\x1b[24;1~"] = Key(KeyType.COMMAND, KeyValue(Command.keyF12), KeyModifier.supr); } } }
D
/** * Manage flow analysis for constructors. * * 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/ctorflow.d, _ctorflow.d) * Documentation: https://dlang.org/phobos/dmd_ctorflow.html * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/ctorflow.d */ module dmd.ctorflow; import core.stdc.stdio; import dmd.root.rmem; import dmd.globals : Loc; enum CSX : ushort { none = 0, this_ctor = 0x01, /// called this() super_ctor = 0x02, /// called super() label = 0x04, /// seen a label return_ = 0x08, /// seen a return statement any_ctor = 0x10, /// either this() or super() was called halt = 0x20, /// assert(0) } /// Individual field in the Ctor with information about its callees and location. struct FieldInit { CSX csx; /// information about the field's callees Loc loc; /// location of the field initialization } /*********** * Primitive flow analysis for constructors */ struct CtorFlow { CSX callSuper; /// state of calling other constructors FieldInit[] fieldinit; /// state of field initializations void allocFieldinit(size_t dim) { fieldinit = (cast(FieldInit*)mem.xcalloc(FieldInit.sizeof, dim))[0 .. dim]; } void freeFieldinit() { if (fieldinit.ptr) mem.xfree(fieldinit.ptr); fieldinit = null; } /*********************** * Create a deep copy of `this` * Returns: * a copy */ CtorFlow clone() { return CtorFlow(callSuper, fieldinit.arraydup); } /********************************** * Set CSX bits in flow analysis state * Params: * csx = bits to set */ void orCSX(CSX csx) nothrow pure { callSuper |= csx; foreach (ref u; fieldinit) u.csx |= csx; } /****************************** * OR CSX bits to `this` * Params: * ctorflow = bits to OR in */ void OR(const ref CtorFlow ctorflow) pure nothrow { callSuper |= ctorflow.callSuper; if (fieldinit.length && ctorflow.fieldinit.length) { assert(fieldinit.length == ctorflow.fieldinit.length); foreach (i, u; ctorflow.fieldinit) { auto fi = &fieldinit[i]; fi.csx |= u.csx; if (fi.loc is Loc.init) fi.loc = u.loc; } } } } /**************************************** * Merge `b` flow analysis results into `a`. * Params: * a = the path to merge `b` into * b = the other path * Returns: * false means one of the paths skips construction */ bool mergeCallSuper(ref CSX a, const CSX b) pure nothrow { // This does a primitive flow analysis to support the restrictions // regarding when and how constructors can appear. // It merges the results of two paths. // The two paths are `a` and `b`; the result is merged into `a`. if (b == a) return true; // Have ALL branches called a constructor? const aAll = (a & (CSX.this_ctor | CSX.super_ctor)) != 0; const bAll = (b & (CSX.this_ctor | CSX.super_ctor)) != 0; // Have ANY branches called a constructor? const aAny = (a & CSX.any_ctor) != 0; const bAny = (b & CSX.any_ctor) != 0; // Have any branches returned? const aRet = (a & CSX.return_) != 0; const bRet = (b & CSX.return_) != 0; // Have any branches halted? const aHalt = (a & CSX.halt) != 0; const bHalt = (b & CSX.halt) != 0; if (aHalt && bHalt) { a = CSX.halt; } else if ((!bHalt && bRet && !bAny && aAny) || (!aHalt && aRet && !aAny && bAny)) { // If one has returned without a constructor call, there must not // be ctor calls in the other. return false; } else if (bHalt || bRet && bAll) { // If one branch has called a ctor and then exited, anything the // other branch has done is OK (except returning without a // ctor call, but we already checked that). a |= b & (CSX.any_ctor | CSX.label); } else if (aHalt || aRet && aAll) { a = cast(CSX)(b | (a & (CSX.any_ctor | CSX.label))); } else if (aAll != bAll) // both branches must have called ctors, or both not return false; else { // If one returned without a ctor, remember that if (bRet && !bAny) a |= CSX.return_; a |= b & (CSX.any_ctor | CSX.label); } return true; } /**************************************** * Merge `b` flow analysis results into `a`. * Params: * a = the path to merge `b` into * b = the other path * Returns: * false means either `a` or `b` skips initialization */ bool mergeFieldInit(ref CSX a, const CSX b) pure nothrow { if (b == a) return true; // Have any branches returned? const aRet = (a & CSX.return_) != 0; const bRet = (b & CSX.return_) != 0; // Have any branches halted? const aHalt = (a & CSX.halt) != 0; const bHalt = (b & CSX.halt) != 0; if (aHalt && bHalt) { a = CSX.halt; return true; } // The logic here is to prefer the branch that neither halts nor returns. bool ok; if (!bHalt && bRet) { // Branch b returns, no merging required. ok = (b & CSX.this_ctor); } else if (!aHalt && aRet) { // Branch a returns, but b doesn't, b takes precedence. ok = (a & CSX.this_ctor); a = b; } else if (bHalt) { // Branch b halts, no merging required. ok = (a & CSX.this_ctor); } else if (aHalt) { // Branch a halts, but b doesn't, b takes precedence. ok = (b & CSX.this_ctor); a = b; } else { // Neither branch returns nor halts, merge flags. ok = !((a ^ b) & CSX.this_ctor); a |= b; } return ok; }
D
/Users/petercernak/vapor/TILApp/Build/Intermediates.noindex/TILApp.build/Debug/TemplateKit.build/Objects-normal/x86_64/TemplateEmbed.o : /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Data/TemplateData.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateEmbed.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Deprecated.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateSource.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Data/TemplateDataStorage.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/ASTCache.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Data/TemplateDataRepresentable.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Utilities/HTMLEscape.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateSyntaxType.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Uppercase.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Lowercase.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Capitalize.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateTag.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateConditional.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateCustom.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateExpression.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Var.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Data/TemplateDataEncoder.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateIdentifier.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/TemplateByteScanner.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/TemplateRenderer.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/TagRenderer.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/PlaintextRenderer.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/ViewRenderer.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/TemplateParser.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/TemplateSerializer.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Utilities/TemplateError.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateIterator.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Contains.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Utilities/Exports.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/DateFormat.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateConstant.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Comment.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Print.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Count.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateDataContext.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/TagContext.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Raw.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateRaw.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/View.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateSyntax.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIO.framework/Modules/NIO.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Async.framework/Modules/Async.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Service.framework/Modules/Service.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Core.framework/Modules/Core.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Debugging.framework/Modules/Debugging.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/COperatingSystem.framework/Modules/COperatingSystem.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIOConcurrencyHelpers.framework/Modules/NIOConcurrencyHelpers.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Bits.framework/Modules/Bits.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIOFoundationCompat.framework/Modules/NIOFoundationCompat.swiftmodule/x86_64.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/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOAtomics/include/cpp_magic.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIODarwin/include/c_nio_darwin.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOAtomics/include/c-atomics.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOLinux/include/c_nio_linux.h /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOSHA1/module.modulemap /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio-zlib-support.git--6538424668019974428/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIODarwin/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOAtomics/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOLinux/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/petercernak/vapor/TILApp/Build/Intermediates.noindex/TILApp.build/Debug/TemplateKit.build/Objects-normal/x86_64/TemplateEmbed~partial.swiftmodule : /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Data/TemplateData.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateEmbed.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Deprecated.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateSource.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Data/TemplateDataStorage.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/ASTCache.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Data/TemplateDataRepresentable.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Utilities/HTMLEscape.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateSyntaxType.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Uppercase.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Lowercase.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Capitalize.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateTag.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateConditional.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateCustom.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateExpression.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Var.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Data/TemplateDataEncoder.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateIdentifier.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/TemplateByteScanner.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/TemplateRenderer.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/TagRenderer.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/PlaintextRenderer.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/ViewRenderer.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/TemplateParser.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/TemplateSerializer.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Utilities/TemplateError.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateIterator.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Contains.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Utilities/Exports.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/DateFormat.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateConstant.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Comment.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Print.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Count.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateDataContext.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/TagContext.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Raw.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateRaw.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/View.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateSyntax.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIO.framework/Modules/NIO.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Async.framework/Modules/Async.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Service.framework/Modules/Service.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Core.framework/Modules/Core.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Debugging.framework/Modules/Debugging.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/COperatingSystem.framework/Modules/COperatingSystem.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIOConcurrencyHelpers.framework/Modules/NIOConcurrencyHelpers.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Bits.framework/Modules/Bits.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIOFoundationCompat.framework/Modules/NIOFoundationCompat.swiftmodule/x86_64.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/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOAtomics/include/cpp_magic.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIODarwin/include/c_nio_darwin.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOAtomics/include/c-atomics.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOLinux/include/c_nio_linux.h /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOSHA1/module.modulemap /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio-zlib-support.git--6538424668019974428/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIODarwin/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOAtomics/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOLinux/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/petercernak/vapor/TILApp/Build/Intermediates.noindex/TILApp.build/Debug/TemplateKit.build/Objects-normal/x86_64/TemplateEmbed~partial.swiftdoc : /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Data/TemplateData.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateEmbed.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Deprecated.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateSource.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Data/TemplateDataStorage.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/ASTCache.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Data/TemplateDataRepresentable.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Utilities/HTMLEscape.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateSyntaxType.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Uppercase.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Lowercase.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Capitalize.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateTag.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateConditional.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateCustom.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateExpression.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Var.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Data/TemplateDataEncoder.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateIdentifier.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/TemplateByteScanner.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/TemplateRenderer.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/TagRenderer.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/PlaintextRenderer.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/ViewRenderer.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/TemplateParser.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Pipeline/TemplateSerializer.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Utilities/TemplateError.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateIterator.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Contains.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Utilities/Exports.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/DateFormat.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateConstant.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Comment.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Print.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Count.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateDataContext.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/TagContext.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/Tag/Raw.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateRaw.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/View.swift /Users/petercernak/vapor/TILApp/.build/checkouts/template-kit.git-9048208343057795534/Sources/TemplateKit/AST/TemplateSyntax.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIO.framework/Modules/NIO.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Async.framework/Modules/Async.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Service.framework/Modules/Service.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Core.framework/Modules/Core.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Debugging.framework/Modules/Debugging.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/COperatingSystem.framework/Modules/COperatingSystem.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIOConcurrencyHelpers.framework/Modules/NIOConcurrencyHelpers.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/Bits.framework/Modules/Bits.swiftmodule/x86_64.swiftmodule /Users/petercernak/vapor/TILApp/Build/Products/Debug/NIOFoundationCompat.framework/Modules/NIOFoundationCompat.swiftmodule/x86_64.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/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOAtomics/include/cpp_magic.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIODarwin/include/c_nio_darwin.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOAtomics/include/c-atomics.h /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio.git--2128188973977302459/Sources/CNIOLinux/include/c_nio_linux.h /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOSHA1/module.modulemap /Users/petercernak/vapor/TILApp/.build/checkouts/swift-nio-zlib-support.git--6538424668019974428/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIODarwin/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOAtomics/module.modulemap /Users/petercernak/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOLinux/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
D
/***********************************************************************\ * winldap.d * * * * Windows API header module * * * * Translated from MinGW Windows headers * * by Stewart Gordon * * * * Placed into public domain * \***********************************************************************/ module win32.winldap; version(Windows): /* Comment from MinGW winldap.h - Header file for the Windows LDAP API Written by Filip Navara <xnavara@volny.cz> References: The C LDAP Application Program Interface http://www.watersprings.org/pub/id/draft-ietf-ldapext-ldap-c-api-05.txt Lightweight Directory Access Protocol Reference http://msdn.microsoft.com/library/en-us/netdir/ldap/ldap_reference.asp This library 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. */ import win32.schannel, win32.winber; private import win32.wincrypt, win32.windef; version(Tango){ private import tango.stdc.stdio; } align(4): enum { LDAP_VERSION1 = 1, LDAP_VERSION2 = 2, LDAP_VERSION3 = 3, LDAP_VERSION = LDAP_VERSION2, LDAP_VERSION_MIN = LDAP_VERSION2, LDAP_VERSION_MAX = LDAP_VERSION3 } /* MinGW defines ANSI and Unicode versions as LDAP_VENDOR_NAME and * LDAP_VENDOR_NAME_W respectively; similarly with other string constants * defined in this module. */ const TCHAR[] LDAP_VENDOR_NAME = "Microsoft Corporation."; const LDAP_API_VERSION = 2004; const LDAP_VENDOR_VERSION = 510; const LDAP_API_INFO_VERSION = 1; const LDAP_FEATURE_INFO_VERSION = 1; enum { LDAP_SUCCESS = 0x00, LDAP_OPT_SUCCESS = LDAP_SUCCESS, LDAP_OPERATIONS_ERROR, LDAP_PROTOCOL_ERROR, LDAP_TIMELIMIT_EXCEEDED, LDAP_SIZELIMIT_EXCEEDED, LDAP_COMPARE_FALSE, LDAP_COMPARE_TRUE, LDAP_STRONG_AUTH_NOT_SUPPORTED, LDAP_AUTH_METHOD_NOT_SUPPORTED = LDAP_STRONG_AUTH_NOT_SUPPORTED, LDAP_STRONG_AUTH_REQUIRED, LDAP_REFERRAL_V2, LDAP_PARTIAL_RESULTS = LDAP_REFERRAL_V2, LDAP_REFERRAL, LDAP_ADMIN_LIMIT_EXCEEDED, LDAP_UNAVAILABLE_CRIT_EXTENSION, LDAP_CONFIDENTIALITY_REQUIRED, LDAP_SASL_BIND_IN_PROGRESS, // = 0x0e LDAP_NO_SUCH_ATTRIBUTE = 0x10, LDAP_UNDEFINED_TYPE, LDAP_INAPPROPRIATE_MATCHING, LDAP_CONSTRAINT_VIOLATION, LDAP_TYPE_OR_VALUE_EXISTS, LDAP_ATTRIBUTE_OR_VALUE_EXISTS = LDAP_TYPE_OR_VALUE_EXISTS, LDAP_INVALID_SYNTAX, // = 0x15 LDAP_NO_SUCH_OBJECT = 0x20, LDAP_ALIAS_PROBLEM, LDAP_INVALID_DN_SYNTAX, LDAP_IS_LEAF, LDAP_ALIAS_DEREF_PROBLEM, // = 0x24 LDAP_INAPPROPRIATE_AUTH = 0x30, LDAP_INVALID_CREDENTIALS, LDAP_INSUFFICIENT_ACCESS, LDAP_INSUFFICIENT_RIGHTS = LDAP_INSUFFICIENT_ACCESS, LDAP_BUSY, LDAP_UNAVAILABLE, LDAP_UNWILLING_TO_PERFORM, LDAP_LOOP_DETECT, // = 0x36 LDAP_NAMING_VIOLATION = 0x40, LDAP_OBJECT_CLASS_VIOLATION, LDAP_NOT_ALLOWED_ON_NONLEAF, LDAP_NOT_ALLOWED_ON_RDN, LDAP_ALREADY_EXISTS, LDAP_NO_OBJECT_CLASS_MODS, LDAP_RESULTS_TOO_LARGE, LDAP_AFFECTS_MULTIPLE_DSAS, // = 0x47 LDAP_OTHER = 0x50, LDAP_SERVER_DOWN, LDAP_LOCAL_ERROR, LDAP_ENCODING_ERROR, LDAP_DECODING_ERROR, LDAP_TIMEOUT, LDAP_AUTH_UNKNOWN, LDAP_FILTER_ERROR, LDAP_USER_CANCELLED, LDAP_PARAM_ERROR, LDAP_NO_MEMORY, LDAP_CONNECT_ERROR, LDAP_NOT_SUPPORTED, LDAP_CONTROL_NOT_FOUND, LDAP_NO_RESULTS_RETURNED, LDAP_MORE_RESULTS_TO_RETURN, LDAP_CLIENT_LOOP, LDAP_REFERRAL_LIMIT_EXCEEDED // = 0x61 } enum { LDAP_PORT = 389, LDAP_SSL_PORT = 636, LDAP_GC_PORT = 3268, LDAP_SSL_GC_PORT = 3269 } const void* LDAP_OPT_OFF = null, LDAP_OPT_ON = cast(void*) 1; enum { LDAP_OPT_API_INFO = 0x00, LDAP_OPT_DESC, LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_THREAD_FN_PTRS, LDAP_OPT_REBIND_FN, LDAP_OPT_REBIND_ARG, LDAP_OPT_REFERRALS, LDAP_OPT_RESTART, LDAP_OPT_SSL, LDAP_OPT_TLS = LDAP_OPT_SSL, LDAP_OPT_IO_FN_PTRS, // = 0x0b LDAP_OPT_CACHE_FN_PTRS = 0x0d, LDAP_OPT_CACHE_STRATEGY, LDAP_OPT_CACHE_ENABLE, LDAP_OPT_REFERRAL_HOP_LIMIT, LDAP_OPT_PROTOCOL_VERSION, LDAP_OPT_VERSION = LDAP_OPT_PROTOCOL_VERSION, LDAP_OPT_SERVER_CONTROLS, LDAP_OPT_CLIENT_CONTROLS, // = 0x13 LDAP_OPT_API_FEATURE_INFO = 0x15, LDAP_OPT_HOST_NAME = 0x30, LDAP_OPT_ERROR_NUMBER, LDAP_OPT_ERROR_STRING, LDAP_OPT_SERVER_ERROR, LDAP_OPT_SERVER_EXT_ERROR, // = 0x34 LDAP_OPT_PING_KEEP_ALIVE = 0x36, LDAP_OPT_PING_WAIT_TIME, LDAP_OPT_PING_LIMIT, // = 0x38 LDAP_OPT_DNSDOMAIN_NAME = 0x3b, LDAP_OPT_GETDSNAME_FLAGS = 0x3d, LDAP_OPT_HOST_REACHABLE, LDAP_OPT_PROMPT_CREDENTIALS, LDAP_OPT_TCP_KEEPALIVE, // = 0x40 LDAP_OPT_REFERRAL_CALLBACK = 0x70, LDAP_OPT_CLIENT_CERTIFICATE = 0x80, LDAP_OPT_SERVER_CERTIFICATE, // = 0x81 LDAP_OPT_AUTO_RECONNECT = 0x91, LDAP_OPT_SSPI_FLAGS, LDAP_OPT_SSL_INFO, LDAP_OPT_TLS_INFO = LDAP_OPT_SSL_INFO, LDAP_OPT_REF_DEREF_CONN_PER_MSG, LDAP_OPT_SIGN, LDAP_OPT_ENCRYPT, LDAP_OPT_SASL_METHOD, LDAP_OPT_AREC_EXCLUSIVE, LDAP_OPT_SECURITY_CONTEXT, LDAP_OPT_ROOTDSE_CACHE // = 0x9a } enum { LDAP_DEREF_NEVER, LDAP_DEREF_SEARCHING, LDAP_DEREF_FINDING, LDAP_DEREF_ALWAYS } const LDAP_NO_LIMIT = 0; const TCHAR[] LDAP_CONTROL_REFERRALS = "1.2.840.113556.1.4.616"; // FIXME: check type (declared with U suffix in MinGW) enum : uint { LDAP_CHASE_SUBORDINATE_REFERRALS = 0x20, LDAP_CHASE_EXTERNAL_REFERRALS = 0x40 } enum { LDAP_SCOPE_DEFAULT = -1, LDAP_SCOPE_BASE, LDAP_SCOPE_ONELEVEL, LDAP_SCOPE_SUBTREE } enum { LDAP_MOD_ADD, LDAP_MOD_DELETE, LDAP_MOD_REPLACE, LDAP_MOD_BVALUES = 0x80 } enum : int { LDAP_RES_BIND = 0x61, LDAP_RES_SEARCH_ENTRY = 0x64, LDAP_RES_SEARCH_RESULT = 0x65, LDAP_RES_MODIFY = 0x67, LDAP_RES_ADD = 0x69, LDAP_RES_DELETE = 0x6b, LDAP_RES_MODRDN = 0x6d, LDAP_RES_COMPARE = 0x6f, LDAP_RES_SEARCH_REFERENCE = 0x73, LDAP_RES_EXTENDED = 0x78, LDAP_RES_ANY = -1 } enum { LDAP_MSG_ONE, LDAP_MSG_ALL, LDAP_MSG_RECEIVED } const TCHAR[] LDAP_SERVER_SORT_OID = "1.2.840.113556.1.4.473", LDAP_SERVER_RESP_SORT_OID = "1.2.840.113556.1.4.474", LDAP_PAGED_RESULT_OID_STRING = "1.2.840.113556.1.4.319", LDAP_CONTROL_VLVREQUEST = "2.16.840.1.113730.3.4.9", LDAP_CONTROL_VLVRESPONSE = "2.16.840.1.113730.3.4.10", LDAP_START_TLS_OID = "1.3.6.1.4.1.1466.20037", LDAP_TTL_EXTENDED_OP_OID = "1.3.6.1.4.1.1466.101.119.1"; enum { LDAP_AUTH_NONE = 0x00U, LDAP_AUTH_SIMPLE = 0x80U, LDAP_AUTH_SASL = 0x83U, LDAP_AUTH_OTHERKIND = 0x86U, LDAP_AUTH_EXTERNAL = LDAP_AUTH_OTHERKIND | 0x0020U, LDAP_AUTH_SICILY = LDAP_AUTH_OTHERKIND | 0x0200U, LDAP_AUTH_NEGOTIATE = LDAP_AUTH_OTHERKIND | 0x0400U, LDAP_AUTH_MSN = LDAP_AUTH_OTHERKIND | 0x0800U, LDAP_AUTH_NTLM = LDAP_AUTH_OTHERKIND | 0x1000U, LDAP_AUTH_DIGEST = LDAP_AUTH_OTHERKIND | 0x4000U, LDAP_AUTH_DPA = LDAP_AUTH_OTHERKIND | 0x2000U, LDAP_AUTH_SSPI = LDAP_AUTH_NEGOTIATE } enum { LDAP_FILTER_AND = 0xa0, LDAP_FILTER_OR, LDAP_FILTER_NOT, LDAP_FILTER_EQUALITY, LDAP_FILTER_SUBSTRINGS, LDAP_FILTER_GE, LDAP_FILTER_LE, // = 0xa6 LDAP_FILTER_APPROX = 0xa8, LDAP_FILTER_EXTENSIBLE, LDAP_FILTER_PRESENT = 0x87 } enum { LDAP_SUBSTRING_INITIAL = 0x80, LDAP_SUBSTRING_ANY, LDAP_SUBSTRING_FINAL } struct LDAP { char[76] Reserved; PCHAR ld_host; ULONG ld_version; UCHAR ld_lberoptions; int ld_deref; int ld_timelimit; int ld_sizelimit; int ld_errno; PCHAR ld_matched; PCHAR ld_error; } alias LDAP* PLDAP; struct LDAPMessage { ULONG lm_msgid; ULONG lm_msgtype; BerElement* lm_ber; LDAPMessage* lm_chain; LDAPMessage* lm_next; ULONG lm_time; } alias LDAPMessage* PLDAPMessage; struct LDAP_TIMEVAL { LONG tv_sec; LONG tv_usec; } alias LDAP_TIMEVAL* PLDAP_TIMEVAL; struct LDAPAPIInfoA { int ldapai_info_version; int ldapai_api_version; int ldapai_protocol_version; char** ldapai_extensions; char* ldapai_vendor_name; int ldapai_vendor_version; } alias LDAPAPIInfoA* PLDAPAPIInfoA; struct LDAPAPIInfoW { int ldapai_info_version; int ldapai_api_version; int ldapai_protocol_version; PWCHAR* ldapai_extensions; PWCHAR ldapai_vendor_name; int ldapai_vendor_version; } alias LDAPAPIInfoW* PLDAPAPIInfoW; struct LDAPAPIFeatureInfoA { int ldapaif_info_version; char* ldapaif_name; int ldapaif_version; } alias LDAPAPIFeatureInfoA* PLDAPAPIFeatureInfoA; struct LDAPAPIFeatureInfoW { int ldapaif_info_version; PWCHAR ldapaif_name; int ldapaif_version; } alias LDAPAPIFeatureInfoW* PLDAPAPIFeatureInfoW; struct LDAPControlA { PCHAR ldctl_oid; BerValue ldctl_value; BOOLEAN ldctl_iscritical; } alias LDAPControlA* PLDAPControlA; struct LDAPControlW { PWCHAR ldctl_oid; BerValue ldctl_value; BOOLEAN ldctl_iscritical; } alias LDAPControlW* PLDAPControlW; /* Do we really need these? In MinGW, LDAPModA/W have only mod_op, mod_type * and mod_vals, and macros are used to simulate anonymous unions in those * structures. */ union mod_vals_u_tA { PCHAR* modv_strvals; BerValue** modv_bvals; } union mod_vals_u_tW { PWCHAR* modv_strvals; BerValue** modv_bvals; } struct LDAPModA { ULONG mod_op; PCHAR mod_type; union { mod_vals_u_tA mod_vals; // The following members are defined as macros in MinGW. PCHAR* mod_values; BerValue** mod_bvalues; } } alias LDAPModA* PLDAPModA; struct LDAPModW { ULONG mod_op; PWCHAR mod_type; union { mod_vals_u_tW mod_vals; // The following members are defined as macros in MinGW. PWCHAR* mod_values; BerValue** mod_bvalues; } } alias LDAPModW* PLDAPModW; /* Opaque structure * http://msdn.microsoft.com/library/en-us/ldap/ldap/ldapsearch.asp */ struct LDAPSearch; alias LDAPSearch* PLDAPSearch; struct LDAPSortKeyA { PCHAR sk_attrtype; PCHAR sk_matchruleoid; BOOLEAN sk_reverseorder; } alias LDAPSortKeyA* PLDAPSortKeyA; struct LDAPSortKeyW { PWCHAR sk_attrtype; PWCHAR sk_matchruleoid; BOOLEAN sk_reverseorder; } alias LDAPSortKeyW* PLDAPSortKeyW; /* MinGW defines these as immediate function typedefs, which don't translate * well into D. */ extern (C) { alias ULONG function(PLDAP, PLDAP, PWCHAR, PCHAR, ULONG, PVOID, PVOID, PLDAP*) QUERYFORCONNECTION; alias BOOLEAN function(PLDAP, PLDAP, PWCHAR, PCHAR, PLDAP, ULONG, PVOID, PVOID, ULONG) NOTIFYOFNEWCONNECTION; alias ULONG function(PLDAP, PLDAP) DEREFERENCECONNECTION; alias BOOLEAN function(PLDAP, PSecPkgContext_IssuerListInfoEx, PCCERT_CONTEXT*) QUERYCLIENTCERT; } struct LDAP_REFERRAL_CALLBACK { ULONG SizeOfCallbacks; QUERYFORCONNECTION* QueryForConnection; NOTIFYOFNEWCONNECTION* NotifyRoutine; DEREFERENCECONNECTION* DereferenceRoutine; } alias LDAP_REFERRAL_CALLBACK* PLDAP_REFERRAL_CALLBACK; struct LDAPVLVInfo { int ldvlv_version; uint ldvlv_before_count; uint ldvlv_after_count; uint ldvlv_offset; uint ldvlv_count; BerValue* ldvlv_attrvalue; BerValue* ldvlv_context; void* ldvlv_extradata; } /* * Under Microsoft WinLDAP the function ldap_error is only stub. * This macro uses LDAP structure to get error string and pass it to the user. */ private extern (C) int printf(in char* format, ...); int ldap_perror(LDAP* handle, char* message) { return printf("%s: %s\n", message, handle.ld_error); } /* FIXME: In MinGW, these are WINLDAPAPI == DECLSPEC_IMPORT. Linkage * attribute? */ extern (C) { PLDAP ldap_initA(PCHAR, ULONG); PLDAP ldap_initW(PWCHAR, ULONG); PLDAP ldap_openA(PCHAR, ULONG); PLDAP ldap_openW(PWCHAR, ULONG); PLDAP cldap_openA(PCHAR, ULONG); PLDAP cldap_openW(PWCHAR, ULONG); ULONG ldap_connect(LDAP*, LDAP_TIMEVAL*); PLDAP ldap_sslinitA(PCHAR, ULONG, int); PLDAP ldap_sslinitW(PWCHAR, ULONG, int); ULONG ldap_start_tls_sA(LDAP*, PLDAPControlA*, PLDAPControlA*); ULONG ldap_start_tls_sW(LDAP*, PLDAPControlW*, PLDAPControlW*); BOOLEAN ldap_stop_tls_s(LDAP*); ULONG ldap_get_optionA(LDAP*, int, void*); ULONG ldap_get_optionW(LDAP*, int, void*); ULONG ldap_set_optionA(LDAP*, int, void*); ULONG ldap_set_optionW(LDAP*, int, void*); ULONG ldap_control_freeA(LDAPControlA*); ULONG ldap_control_freeW(LDAPControlW*); ULONG ldap_controls_freeA(LDAPControlA**); ULONG ldap_controls_freeW(LDAPControlW**); ULONG ldap_free_controlsA(LDAPControlA**); ULONG ldap_free_controlsW(LDAPControlW**); ULONG ldap_sasl_bindA(LDAP*, PCHAR, PCHAR, BERVAL*, PLDAPControlA*, PLDAPControlA*, int*); ULONG ldap_sasl_bindW(LDAP*, PWCHAR, PWCHAR, BERVAL*, PLDAPControlW*, PLDAPControlW*, int*); ULONG ldap_sasl_bind_sA(LDAP*, PCHAR, PCHAR, BERVAL*, PLDAPControlA*, PLDAPControlA*, PBERVAL*); ULONG ldap_sasl_bind_sW(LDAP*, PWCHAR, PWCHAR, BERVAL*, PLDAPControlW*, PLDAPControlW*, PBERVAL*); ULONG ldap_simple_bindA(LDAP*, PCHAR, PCHAR); ULONG ldap_simple_bindW(LDAP*, PWCHAR, PWCHAR); ULONG ldap_simple_bind_sA(LDAP*, PCHAR, PCHAR); ULONG ldap_simple_bind_sW(LDAP*, PWCHAR, PWCHAR); ULONG ldap_unbind(LDAP*); ULONG ldap_unbind_s(LDAP*); ULONG ldap_search_extA(LDAP*, PCHAR, ULONG, PCHAR, PCHAR[], ULONG, PLDAPControlW*, PLDAPControlW*, ULONG, ULONG, ULONG*); ULONG ldap_search_extW(LDAP*, PWCHAR, ULONG, PWCHAR, PWCHAR[], ULONG, PLDAPControlW*, PLDAPControlW*, ULONG, ULONG, ULONG*); ULONG ldap_search_ext_sA(LDAP*, PCHAR, ULONG, PCHAR, PCHAR[], ULONG, PLDAPControlA*, PLDAPControlA*, LDAP_TIMEVAL*, ULONG, LDAPMessage**); ULONG ldap_search_ext_sW(LDAP*, PWCHAR, ULONG, PWCHAR, PWCHAR[], ULONG, PLDAPControlW*, PLDAPControlW*, LDAP_TIMEVAL*, ULONG, LDAPMessage**); ULONG ldap_searchA(LDAP*, PCHAR, ULONG, PCHAR, PCHAR[], ULONG); ULONG ldap_searchW(LDAP*, PWCHAR, ULONG, PWCHAR, PWCHAR[], ULONG); ULONG ldap_search_sA(LDAP*, PCHAR, ULONG, PCHAR, PCHAR[], ULONG, LDAPMessage**); ULONG ldap_search_sW(LDAP*, PWCHAR, ULONG, PWCHAR, PWCHAR[], ULONG, LDAPMessage**); ULONG ldap_search_stA(LDAP*, PCHAR, ULONG, PCHAR, PCHAR[], ULONG, LDAP_TIMEVAL*, LDAPMessage**); ULONG ldap_search_stW(LDAP*, PWCHAR, ULONG, PWCHAR, PWCHAR[], ULONG, LDAP_TIMEVAL*, LDAPMessage**); ULONG ldap_compare_extA(LDAP*, PCHAR, PCHAR, PCHAR, BerValue*, PLDAPControlA*, PLDAPControlA*, ULONG*); ULONG ldap_compare_extW(LDAP*, PWCHAR, PWCHAR, PWCHAR, BerValue*, PLDAPControlW*, PLDAPControlW*, ULONG*); ULONG ldap_compare_ext_sA(LDAP*, PCHAR, PCHAR, PCHAR, BerValue*, PLDAPControlA*, PLDAPControlA*); ULONG ldap_compare_ext_sW(LDAP*, PWCHAR, PWCHAR, PWCHAR, BerValue*, PLDAPControlW*, PLDAPControlW*); ULONG ldap_compareA(LDAP*, PCHAR, PCHAR, PCHAR); ULONG ldap_compareW(LDAP*, PWCHAR, PWCHAR, PWCHAR); ULONG ldap_compare_sA(LDAP*, PCHAR, PCHAR, PCHAR); ULONG ldap_compare_sW(LDAP*, PWCHAR, PWCHAR, PWCHAR); ULONG ldap_modify_extA(LDAP*, PCHAR, LDAPModA*[], PLDAPControlA*, PLDAPControlA*, ULONG*); ULONG ldap_modify_extW(LDAP*, PWCHAR, LDAPModW*[], PLDAPControlW*, PLDAPControlW*, ULONG*); ULONG ldap_modify_ext_sA(LDAP*, PCHAR, LDAPModA*[], PLDAPControlA*, PLDAPControlA*); ULONG ldap_modify_ext_sW(LDAP*, PWCHAR, LDAPModW*[], PLDAPControlW*, PLDAPControlW*); ULONG ldap_modifyA(LDAP*, PCHAR, LDAPModA*[]); ULONG ldap_modifyW(LDAP*, PWCHAR, LDAPModW*[]); ULONG ldap_modify_sA(LDAP*, PCHAR, LDAPModA*[]); ULONG ldap_modify_sW(LDAP*, PWCHAR, LDAPModW*[]); ULONG ldap_rename_extA(LDAP*, PCHAR, PCHAR, PCHAR, INT, PLDAPControlA*, PLDAPControlA*, ULONG*); ULONG ldap_rename_extW(LDAP*, PWCHAR, PWCHAR, PWCHAR, INT, PLDAPControlW*, PLDAPControlW*, ULONG*); ULONG ldap_rename_ext_sA(LDAP*, PCHAR, PCHAR, PCHAR, INT, PLDAPControlA*, PLDAPControlA*); ULONG ldap_rename_ext_sW(LDAP*, PWCHAR, PWCHAR, PWCHAR, INT, PLDAPControlW*, PLDAPControlW*); ULONG ldap_add_extA(LDAP*, PCHAR, LDAPModA*[], PLDAPControlA*, PLDAPControlA*, ULONG*); ULONG ldap_add_extW(LDAP*, PWCHAR, LDAPModW*[], PLDAPControlW*, PLDAPControlW*, ULONG*); ULONG ldap_add_ext_sA(LDAP*, PCHAR, LDAPModA*[], PLDAPControlA*, PLDAPControlA*); ULONG ldap_add_ext_sW(LDAP*, PWCHAR, LDAPModW*[], PLDAPControlW*, PLDAPControlW*); ULONG ldap_addA(LDAP*, PCHAR, LDAPModA*[]); ULONG ldap_addW(LDAP*, PWCHAR, LDAPModW*[]); ULONG ldap_add_sA(LDAP*, PCHAR, LDAPModA*[]); ULONG ldap_add_sW(LDAP*, PWCHAR, LDAPModW*[]); ULONG ldap_delete_extA(LDAP*, PCHAR, PLDAPControlA*, PLDAPControlA*, ULONG*); ULONG ldap_delete_extW(LDAP*, PWCHAR, PLDAPControlW*, PLDAPControlW*, ULONG*); ULONG ldap_delete_ext_sA(LDAP*, PCHAR, PLDAPControlA*, PLDAPControlA*); ULONG ldap_delete_ext_sW(LDAP*, PWCHAR, PLDAPControlW*, PLDAPControlW*); ULONG ldap_deleteA(LDAP*, PCHAR); ULONG ldap_deleteW(LDAP*, PWCHAR); ULONG ldap_delete_sA(LDAP*, PCHAR); ULONG ldap_delete_sW(LDAP*, PWCHAR); ULONG ldap_extended_operationA(LDAP*, PCHAR, BerValue*, PLDAPControlA*, PLDAPControlA*, ULONG*); ULONG ldap_extended_operationW(LDAP*, PWCHAR, BerValue*, PLDAPControlW*, PLDAPControlW*, ULONG*); ULONG ldap_extended_operation_sA(LDAP*, PCHAR, BerValue*, PLDAPControlA*, PLDAPControlA*, PCHAR*, BerValue**); ULONG ldap_extended_operation_sW(LDAP*, PWCHAR, BerValue*, PLDAPControlW*, PLDAPControlW*, PWCHAR*, BerValue**); ULONG ldap_close_extended_op(LDAP*, ULONG); ULONG ldap_abandon(LDAP*, ULONG); ULONG ldap_result(LDAP*, ULONG, ULONG, LDAP_TIMEVAL*, LDAPMessage**); ULONG ldap_msgfree(LDAPMessage*); ULONG ldap_parse_resultA(LDAP*, LDAPMessage*, ULONG*, PCHAR*, PCHAR*, PCHAR**, PLDAPControlA**, BOOLEAN); ULONG ldap_parse_resultW(LDAP*, LDAPMessage*, ULONG*, PWCHAR*, PWCHAR*, PWCHAR**, PLDAPControlW**, BOOLEAN); ULONG ldap_parse_extended_resultA(LDAP, LDAPMessage*, PCHAR*, BerValue**, BOOLEAN); ULONG ldap_parse_extended_resultW(LDAP, LDAPMessage*, PWCHAR*, BerValue**, BOOLEAN); PCHAR ldap_err2stringA(ULONG); PWCHAR ldap_err2stringW(ULONG); ULONG LdapGetLastError(); ULONG LdapMapErrorToWin32(ULONG); ULONG ldap_result2error(LDAP*, LDAPMessage*, ULONG); PLDAPMessage ldap_first_entry(LDAP*, LDAPMessage*); PLDAPMessage ldap_next_entry(LDAP*, LDAPMessage*); PLDAPMessage ldap_first_reference(LDAP*, LDAPMessage*); PLDAPMessage ldap_next_reference(LDAP*, LDAPMessage*); ULONG ldap_count_entries(LDAP*, LDAPMessage*); ULONG ldap_count_references(LDAP*, LDAPMessage*); PCHAR ldap_first_attributeA(LDAP*, LDAPMessage*, BerElement**); PWCHAR ldap_first_attributeW(LDAP*, LDAPMessage*, BerElement**); PCHAR ldap_next_attributeA(LDAP*, LDAPMessage*, BerElement*); PWCHAR ldap_next_attributeW(LDAP*, LDAPMessage*, BerElement*); VOID ldap_memfreeA(PCHAR); VOID ldap_memfreeW(PWCHAR); PCHAR* ldap_get_valuesA(LDAP*, LDAPMessage*, PCHAR); PWCHAR* ldap_get_valuesW(LDAP*, LDAPMessage*, PWCHAR); BerValue** ldap_get_values_lenA(LDAP*, LDAPMessage*, PCHAR); BerValue** ldap_get_values_lenW(LDAP*, LDAPMessage*, PWCHAR); ULONG ldap_count_valuesA(PCHAR*); ULONG ldap_count_valuesW(PWCHAR*); ULONG ldap_count_values_len(BerValue**); ULONG ldap_value_freeA(PCHAR*); ULONG ldap_value_freeW(PWCHAR*); ULONG ldap_value_free_len(BerValue**); PCHAR ldap_get_dnA(LDAP*, LDAPMessage*); PWCHAR ldap_get_dnW(LDAP*, LDAPMessage*); PCHAR ldap_explode_dnA(PCHAR, ULONG); PWCHAR ldap_explode_dnW(PWCHAR, ULONG); PCHAR ldap_dn2ufnA(PCHAR); PWCHAR ldap_dn2ufnW(PWCHAR); ULONG ldap_ufn2dnA(PCHAR, PCHAR*); ULONG ldap_ufn2dnW(PWCHAR, PWCHAR*); ULONG ldap_parse_referenceA(LDAP*, LDAPMessage*, PCHAR**); ULONG ldap_parse_referenceW(LDAP*, LDAPMessage*, PWCHAR**); ULONG ldap_check_filterA(LDAP*, PCHAR); ULONG ldap_check_filterW(LDAP*, PWCHAR); ULONG ldap_create_page_controlA(PLDAP, ULONG, BerValue*, UCHAR, PLDAPControlA*); ULONG ldap_create_page_controlW(PLDAP, ULONG, BerValue*, UCHAR, PLDAPControlW*); ULONG ldap_create_sort_controlA(PLDAP, PLDAPSortKeyA*, UCHAR, PLDAPControlA*); ULONG ldap_create_sort_controlW(PLDAP, PLDAPSortKeyW*, UCHAR, PLDAPControlW*); INT ldap_create_vlv_controlA(LDAP*, LDAPVLVInfo*, UCHAR, LDAPControlA**); INT ldap_create_vlv_controlW(LDAP*, LDAPVLVInfo*, UCHAR, LDAPControlW**); ULONG ldap_encode_sort_controlA(PLDAP, PLDAPSortKeyA*, PLDAPControlA, BOOLEAN); ULONG ldap_encode_sort_controlW(PLDAP, PLDAPSortKeyW*, PLDAPControlW, BOOLEAN); ULONG ldap_escape_filter_elementA(PCHAR, ULONG, PCHAR, ULONG); ULONG ldap_escape_filter_elementW(PWCHAR, ULONG, PWCHAR, ULONG); ULONG ldap_get_next_page(PLDAP, PLDAPSearch, ULONG, ULONG*); ULONG ldap_get_next_page_s(PLDAP, PLDAPSearch, LDAP_TIMEVAL*, ULONG, ULONG*, LDAPMessage**); ULONG ldap_get_paged_count(PLDAP, PLDAPSearch, ULONG*, PLDAPMessage); ULONG ldap_parse_page_controlA(PLDAP, PLDAPControlA*, ULONG*, BerValue**); ULONG ldap_parse_page_controlW(PLDAP, PLDAPControlW*, ULONG*, BerValue**); ULONG ldap_parse_sort_controlA(PLDAP, PLDAPControlA*, ULONG*, PCHAR*); ULONG ldap_parse_sort_controlW(PLDAP, PLDAPControlW*, ULONG*, PWCHAR*); INT ldap_parse_vlv_controlA(LDAP*, LDAPControlA**, uint*, uint*, BerValue**, int*); INT ldap_parse_vlv_controlW(LDAP*, LDAPControlW**, uint*, uint*, BerValue**, int*); PLDAPSearch ldap_search_init_pageA(PLDAP, PCHAR, ULONG, PCHAR, PCHAR[], ULONG, PLDAPControlA*, PLDAPControlA*, ULONG, ULONG, PLDAPSortKeyA*); PLDAPSearch ldap_search_init_pageW(PLDAP, PWCHAR, ULONG, PWCHAR, PWCHAR[], ULONG, PLDAPControlW*, PLDAPControlW*, ULONG, ULONG, PLDAPSortKeyW*); ULONG ldap_search_abandon_page(PLDAP, PLDAPSearch); LDAP ldap_conn_from_msg(LDAP*, LDAPMessage*); INT LdapUnicodeToUTF8(LPCWSTR, int, LPSTR, int); INT LdapUTF8ToUnicode(LPCSTR, int, LPWSTR, int); deprecated { ULONG ldap_bindA(LDAP*, PCHAR, PCHAR, ULONG); ULONG ldap_bindW(LDAP*, PWCHAR, PWCHAR, ULONG); ULONG ldap_bind_sA(LDAP*, PCHAR, PCHAR, ULONG); ULONG ldap_bind_sW(LDAP*, PWCHAR, PWCHAR, ULONG); ULONG ldap_modrdnA(LDAP*, PCHAR, PCHAR); ULONG ldap_modrdnW(LDAP*, PWCHAR, PWCHAR); ULONG ldap_modrdn_sA(LDAP*, PCHAR, PCHAR); ULONG ldap_modrdn_sW(LDAP*, PWCHAR, PWCHAR); ULONG ldap_modrdn2A(LDAP*, PCHAR, PCHAR, INT); ULONG ldap_modrdn2W(LDAP*, PWCHAR, PWCHAR, INT); ULONG ldap_modrdn2_sA(LDAP*, PCHAR, PCHAR, INT); ULONG ldap_modrdn2_sW(LDAP*, PWCHAR, PWCHAR, INT); } } version (Unicode) { alias LDAPControlW LDAPControl; alias PLDAPControlW PLDAPControl; alias LDAPModW LDAPMod; alias LDAPModW PLDAPMod; alias LDAPSortKeyW LDAPSortKey; alias PLDAPSortKeyW PLDAPSortKey; alias LDAPAPIInfoW LDAPAPIInfo; alias PLDAPAPIInfoW PLDAPAPIInfo; alias LDAPAPIFeatureInfoW LDAPAPIFeatureInfo; alias PLDAPAPIFeatureInfoW PLDAPAPIFeatureInfo; alias cldap_openW cldap_open; alias ldap_openW ldap_open; alias ldap_simple_bindW ldap_simple_bind; alias ldap_simple_bind_sW ldap_simple_bind_s; alias ldap_sasl_bindW ldap_sasl_bind; alias ldap_sasl_bind_sW ldap_sasl_bind_s; alias ldap_initW ldap_init; alias ldap_sslinitW ldap_sslinit; alias ldap_get_optionW ldap_get_option; alias ldap_set_optionW ldap_set_option; alias ldap_start_tls_sW ldap_start_tls_s; alias ldap_addW ldap_add; alias ldap_add_extW ldap_add_ext; alias ldap_add_sW ldap_add_s; alias ldap_add_ext_sW ldap_add_ext_s; alias ldap_compareW ldap_compare; alias ldap_compare_extW ldap_compare_ext; alias ldap_compare_sW ldap_compare_s; alias ldap_compare_ext_sW ldap_compare_ext_s; alias ldap_deleteW ldap_delete; alias ldap_delete_extW ldap_delete_ext; alias ldap_delete_sW ldap_delete_s; alias ldap_delete_ext_sW ldap_delete_ext_s; alias ldap_extended_operation_sW ldap_extended_operation_s; alias ldap_extended_operationW ldap_extended_operation; alias ldap_modifyW ldap_modify; alias ldap_modify_extW ldap_modify_ext; alias ldap_modify_sW ldap_modify_s; alias ldap_modify_ext_sW ldap_modify_ext_s; alias ldap_check_filterW ldap_check_filter; alias ldap_count_valuesW ldap_count_values; alias ldap_create_page_controlW ldap_create_page_control; alias ldap_create_sort_controlW ldap_create_sort_control; alias ldap_create_vlv_controlW ldap_create_vlv_control; alias ldap_encode_sort_controlW ldap_encode_sort_control; alias ldap_escape_filter_elementW ldap_escape_filter_element; alias ldap_first_attributeW ldap_first_attribute; alias ldap_next_attributeW ldap_next_attribute; alias ldap_get_valuesW ldap_get_values; alias ldap_get_values_lenW ldap_get_values_len; alias ldap_parse_extended_resultW ldap_parse_extended_result; alias ldap_parse_page_controlW ldap_parse_page_control; alias ldap_parse_referenceW ldap_parse_reference; alias ldap_parse_resultW ldap_parse_result; alias ldap_parse_sort_controlW ldap_parse_sort_control; alias ldap_parse_vlv_controlW ldap_parse_vlv_control; alias ldap_searchW ldap_search; alias ldap_search_sW ldap_search_s; alias ldap_search_stW ldap_search_st; alias ldap_search_extW ldap_search_ext; alias ldap_search_ext_sW ldap_search_ext_s; alias ldap_search_init_pageW ldap_search_init_page; alias ldap_err2stringW ldap_err2string; alias ldap_control_freeW ldap_control_free; alias ldap_controls_freeW ldap_controls_free; alias ldap_free_controlsW ldap_free_controls; alias ldap_memfreeW ldap_memfree; alias ldap_value_freeW ldap_value_free; alias ldap_dn2ufnW ldap_dn2ufn; alias ldap_ufn2dnW ldap_ufn2dn; alias ldap_explode_dnW ldap_explode_dn; alias ldap_get_dnW ldap_get_dn; alias ldap_rename_extW ldap_rename; alias ldap_rename_ext_sW ldap_rename_s; alias ldap_rename_extW ldap_rename_ext; alias ldap_rename_ext_sW ldap_rename_ext_s; deprecated { alias ldap_bindW ldap_bind; alias ldap_bind_sW ldap_bind_s; alias ldap_modrdnW ldap_modrdn; alias ldap_modrdn_sW ldap_modrdn_s; alias ldap_modrdn2W ldap_modrdn2; alias ldap_modrdn2_sW ldap_modrdn2_s; } } else { alias LDAPControlA LDAPControl; alias PLDAPControlA PLDAPControl; alias LDAPModA LDAPMod; alias LDAPModA PLDAPMod; alias LDAPSortKeyA LDAPSortKey; alias PLDAPSortKeyA PLDAPSortKey; alias LDAPAPIInfoA LDAPAPIInfo; alias PLDAPAPIInfoA PLDAPAPIInfo; alias LDAPAPIFeatureInfoA LDAPAPIFeatureInfo; alias PLDAPAPIFeatureInfoA PLDAPAPIFeatureInfo; alias cldap_openA cldap_open; alias ldap_openA ldap_open; alias ldap_simple_bindA ldap_simple_bind; alias ldap_simple_bind_sA ldap_simple_bind_s; alias ldap_sasl_bindA ldap_sasl_bind; alias ldap_sasl_bind_sA ldap_sasl_bind_s; alias ldap_initA ldap_init; alias ldap_sslinitA ldap_sslinit; alias ldap_get_optionA ldap_get_option; alias ldap_set_optionA ldap_set_option; alias ldap_start_tls_sA ldap_start_tls_s; alias ldap_addA ldap_add; alias ldap_add_extA ldap_add_ext; alias ldap_add_sA ldap_add_s; alias ldap_add_ext_sA ldap_add_ext_s; alias ldap_compareA ldap_compare; alias ldap_compare_extA ldap_compare_ext; alias ldap_compare_sA ldap_compare_s; alias ldap_compare_ext_sA ldap_compare_ext_s; alias ldap_deleteA ldap_delete; alias ldap_delete_extA ldap_delete_ext; alias ldap_delete_sA ldap_delete_s; alias ldap_delete_ext_sA ldap_delete_ext_s; alias ldap_extended_operation_sA ldap_extended_operation_s; alias ldap_extended_operationA ldap_extended_operation; alias ldap_modifyA ldap_modify; alias ldap_modify_extA ldap_modify_ext; alias ldap_modify_sA ldap_modify_s; alias ldap_modify_ext_sA ldap_modify_ext_s; alias ldap_check_filterA ldap_check_filter; alias ldap_count_valuesA ldap_count_values; alias ldap_create_page_controlA ldap_create_page_control; alias ldap_create_sort_controlA ldap_create_sort_control; alias ldap_create_vlv_controlA ldap_create_vlv_control; alias ldap_encode_sort_controlA ldap_encode_sort_control; alias ldap_escape_filter_elementA ldap_escape_filter_element; alias ldap_first_attributeA ldap_first_attribute; alias ldap_next_attributeA ldap_next_attribute; alias ldap_get_valuesA ldap_get_values; alias ldap_get_values_lenA ldap_get_values_len; alias ldap_parse_extended_resultA ldap_parse_extended_result; alias ldap_parse_page_controlA ldap_parse_page_control; alias ldap_parse_referenceA ldap_parse_reference; alias ldap_parse_resultA ldap_parse_result; alias ldap_parse_sort_controlA ldap_parse_sort_control; alias ldap_parse_vlv_controlA ldap_parse_vlv_control; alias ldap_searchA ldap_search; alias ldap_search_sA ldap_search_s; alias ldap_search_stA ldap_search_st; alias ldap_search_extA ldap_search_ext; alias ldap_search_ext_sA ldap_search_ext_s; alias ldap_search_init_pageA ldap_search_init_page; alias ldap_err2stringA ldap_err2string; alias ldap_control_freeA ldap_control_free; alias ldap_controls_freeA ldap_controls_free; alias ldap_free_controlsA ldap_free_controls; alias ldap_memfreeA ldap_memfree; alias ldap_value_freeA ldap_value_free; alias ldap_dn2ufnA ldap_dn2ufn; alias ldap_ufn2dnA ldap_ufn2dn; alias ldap_explode_dnA ldap_explode_dn; alias ldap_get_dnA ldap_get_dn; alias ldap_rename_extA ldap_rename; alias ldap_rename_ext_sA ldap_rename_s; alias ldap_rename_extA ldap_rename_ext; alias ldap_rename_ext_sA ldap_rename_ext_s; deprecated { alias ldap_bindA ldap_bind; alias ldap_bind_sA ldap_bind_s; alias ldap_modrdnA ldap_modrdn; alias ldap_modrdn_sA ldap_modrdn_s; alias ldap_modrdn2A ldap_modrdn2; alias ldap_modrdn2_sA ldap_modrdn2_s; } }
D
/// module ddb.pg.exceptions; import ddb.pg.messages : ResponseMessage; import std.exception; public import std.exception : enforce; @safe: class ParamException : Exception { this(string msg, string fn = __FILE__, size_t ln = __LINE__) pure nothrow { super(msg, fn, ln); } } /// Exception thrown on server error class PGServerErrorException: Exception { /// Contains information about this _error. Aliased to this. ResponseMessage error; alias error this; this(string msg, string fn = __FILE__, size_t ln = __LINE__) pure nothrow { super(msg, fn, ln); } this(ResponseMessage error, string fn = __FILE__, size_t ln = __LINE__) { super(error.toString(), fn, ln); this.error = error; } } /// class TransactionException : Exception { this(string msg, Throwable thr) { super(msg, thr); } } /// class CommitTransactionException : TransactionException { this(string msg, Throwable thr) { super(msg, thr); } } /// class RollbackTransactionException : TransactionException { this(string msg, Throwable thr) { super(msg, thr); } }
D
module imports.gdc241b; class C241 { } enum E241 { a } struct S241 { } extern(C++, N241) { struct T { } }
D
INSTANCE Mod_7219_BDT_Bandit_NW (Npc_Default) { // ------ NSC ------ name = "Räuber"; guild = GIL_STRF; id = 7219; voice = 0; flags = 0; npctype = NPCTYPE_nw_bandit; // ------ Attribute ------ B_SetAttributesToChapter (self, 3); // ------ Kampf-Taktik ------ fight_tactic = FAI_HUMAN_strong; // ------ Equippte Waffen ------ EquipItem (self, ItMw_Banditenschwert_Andre); B_SetAttitude (self, ATT_HOSTILE); // ------ Inventory ------ B_CreateAmbientInv (self); // ------ visuals ------ B_SetNpcVisual (self, MALE, "Hum_Head_Bald", Face_N_Normal06, BodyTex_N, ITAR_BDT_M_01); Mdl_SetModelFatness (self, -1); Mdl_ApplyOverlayMds (self, "Humans_Relaxed.mds"); // ------ NSC-relevante Talente vergeben ------ B_GiveNpcTalents (self); // ------ Kampf-Talente ------ B_SetFightSkills (self, 50); // ------ TA anmelden ------ daily_routine = Rtn_Start_7219; }; FUNC VOID Rtn_Start_7219 () { TA_Sit_Campfire (08,00,23,00,"NW_FOREST_CAVE1_IN_05"); TA_Sit_Campfire (23,00,08,00,"NW_FOREST_CAVE1_IN_05"); };
D
/** Vibe-based AWS client */ module vibe.aws.aws; import std.algorithm; import std.datetime; import std.random; import std.range; import std.stdio; import std.string; import vibe.core.core; import vibe.core.log; import vibe.data.json; import vibe.http.client; import vibe.aws.sigv4; public import vibe.aws.credentials; class AWSException : Exception { immutable string type; immutable bool retriable; this(string type, bool retriable, string message) { super(type ~ ": " ~ message); this.type = type; this.retriable = retriable; } /** Returns the 'ThrottlingException' from 'com.amazon.coral.service#ThrottlingException' */ @property string simpleType() { auto h = type.indexOf('#'); if (h == -1) return type; return type[h+1..$]; } } /** Configuraton for AWS clients */ struct ClientConfiguration { uint maxErrorRetry = 3; } /** Thrown when the signature/authorization information is wrong */ class AuthorizationException : AWSException { this(string type, string message) { super(type, false, message); } } struct ExponentialBackoff { immutable uint maxRetries; uint tries = 0; uint maxSleepMs = 10; this(uint maxRetries) { this.maxRetries = maxRetries; } @property bool canRetry() { return tries < maxRetries; } @property bool finished() { return tries >= maxRetries + 1; } void inc() { tries++; maxSleepMs *= 2; } void sleep() { vibe.core.core.sleep(uniform!("[]")(1, maxSleepMs).msecs); } } class AWSClient { protected static immutable exceptionPrefix = "com.amazon.coral.service#"; immutable string endpoint; immutable string region; immutable string service; private AWSCredentialSource m_credsSource; private ClientConfiguration m_config; this(string endpoint, string region, string service, AWSCredentialSource credsSource, ClientConfiguration config=ClientConfiguration()) { this.region = region; this.endpoint = endpoint; this.service = service; this.m_credsSource = credsSource; this.m_config = config; } AWSResponse doRequest(string operation, Json request) { auto backoff = ExponentialBackoff(m_config.maxErrorRetry); for (; !backoff.finished; backoff.inc()) { auto credScope = region ~ "/" ~ service; auto creds = m_credsSource.credentials(credScope); HTTPClientResponse resp; try { // FIXME: Auto-retries for retriable errors // FIXME: Report credential errors and retry for failed credentials resp = requestHTTP("https://" ~ endpoint ~ "/", (scope req) { auto timeString = currentTimeString(); auto jsonString = cast(ubyte[])request.toString(); req.method = HTTPMethod.POST; req.headers["x-amz-target"] = operation; req.headers["x-amz-date"] = currentTimeString(); req.headers["host"] = endpoint; if (creds.sessionToken && !creds.sessionToken.empty) req.headers["x-amz-security-token"] = creds.sessionToken; req.contentType = "application/x-amz-json-1.1"; signRequest(req, jsonString, creds, timeString, region, service); req.writeBody(jsonString); }); checkForError(resp); return new AWSResponse(resp); } catch (AuthorizationException ex) { logWarn(ex.msg); // Report credentials as invalid. Will retry if possible. m_credsSource.credentialsInvalid(credScope, creds, ex.msg); resp.dropBody(); resp.destroy(); if (!backoff.canRetry) throw ex; } catch (AWSException ex) { logWarn(ex.msg); resp.dropBody(); resp.destroy(); // Retry if possible and retriable, otherwise give up. if (!backoff.canRetry || !ex.retriable) throw ex; } catch (Throwable t) //ssl errors from ssl.d { if (!backoff.canRetry) { logError("no retries left, failing request"); throw(t); } } backoff.sleep(); } assert(0); } protected auto currentTimeString() { auto t = Clock.currTime(UTC()); t.fracSec = FracSec.zero(); return t.toISOString(); } void checkForError(HTTPClientResponse response) { if (response.statusCode < 400) return; // No error auto bod = response.readJson(); throw makeException(bod.__type.get!string, response.statusCode / 100 == 5, bod.message.opt!string("")); } AWSException makeException(string type, bool retriable, string message) { if (type == exceptionPrefix ~ "UnrecognizedClientException" || type == exceptionPrefix ~ "InvalidSignatureException") throw new AuthorizationException(type, message); return new AWSException(type, retriable, message); } } private void signRequest(HTTPClientRequest req, ubyte[] requestBody, AWSCredentials creds, string timeString, string region, string service) { auto dateString = dateFromISOString(timeString); auto credScope = dateString ~ "/" ~ region ~ "/" ~ service; SignableRequest signRequest; signRequest.dateString = dateString; signRequest.timeStringUTC = timeFromISOString(timeString); signRequest.region = region; signRequest.service = service; signRequest.canonicalRequest.method = req.method.to!string(); signRequest.canonicalRequest.uri = req.requestURL; // FIXME: Can include query params auto reqHeaders = req.headers.toRepresentation; foreach (x; reqHeaders) { signRequest.canonicalRequest.headers[x.key] = x.value; } signRequest.canonicalRequest.payload = requestBody; ubyte[] signKey = signingKey(creds.accessKeySecret, dateString, region, service); ubyte[] stringToSign = cast(ubyte[])signableString(signRequest); auto signature = sign(signKey, stringToSign); auto authHeader = createSignatureHeader(creds.accessKeyID, credScope, signRequest.canonicalRequest.headers, signature); req.headers["authorization"] = authHeader; } class AWSResponse { private Json m_body; this(HTTPClientResponse response) { //m_response = response; m_body = response.readJson(); response.dropBody(); response.destroy(); } override string toString() { return m_body.toString(); } @property Json responseBody() { return m_body; } }
D
/*============================================================================= spiritd - Copyright (c) 2009 s.d.hammett a D2 parser library ported from boost::spirit Copyright (c) 1998-2003 Joel de Guzman Copyright (c) 2001 Daniel Nuffer Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ module spiritd.impl.directives; import spiritd.match; import spiritd.scanner; import spiritd.skipper; import spiritd.composite.directivesCommon; /**\brief function to turn off skipping so parsers can work at the character level */ resultT contiguousParserParse(resultT, parserT, scannerT)(parserT p, scannerT s) { alias noSkipPolicy!(scannerT._valueT, scannerT._iterationPolicyT) noSkipPoliciesT; scope noskipPol = new noSkipPoliciesT; s.skip(s); scope noSkipScanner = s.changeIterPolicies!(noSkipPoliciesT)(s, noskipPol); auto m = p.parse(noSkipScanner); if(m.match) s.first = noSkipScanner.first; return m; } resultT implicitLexemeParse(resultT, parserT, scannerT)(parserT p, scannerT s) { alias noSkipPolicy!(scannerT._valueT, scannerT._iterationPolicyT) noSkipPoliciesT; scope noskipPol = new noSkipPoliciesT; s.skip(s); scope noSkipScanner = s.changeIterPolicies!(noSkipPoliciesT)(s, noskipPol); auto m = p.parseMain(noSkipScanner); if(m.match) s.first = noSkipScanner.first; return m; } resultT inhibitCaseParserParse(resultT, parserT, scannerT)(parserT p, scannerT s) { alias inhibitCasePolicy!(scannerT._iterationPolicyT) inhibCasePoliciesT; scope nocasePol = new inhibCasePoliciesT; s.skip(s); scope inhibitCaseScanner = s.changeIterPolicies!(inhibCasePoliciesT)(s, nocasePol); auto m = p.parse(inhibitCaseScanner); if(m.match) s.first = inhibitCaseScanner.first; return conv(m); }
D
/** Optimised asm arbitrary точность arithmetic ('bignum') * routines for X86 processors. * * All functions operate on массивы of uints, stored LSB first. * If there is a destination array, it will be the first parameter. * Currently, all of these functions are субъект to change, and are * intended for internal use only. * The symbol [#] indicates an array of machine words which is to be * interpreted as a multi-byte число. * * Copyright: Copyright (C) 2008 Don Clugston. All rights reserved. * License: BSD style: $(LICENSE) * Authors: Don Clugston */ /** * In simple terms, there are 3 modern x86 microarchitectures: * (a) the P6 семейство (Pentium Pro, PII, PIII, PM, Core), produced by Intel; * (b) the K6, Athlon, and AMD64 families, produced by AMD; and * (c) the Pentium 4, produced by Marketing. * * This код есть been optimised for the Intel P6 семейство. * Generally the код remains near-optimal for Intel Core2, after translating * EAX-> RAX, etc, since all these CPUs use essentially the same pИПeline, and * are typically limited by memory access. * The код uses techniques described in Agner Fog's superb Pentium manuals * available at www.agner.org. * Not optimised for AMD, which can do two memory loads per cycle (Intel * CPUs can only do one). Despite this, performance is superior on AMD. * Performance is dreadful on P4. * * Timing results (cycles per цел) * --Intel Pentium-- --AMD-- * PM P4 Core2 K7 * +,- 2.25 15.6 2.25 1.5 * <<,>> 2.0 6.6 2.0 5.0 * (<< MMX) 1.7 5.3 1.5 1.2 * * 5.0 15.0 4.0 4.3 * mulAdd 5.7 19.0 4.9 4.0 * div 30.0 32.0 32.0 22.4 * mulAcc(32) 6.5 20.0 5.4 4.9 * * mulAcc(32) is multИПlyAccumulate() for a 32*32 multИПly. Thus it includes * function call overhead. * The timing for Div is quite unpredictable, but it's probably too slow * to be useful. On 64-bit processors, these times should * halve if run in 64-bit режим, except for the MMX functions. */ module math.internal.BignumX86; /* Naked asm is used throughout, because: (a) it frees up the EBP register (b) compiler bugs prevent the use of .ptr when a frame pointer is used. */ version(GNU) { // GDC is a filthy liar. It can't actually do inline asm. } else version(D_InlineAsm_X86) { version = Really_D_InlineAsm_X86; } else version(LLVM_InlineAsm_X86) { version = Really_D_InlineAsm_X86; } version(Really_D_InlineAsm_X86) { private: /* Duplicate ткст s, with n times, substituting index for '@'. * * Each instance of '@' in s is replaced by 0,1,...n-1. This is a helper * function for some of the asm routines. */ сим [] откатиИндексированныйЦикл(цел n, сим [] s) { сим [] u; for (цел i = 0; i<n; ++i) { сим [] nstr= (i>9 ? ""~ cast(сим)('0'+i/10) : "") ~ cast(сим)('0' + i%10); цел последний = 0; for (цел j = 0; j<s.length; ++j) { if (s[j]=='@') { u ~= s[последний..j] ~ nstr; последний = j+1; } } if (последний<s.length) u = u ~ s[последний..$]; } return u; } debug (UnitTest) { unittest { assert(откатиИндексированныйЦикл(3, "@*23;")=="0*23;1*23;2*23;"); } } public: alias бцел БольшЦифра; // A Bignum is an array of BigDigits. Usually the machine word size. // Limits for when to switch between multИПlication algorithms. enum : цел { KARATSUBALIMIT = 18 }; // Minimum value for which Karatsuba is worthwhile. enum : цел { KARATSUBASQUARELIMIT=26 }; // Minimum value for which square Karatsuba is worthwhile /** Multi-byte addition or subtraction * приёмник[#] = src1[#] + src2[#] + carry (0 or 1). * or приёмник[#] = src1[#] - src2[#] - carry (0 or 1). * Returns carry or borrow (0 or 1). * Набор op == '+' for addition, '-' for subtraction. */ бцел многобайтПрибавОтним(сим op)(бцел[] приёмник, бцел [] src1, бцел [] src2, бцел carry) { // Timing: // Pentium M: 2.25/цел // P6 семейство, Core2 have a partial flags stall when reading the carry flag in // an ADC, SBB operation after an operation such as INC or DEC which // modifies some, but not all, flags. We avoопр this by storing carry преобр_в // a resister (AL), and restoring it after the branch. enum { LASTPARAM = 4*4 } // 3* pushes + return address. asm { naked; push EDI; push EBX; push ESI; mov ECX, [ESP + LASTPARAM + 4*4]; // приёмник.length; mov EDX, [ESP + LASTPARAM + 3*4]; // src1.ptr mov ESI, [ESP + LASTPARAM + 1*4]; // src2.ptr mov EDI, [ESP + LASTPARAM + 5*4]; // приёмник.ptr // Carry is in EAX // Count UP to zero (from -len) to minimize loop overhead. lea EDX, [EDX + 4*ECX]; // EDX = end of src1. lea ESI, [ESI + 4*ECX]; // EBP = end of src2. lea EDI, [EDI + 4*ECX]; // EDI = end of приёмник. neg ECX; add ECX, 8; jb L2; // if length < 8 , bypass the unrolled loop. L_unrolled: shr AL, 1; // get carry from EAX } mixin(" asm {" ~ откатиИндексированныйЦикл( 8, "mov EAX, [@*4-8*4+EDX+ECX*4];" ~ ( op == '+' ? "adc" : "sbb" ) ~ " EAX, [@*4-8*4+ESI+ECX*4];" "mov [@*4-8*4+EDI+ECX*4], EAX;") ~ "}"); asm { setc AL; // save carry add ECX, 8; ja L_unrolled; L2: // Do the resопрual 1..7 ints. sub ECX, 8; jz done; L_resопрual: shr AL, 1; // get carry from EAX } mixin(" asm {" ~ откатиИндексированныйЦикл( 1, "mov EAX, [@*4+EDX+ECX*4];" ~ ( op == '+' ? "adc" : "sbb" ) ~ " EAX, [@*4+ESI+ECX*4];" "mov [@*4+EDI+ECX*4], EAX;") ~ "}"); asm { setc AL; // save carry add ECX, 1; jnz L_resопрual; done: and EAX, 1; // make it O or 1. pop ESI; pop EBX; pop EDI; ret 6*4; } } debug (UnitTest) { unittest { бцел [] a = new бцел[40]; бцел [] b = new бцел[40]; бцел [] c = new бцел[40]; for (цел i=0; i<a.length; ++i) { if (i&1) a[i]=0x8000_0000 + i; else a[i]=i; b[i]= 0x8000_0003; } c[19]=0x3333_3333; бцел carry = многобайтПрибавОтним!('+')(c[0..18], a[0..18], b[0..18], 0); assert(carry==1); assert(c[0]==0x8000_0003); assert(c[1]==4); assert(c[19]==0x3333_3333); // check for overrun for (цел i=0; i<a.length; ++i) { a[i]=b[i]=c[i]=0; } a[8]=0x048D159E; b[8]=0x048D159E; a[10]=0x1D950C84; b[10]=0x1D950C84; a[5] =0x44444444; carry = многобайтПрибавОтним!('-')(a[0..12], a[0..12], b[0..12], 0); assert(a[11]==0); for (цел i=0; i<10; ++i) if (i!=5) assert(a[i]==0); for (цел q=3; q<36; ++q) { for (цел i=0; i<a.length; ++i) { a[i]=b[i]=c[i]=0; } a[q-2]=0x040000; b[q-2]=0x040000; carry = многобайтПрибавОтним!('-')(a[0..q], a[0..q], b[0..q], 0); assert(a[q-2]==0); } } } /** приёмник[#] += carry, or приёмник[#] -= carry. * op must be '+' or '-' * Returns final carry or borrow (0 or 1) */ бцел многобайтИнкрПрисвой(сим op)(бцел[] приёмник, бцел carry) { enum { LASTPARAM = 1*4 } // 0* pushes + return address. asm { naked; mov ECX, [ESP + LASTPARAM + 0*4]; // приёмник.length; mov EDX, [ESP + LASTPARAM + 1*4]; // приёмник.ptr // EAX = carry L1: ; } static if (op=='+') asm { add [EDX], EAX; } else asm { sub [EDX], EAX; } asm { mov EAX, 1; jnc L2; add EDX, 4; dec ECX; jnz L1; mov EAX, 2; L2: dec EAX; ret 2*4; } } /** приёмник[#] = src[#] << numbits * numbits must be in the range 1..31 * Returns the overflow */ бцел многобайтСдвигЛБезММХ(бцел [] приёмник, бцел [] src, бцел numbits) { // Timing: Optimal for P6 семейство. // 2.0 cycles/цел on PPro..PM (limited by execution порт p0) // 5.0 cycles/цел on Athlon, which есть 7 cycles for SHLD!! enum { LASTPARAM = 4*4 } // 3* pushes + return address. asm { naked; push ESI; push EDI; push EBX; mov EDI, [ESP + LASTPARAM + 4*3]; //приёмник.ptr; mov EBX, [ESP + LASTPARAM + 4*2]; //приёмник.length; mov ESI, [ESP + LASTPARAM + 4*1]; //src.ptr; mov ECX, EAX; // numbits; mov EAX, [-4+ESI + 4*EBX]; mov EDX, 0; shld EDX, EAX, CL; push EDX; // Save return value cmp EBX, 1; jz L_last; mov EDX, [-4+ESI + 4*EBX]; test EBX, 1; jz L_odd; sub EBX, 1; L_even: mov EDX, [-4+ ESI + 4*EBX]; shld EAX, EDX, CL; mov [EDI+4*EBX], EAX; L_odd: mov EAX, [-8+ESI + 4*EBX]; shld EDX, EAX, CL; mov [-4+EDI + 4*EBX], EDX; sub EBX, 2; jg L_even; L_last: shl EAX, CL; mov [EDI], EAX; pop EAX; // pop return value pop EBX; pop EDI; pop ESI; ret 4*4; } } /** приёмник[#] = src[#] >> numbits * numbits must be in the range 1..31 * This version uses MMX. */ бцел многобайтСдвигЛ(бцел [] приёмник, бцел [] src, бцел numbits) { // Timing: // K7 1.2/цел. PM 1.7/цел P4 5.3/цел enum { LASTPARAM = 4*4 } // 3* pushes + return address. asm { naked; push ESI; push EDI; push EBX; mov EDI, [ESP + LASTPARAM + 4*3]; //приёмник.ptr; mov EBX, [ESP + LASTPARAM + 4*2]; //приёмник.length; mov ESI, [ESP + LASTPARAM + 4*1]; //src.ptr; movd MM3, EAX; // numbits = биты to shift left xor EAX, 63; align 16; inc EAX; movd MM4, EAX ; // 64-numbits = биты to shift right // Get the return value преобр_в EAX and EAX, 31; // EAX = 32-numbits movd MM2, EAX; // 32-numbits movd MM1, [ESI+4*EBX-4]; psrlq MM1, MM2; movd EAX, MM1; // EAX = return value test EBX, 1; jz L_even; L_odd: cmp EBX, 1; jz L_length1; // deal with odd lengths movq MM1, [ESI+4*EBX-8]; psrlq MM1, MM2; movd [EDI +4*EBX-4], MM1; sub EBX, 1; L_even: // It's either singly or doubly even movq MM2, [ESI + 4*EBX - 8]; psllq MM2, MM3; sub EBX, 2; jle L_last; movq MM1, MM2; add EBX, 2; test EBX, 2; jz L_onceeven; sub EBX, 2; // MAIN LOOP -- 128 bytes per iteration L_twiceeven: // here MM2 is the carry movq MM0, [ESI + 4*EBX-8]; psrlq MM0, MM4; movq MM1, [ESI + 4*EBX-8]; psllq MM1, MM3; por MM2, MM0; movq [EDI +4*EBX], MM2; L_onceeven: // here MM1 is the carry movq MM0, [ESI + 4*EBX-16]; psrlq MM0, MM4; movq MM2, [ESI + 4*EBX-16]; por MM1, MM0; movq [EDI +4*EBX-8], MM1; psllq MM2, MM3; sub EBX, 4; jg L_twiceeven; L_last: movq [EDI +4*EBX], MM2; L_alldone: emms; // NOTE: costs 6 cycles on Intel CPUs pop EBX; pop EDI; pop ESI; ret 4*4; L_length1: // length 1 is a special case movd MM1, [ESI]; psllq MM1, MM3; movd [EDI], MM1; jmp L_alldone; } } проц многобайтСдвигП(бцел [] приёмник, бцел [] src, бцел numbits) { enum { LASTPARAM = 4*4 } // 3* pushes + return address. asm { naked; push ESI; push EDI; push EBX; mov EDI, [ESP + LASTPARAM + 4*3]; //приёмник.ptr; mov EBX, [ESP + LASTPARAM + 4*2]; //приёмник.length; align 16; mov ESI, [ESP + LASTPARAM + 4*1]; //src.ptr; lea EDI, [EDI + 4*EBX]; // EDI = end of приёмник lea ESI, [ESI + 4*EBX]; // ESI = end of src neg EBX; // count UP to zero. movd MM3, EAX; // numbits = биты to shift right xor EAX, 63; inc EAX; movd MM4, EAX ; // 64-numbits = биты to shift left test EBX, 1; jz L_even; L_odd: // deal with odd lengths and EAX, 31; // EAX = 32-numbits movd MM2, EAX; // 32-numbits cmp EBX, -1; jz L_length1; movq MM0, [ESI+4*EBX]; psrlq MM0, MM3; movd [EDI +4*EBX], MM0; add EBX, 1; L_even: movq MM2, [ESI + 4*EBX]; psrlq MM2, MM3; movq MM1, MM2; add EBX, 4; cmp EBX, -2+4; jz L_last; // It's either singly or doubly even sub EBX, 2; test EBX, 2; jnz L_onceeven; add EBX, 2; // MAIN LOOP -- 128 bytes per iteration L_twiceeven: // here MM2 is the carry movq MM0, [ESI + 4*EBX-8]; psllq MM0, MM4; movq MM1, [ESI + 4*EBX-8]; psrlq MM1, MM3; por MM2, MM0; movq [EDI +4*EBX-16], MM2; L_onceeven: // here MM1 is the carry movq MM0, [ESI + 4*EBX]; psllq MM0, MM4; movq MM2, [ESI + 4*EBX]; por MM1, MM0; movq [EDI +4*EBX-8], MM1; psrlq MM2, MM3; add EBX, 4; jl L_twiceeven; L_last: movq [EDI +4*EBX-16], MM2; L_alldone: emms; // NOTE: costs 6 cycles on Intel CPUs pop EBX; pop EDI; pop ESI; ret 4*4; L_length1: // length 1 is a special case movd MM1, [ESI+4*EBX]; psrlq MM1, MM3; movd [EDI +4*EBX], MM1; jmp L_alldone; } } /** приёмник[#] = src[#] >> numbits * numbits must be in the range 1..31 */ проц многобайтСдвигПБезММХ(бцел [] приёмник, бцел [] src, бцел numbits) { // Timing: Optimal for P6 семейство. // 2.0 cycles/цел on PPro..PM (limited by execution порт p0) // Terrible performance on AMD64, which есть 7 cycles for SHRD!! enum { LASTPARAM = 4*4 } // 3* pushes + return address. asm { naked; push ESI; push EDI; push EBX; mov EDI, [ESP + LASTPARAM + 4*3]; //приёмник.ptr; mov EBX, [ESP + LASTPARAM + 4*2]; //приёмник.length; mov ESI, [ESP + LASTPARAM + 4*1]; //src.ptr; mov ECX, EAX; // numbits; lea EDI, [EDI + 4*EBX]; // EDI = end of приёмник lea ESI, [ESI + 4*EBX]; // ESI = end of src neg EBX; // count UP to zero. mov EAX, [ESI + 4*EBX]; cmp EBX, -1; jz L_last; mov EDX, [ESI + 4*EBX]; test EBX, 1; jz L_odd; add EBX, 1; L_even: mov EDX, [ ESI + 4*EBX]; shrd EAX, EDX, CL; mov [-4 + EDI+4*EBX], EAX; L_odd: mov EAX, [4 + ESI + 4*EBX]; shrd EDX, EAX, CL; mov [EDI + 4*EBX], EDX; add EBX, 2; jl L_even; L_last: shr EAX, CL; mov [-4 + EDI], EAX; pop EBX; pop EDI; pop ESI; ret 4*4; } } debug (UnitTest) { unittest { бцел [] aa = [0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE]; многобайтСдвигП(aa[0..$-1], aa, 4); assert(aa[0] == 0x6122_2222 && aa[1]==0xA455_5555 && aa[2]==0xD899_9999 && aa[3]==0x0BCC_CCCC); aa = [0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE]; многобайтСдвигП(aa[2..$-1], aa[2..$-1], 4); assert(aa[0] == 0x1222_2223 && aa[1]==0x4555_5556 && aa[2]==0xD899_9999 && aa[3]==0x0BCC_CCCC); aa = [0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE]; многобайтСдвигП(aa[0..$-2], aa, 4); assert(aa[1]==0xA455_5555 && aa[2]==0x0899_9999); assert(aa[0]==0x6122_2222); assert(aa[3]==0xBCCC_CCCD); aa = [0xF0FF_FFFF, 0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE]; бцел r = многобайтСдвигЛ(aa[2..4], aa[2..4], 4); assert(aa[0] == 0xF0FF_FFFF && aa[1]==0x1222_2223 && aa[2]==0x5555_5560 && aa[3]==0x9999_99A4 && aa[4]==0xBCCC_CCCD); assert(r==8); aa = [0xF0FF_FFFF, 0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE]; r = многобайтСдвигЛ(aa[1..4], aa[1..4], 4); assert(aa[0] == 0xF0FF_FFFF && aa[2]==0x5555_5561); assert(aa[3]==0x9999_99A4 && aa[4]==0xBCCC_CCCD); assert(r==8); assert(aa[1]==0x2222_2230); aa = [0xF0FF_FFFF, 0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE]; r = многобайтСдвигЛ(aa[0..4], aa[1..5], 31); } } /** приёмник[#] = src[#] * множитель + carry. * Returns carry. */ бцел многобайтУмнож(бцел[] приёмник, бцел[] src, бцел множитель, бцел carry) { // Timing: definitely not optimal. // Pentium M: 5.0 cycles/operation, есть 3 resource stalls/iteration // Fastest implementation найдено was 4.6 cycles/op, but not worth the complexity. enum { LASTPARAM = 4*4 } // 4* pushes + return address. // We'll use p2 (load unit) instead of the overworked p0 or p1 (ALU units) // when initializing variables to zero. version(D_PIC) { enum { zero = 0 } } else { static цел zero = 0; } asm { naked; push ESI; push EDI; push EBX; mov EDI, [ESP + LASTPARAM + 4*4]; // приёмник.ptr mov EBX, [ESP + LASTPARAM + 4*3]; // приёмник.length mov ESI, [ESP + LASTPARAM + 4*2]; // src.ptr align 16; lea EDI, [EDI + 4*EBX]; // EDI = end of приёмник lea ESI, [ESI + 4*EBX]; // ESI = end of src mov ECX, EAX; // [carry]; -- последний param is in EAX. neg EBX; // count UP to zero. test EBX, 1; jnz L_odd; add EBX, 1; L1: mov EAX, [-4 + ESI + 4*EBX]; mul int ptr [ESP+LASTPARAM]; //[множитель]; add EAX, ECX; mov ECX, zero; mov [-4+EDI + 4*EBX], EAX; adc ECX, EDX; L_odd: mov EAX, [ESI + 4*EBX]; // p2 mul int ptr [ESP+LASTPARAM]; //[множитель]; // p0*3, add EAX, ECX; mov ECX, zero; adc ECX, EDX; mov [EDI + 4*EBX], EAX; add EBX, 2; jl L1; mov EAX, ECX; // get final carry pop EBX; pop EDI; pop ESI; ret 5*4; } } debug (UnitTest) { unittest { бцел [] aa = [0xF0FF_FFFF, 0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE]; многобайтУмнож(aa[1..4], aa[1..4], 16, 0); assert(aa[0] == 0xF0FF_FFFF && aa[1] == 0x2222_2230 && aa[2]==0x5555_5561 && aa[3]==0x9999_99A4 && aa[4]==0x0BCCC_CCCD); } } // The inner multИПly-and-add loop, together with the Even entry точка. // MultИПles by M_ADDRESS which should be "ESP+LASTPARAM" or "ESP". OP must be "add" or "sub" // This is the most time-critical код in the BigInt library. // It is used by Всё MulAdd, multИПlyAccumulate, and triangleAccumulate сим [] асмУмножьДоб_внутрцикл(сим [] OP, сим [] M_ADDRESS) { // The bottlenecks in this код are extremely complicated. The MUL, ADD, and ADC // need 4 cycles on each of the ALUs units p0 and p1. So we use memory load // (unit p2) for initializing registers to zero. // There are also dependencies between the instructions, and we run up against the // ROB-read limit (can only read 2 registers per cycle). // We also need the число of uops in the loop to be a multИПle of 3. // The only available execution unit for this is p3 (memory write). Unfortunately we can't do that // if Position-Independent Code is required. // Register usage // ESI = end of src // EDI = end of приёмник // EBX = index. Counts up to zero (in steps of 2). // EDX:EAX = черновик, used in multИПly. // ECX = carry1. // EBP = carry2. // ESP = points to the множитель. // The first member of 'приёмник' which will be modified is [EDI+4*EBX]. // EAX must already contain the first member of 'src', [ESI+4*EBX]. version(D_PIC) { bool using_PIC = true; } else { bool using_PIC=false; } return "asm { // Entry точка for even length add EBX, 1; mov EBP, ECX; // carry mul int ptr [" ~ M_ADDRESS ~ "]; // M mov ECX, 0; add EBP, EAX; mov EAX, [ESI+4*EBX]; adc ECX, EDX; mul int ptr [" ~ M_ADDRESS ~ "]; // M " ~ OP ~ " [-4+EDI+4*EBX], EBP; mov EBP, zero; adc ECX, EAX; mov EAX, [4+ESI+4*EBX]; adc EBP, EDX; add EBX, 2; jnl L_done; L1: mul int ptr [" ~ M_ADDRESS ~ "]; " ~ OP ~ " [-8+EDI+4*EBX], ECX; adc EBP, EAX; mov ECX, zero; mov EAX, [ESI+4*EBX]; adc ECX, EDX; " ~ (using_PIC ? "" : " mov storagenop, EDX; ") // make #uops in loop a multИПle of 3, can't do this in PIC режим. ~ " mul int ptr [" ~ M_ADDRESS ~ "]; " ~ OP ~ " [-4+EDI+4*EBX], EBP; mov EBP, zero; adc ECX, EAX; mov EAX, [4+ESI+4*EBX]; adc EBP, EDX; add EBX, 2; jl L1; L_done: " ~ OP ~ " [-8+EDI+4*EBX], ECX; adc EBP, 0; }"; // final carry is now in EBP } сим [] асмУмножьДоб_вх_одд(сим [] OP, сим [] M_ADDRESS) { return "asm { mul int ptr [" ~M_ADDRESS ~"]; mov EBP, zero; add ECX, EAX; mov EAX, [4+ESI+4*EBX]; adc EBP, EDX; add EBX, 2; jl L1; jmp L_done; }"; } /** * приёмник[#] += src[#] * множитель OP carry(0..FFFF_FFFF). * where op == '+' or '-' * Returns carry out of MSB (0..FFFF_FFFF). */ бцел многобайтУмножПрибавь(сим op)(бцел [] приёмник, бцел[] src, бцел множитель, бцел carry) { // Timing: This is the most time-critical bignum function. // Pentium M: 5.4 cycles/operation, still есть 2 resource stalls + 1load block/iteration // The main loop is pИПelined and unrolled by 2, // so entry to the loop is also complicated. // Register usage // EDX:EAX = multИПly // EBX = counter // ECX = carry1 // EBP = carry2 // EDI = приёмник // ESI = src const сим [] OP = (op=='+')? "add" : "sub"; version(D_PIC) { enum { zero = 0 } } else { // use p2 (load unit) instead of the overworked p0 or p1 (ALU units) // when initializing registers to zero. static цел zero = 0; // use p3/p4 units static цел storagenop; // write-only } enum { LASTPARAM = 5*4 } // 4* pushes + return address. asm { naked; push ESI; push EDI; push EBX; push EBP; mov EDI, [ESP + LASTPARAM + 4*4]; // приёмник.ptr mov EBX, [ESP + LASTPARAM + 4*3]; // приёмник.length align 16; nop; mov ESI, [ESP + LASTPARAM + 4*2]; // src.ptr lea EDI, [EDI + 4*EBX]; // EDI = end of приёмник lea ESI, [ESI + 4*EBX]; // ESI = end of src mov EBP, 0; mov ECX, EAX; // ECX = input carry. neg EBX; // count UP to zero. mov EAX, [ESI+4*EBX]; test EBX, 1; jnz L_enter_odd; } // Main loop, with entry точка for even length mixin(асмУмножьДоб_внутрцикл(OP, "ESP+LASTPARAM")); asm { mov EAX, EBP; // get final carry pop EBP; pop EBX; pop EDI; pop ESI; ret 5*4; } L_enter_odd: mixin(асмУмножьДоб_вх_одд(OP, "ESP+LASTPARAM")); } debug (UnitTest) { unittest { бцел [] aa = [0xF0FF_FFFF, 0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE]; бцел [] bb = [0x1234_1234, 0xF0F0_F0F0, 0x00C0_C0C0, 0xF0F0_F0F0, 0xC0C0_C0C0]; многобайтУмножПрибавь!('+')(bb[1..$-1], aa[1..$-2], 16, 5); assert(bb[0] == 0x1234_1234 && bb[4] == 0xC0C0_C0C0); assert(bb[1] == 0x2222_2230 + 0xF0F0_F0F0+5 && bb[2] == 0x5555_5561+0x00C0_C0C0+1 && bb[3] == 0x9999_99A4+0xF0F0_F0F0 ); } } /** Sets result[#] = result[0..left.length] + left[#] * right[#] It is defined in this way to allow cache-efficient multИПlication. This function is equivalent to: ---- for (цел i = 0; i< right.length; ++i) { приёмник[left.length + i] = многобайтУмножПрибавь(приёмник[i..left.length+i], left, right[i], 0); } ---- */ проц многобайтУмножАккум(бцел [] приёмник, бцел[] left, бцел [] right) { // Register usage // EDX:EAX = used in multИПly // EBX = index // ECX = carry1 // EBP = carry2 // EDI = end of приёмник for this пароль through the loop. Index for outer loop. // ESI = end of left. never changes // [ESP] = M = right[i] = множитель for this пароль through the loop. // right.length is changed преобр_в приёмник.ptr+приёмник.length version(D_PIC) { enum { zero = 0 } } else { // use p2 (load unit) instead of the overworked p0 or p1 (ALU units) // when initializing registers to zero. static цел zero = 0; // use p3/p4 units static цел storagenop; // write-only } enum { LASTPARAM = 6*4 } // 4* pushes + local + return address. asm { naked; push ESI; push EDI; align 16; push EBX; push EBP; push EAX; // local переменная M mov EDI, [ESP + LASTPARAM + 4*5]; // приёмник.ptr mov EBX, [ESP + LASTPARAM + 4*2]; // left.length mov ESI, [ESP + LASTPARAM + 4*3]; // left.ptr lea EDI, [EDI + 4*EBX]; // EDI = end of приёмник for first пароль mov EAX, [ESP + LASTPARAM + 4*0]; // right.length lea EAX, [EDI + 4*EAX]; mov [ESP + LASTPARAM + 4*0], EAX; // последний value for EDI lea ESI, [ESI + 4*EBX]; // ESI = end of left mov EAX, [ESP + LASTPARAM + 4*1]; // right.ptr mov EAX, [EAX]; mov [ESP], EAX; // M outer_loop: mov EBP, 0; mov ECX, 0; // ECX = input carry. neg EBX; // count UP to zero. mov EAX, [ESI+4*EBX]; test EBX, 1; jnz L_enter_odd; } // -- Inner loop, with even entry точка mixin(асмУмножьДоб_внутрцикл("add", "ESP")); asm { mov [-4+EDI+4*EBX], EBP; add EDI, 4; cmp EDI, [ESP + LASTPARAM + 4*0]; // is EDI = &приёмник[$]? jz outer_done; mov EAX, [ESP + LASTPARAM + 4*1]; // right.ptr mov EAX, [EAX+4]; // get new M mov [ESP], EAX; // save new M add int ptr [ESP + LASTPARAM + 4*1], 4; // right.ptr mov EBX, [ESP + LASTPARAM + 4*2]; // left.length jmp outer_loop; outer_done: pop EAX; pop EBP; pop EBX; pop EDI; pop ESI; ret 6*4; } L_enter_odd: mixin(асмУмножьДоб_вх_одд("add", "ESP")); } /** приёмник[#] /= divisor. * overflow is the начальное remainder, and must be in the range 0..divisor-1. * divisor must not be a power of 2 (use right shift for that case; * A division by zero will occur if divisor is a power of 2). * Returns the final remainder * * Based on public домен код by Eric Bainville. * (http://www.bealto.com/) Used with permission. */ бцел многобайтПрисвойДеление(бцел [] приёмник, бцел divisor, бцел overflow) { // Timing: limited by a horrible dependency chain. // Pentium M: 18 cycles/op, 8 resource stalls/op. // EAX, EDX = черновик, used by MUL // EDI = приёмник // CL = shift // ESI = quotient // EBX = remainderhi // EBP = remainderlo // [ESP-4] = mask // [ESP] = kinv (2^64 /divisor) enum { LASTPARAM = 5*4 } // 4* pushes + return address. enum { LOCALS = 2*4} // MASK, KINV asm { naked; push ESI; push EDI; push EBX; push EBP; mov EDI, [ESP + LASTPARAM + 4*2]; // приёмник.ptr mov EBX, [ESP + LASTPARAM + 4*1]; // приёмник.length // Loop from msb to lsb lea EDI, [EDI + 4*EBX]; mov EBP, EAX; // rem is the input remainder, in 0..divisor-1 // Build the pseudo-inverse of divisor k: 2^64/k // First determine the shift in ecx to get the max число of биты in kinv xor ECX, ECX; mov EAX, [ESP + LASTPARAM]; //divisor; mov EDX, 1; kinv1: inc ECX; ror EDX, 1; shl EAX, 1; jnc kinv1; dec ECX; // Here, ecx is a left shift moving the msb of k to bit 32 mov EAX, 1; shl EAX, CL; dec EAX; ror EAX, CL ; //ecx биты at msb push EAX; // MASK // Then divопрe 2^(32+cx) by divisor (edx already ok) xor EAX, EAX; div int ptr [ESP + LASTPARAM + LOCALS-4*1]; //divisor; push EAX; // kinv align 16; L2: // Get 32 биты of quotient approx, multИПlying // most significant word of (rem*2^32+input) mov EAX, [ESP+4]; //MASK; and EAX, [EDI - 4]; or EAX, EBP; rol EAX, CL; mov EBX, EBP; mov EBP, [EDI - 4]; mul int ptr [ESP]; //KINV; shl EAX, 1; rcl EDX, 1; // MultИПly by k and вычти to get remainder // Subtraction must be done on two words mov EAX, EDX; mov ESI, EDX; // quot = high word mul int ptr [ESP + LASTPARAM+LOCALS]; //divisor; sub EBP, EAX; sbb EBX, EDX; jz Lb; // high word is 0, goto исправь on single word // Adjust quotient and remainder on two words Ld: inc ESI; sub EBP, [ESP + LASTPARAM+LOCALS]; //divisor; sbb EBX, 0; jnz Ld; // Adjust quotient and remainder on single word Lb: cmp EBP, [ESP + LASTPARAM+LOCALS]; //divisor; jc Lc; // rem in 0..divisor-1, ОК sub EBP, [ESP + LASTPARAM+LOCALS]; //divisor; inc ESI; jmp Lb; // Store result Lc: mov [EDI - 4], ESI; lea EDI, [EDI - 4]; dec int ptr [ESP + LASTPARAM + 4*1+LOCALS]; // len jnz L2; pop EAX; // discard kinv pop EAX; // discard mask mov EAX, EBP; // return final remainder pop EBP; pop EBX; pop EDI; pop ESI; ret 3*4; } } debug (UnitTest) { unittest { бцел [] aa = new бцел[101]; for (цел i=0; i<aa.length; ++i) aa[i] = 0x8765_4321 * (i+3); бцел overflow = многобайтУмнож(aa, aa, 0x8EFD_FCFB, 0x33FF_7461); бцел r = многобайтПрисвойДеление(aa, 0x8EFD_FCFB, overflow); for (цел i=0; i<aa.length-1; ++i) assert(aa[i] == 0x8765_4321 * (i+3)); assert(r==0x33FF_7461); } } // Набор приёмник[2*i..2*i+1]+=src[i]*src[i] проц многобайтПрибавьДиагПлощ(бцел [] приёмник, бцел [] src) { /* Unlike mulAdd, the carry is only 1 bit, since FFFF*FFFF+FFFF_FFFF = 1_0000_0000. Note also that on the последний iteration, no carry can occur. As for multibyteAdd, we save & restore carry flag through the loop. The timing is entirely dictated by the dependency chain. We could improve it by moving the mov EAX after the adc [EDI], EAX. Probably not worthwhile. */ enum { LASTPARAM = 4*5 } // 4* pushes + return address. asm { naked; push ESI; push EDI; push EBX; push ECX; mov EDI, [ESP + LASTPARAM + 4*3]; //приёмник.ptr; mov EBX, [ESP + LASTPARAM + 4*0]; //src.length; mov ESI, [ESP + LASTPARAM + 4*1]; //src.ptr; lea EDI, [EDI + 8*EBX]; // EDI = end of приёмник lea ESI, [ESI + 4*EBX]; // ESI = end of src neg EBX; // count UP to zero. xor ECX, ECX; // начальное carry = 0. L1: mov EAX, [ESI + 4*EBX]; mul EAX, EAX; shr CL, 1; // get carry adc [EDI + 8*EBX], EAX; adc [EDI + 8*EBX + 4], EDX; setc CL; // save carry inc EBX; jnz L1; pop ECX; pop EBX; pop EDI; pop ESI; ret 4*4; } } debug (UnitTest) { unittest { бцел [] aa = new бцел[13]; бцел [] bb = new бцел[6]; for (цел i=0; i<aa.length; ++i) aa[i] = 0x8000_0000; for (цел i=0; i<bb.length; ++i) bb[i] = i; aa[$-1]= 7; многобайтПрибавьДиагПлощ(aa[0..$-1], bb); assert(aa[$-1]==7); for (цел i=0; i<bb.length; ++i) { assert(aa[2*i]==0x8000_0000+i*i); assert(aa[2*i+1]==0x8000_0000); } } } проц многобайтПрямоугАккумД(бцел[] приёмник, бцел[] x) { for (цел i = 0; i < x.length-3; ++i) { приёмник[i+x.length] = многобайтУмножПрибавь!('+')( приёмник[i+i+1 .. i+x.length], x[i+1..$], x[i], 0); } ulong c = cast(ulong)(x[$-3]) * x[$-2] + приёмник[$-5]; приёмник[$-5] = cast(бцел)c; c >>= 32; c += cast(ulong)(x[$-3]) * x[$-1] + приёмник[$-4]; приёмник[$-4] = cast(бцел)c; c >>= 32; length2: c += cast(ulong)(x[$-2]) * x[$-1]; приёмник[$-3] = cast(бцел)c; c >>= 32; приёмник[$-2] = cast(бцел)c; } //приёмник += src[0]*src[1...$] + src[1]*src[2..$] + ... + src[$-3]*src[$-2..$]+ src[$-2]*src[$-1] // assert(приёмник.length = src.length*2); // assert(src.length >= 3); проц многобайтПрямоугАккумАсм(бцел[] приёмник, бцел[] src) { // Register usage // EDX:EAX = used in multИПly // EBX = index // ECX = carry1 // EBP = carry2 // EDI = end of приёмник for this пароль through the loop. Index for outer loop. // ESI = end of src. never changes // [ESP] = M = src[i] = множитель for this пароль through the loop. // приёмник.length is changed преобр_в приёмник.ptr+приёмник.length version(D_PIC) { enum { zero = 0 } } else { // use p2 (load unit) instead of the overworked p0 or p1 (ALU units) // when initializing registers to zero. static цел zero = 0; // use p3/p4 units static цел storagenop; // write-only } enum { LASTPARAM = 6*4 } // 4* pushes + local + return address. asm { naked; push ESI; push EDI; align 16; push EBX; push EBP; push EAX; // local переменная M= src[i] mov EDI, [ESP + LASTPARAM + 4*3]; // приёмник.ptr mov EBX, [ESP + LASTPARAM + 4*0]; // src.length mov ESI, [ESP + LASTPARAM + 4*1]; // src.ptr lea ESI, [ESI + 4*EBX]; // ESI = end of left add int ptr [ESP + LASTPARAM + 4*1], 4; // src.ptr, used for getting M // local переменная [ESP + LASTPARAM + 4*2] = последний value for EDI lea EDI, [EDI + 4*EBX]; // EDI = end of приёмник for first пароль lea EAX, [EDI + 4*EBX-3*4]; // up to src.length - 3 mov [ESP + LASTPARAM + 4*2], EAX; // последний value for EDI = &приёмник[src.length*2 -3] cmp EBX, 3; jz length_is_3; // We start at src[1], not src[0]. dec EBX; mov [ESP + LASTPARAM + 4*0], EBX; outer_loop: mov EBX, [ESP + LASTPARAM + 4*0]; // src.length mov EBP, 0; mov ECX, 0; // ECX = input carry. dec [ESP + LASTPARAM + 4*0]; // Next time, the length will be shorter by 1. neg EBX; // count UP to zero. mov EAX, [ESI + 4*EBX - 4*1]; // get new M mov [ESP], EAX; // save new M mov EAX, [ESI+4*EBX]; test EBX, 1; jnz L_enter_odd; } // -- Inner loop, with even entry точка mixin(асмУмножьДоб_внутрцикл("add", "ESP")); asm { mov [-4+EDI+4*EBX], EBP; add EDI, 4; cmp EDI, [ESP + LASTPARAM + 4*2]; // is EDI = &приёмник[$-3]? jnz outer_loop; length_is_3: mov EAX, [ESI - 4*3]; mul EAX, [ESI - 4*2]; mov ECX, 0; add [EDI-2*4], EAX; // ECX:приёмник[$-5] += x[$-3] * x[$-2] adc ECX, EDX; mov EAX, [ESI - 4*3]; mul EAX, [ESI - 4*1]; // x[$-3] * x[$-1] add EAX, ECX; mov ECX, 0; adc EDX, 0; // now EDX: EAX = c + x[$-3] * x[$-1] add [EDI-1*4], EAX; // ECX:приёмник[$-4] += (EDX:EAX) adc ECX, EDX; // ECX holds приёмник[$-3], it acts as carry for the последний row // do length==2 mov EAX, [ESI - 4*2]; mul EAX, [ESI - 4*1]; add ECX, EAX; adc EDX, 0; mov [EDI - 0*4], ECX; // приёмник[$-2:$-3] = c + x[$-2] * x[$-1]; mov [EDI + 1*4], EDX; pop EAX; pop EBP; pop EBX; pop EDI; pop ESI; ret 4*4; } L_enter_odd: mixin(асмУмножьДоб_вх_одд("add", "ESP")); } debug (UnitTest) { unittest { бцел [] aa = new бцел[200]; бцел [] a = aa[0..100]; бцел [] b = new бцел [100]; aa[] = 761; a[] = 0; b[] = 0; a[3] = 6; b[0]=1; b[1] = 17; b[50..100]=78; многобайтПрямоугАккумАсм(a, b[0..50]); бцел [] c = new бцел[100]; c[] = 0; c[1] = 17; c[3] = 6; assert(a[]==c[]); assert(a[0]==0); aa[] = 0xFFFF_FFFF; a[] = 0; b[] = 0; b[0]= 0xbf6a1f01; b[1]= 0x6e38ed64; b[2]= 0xdaa797ed; b[3] = 0; многобайтПрямоугАккумАсм(a[0..8], b[0..4]); assert(a[1]==0x3a600964); assert(a[2]==0x339974f6); assert(a[3]==0x46736fce); assert(a[4]==0x5e24a2b4); b[3] = 0xe93ff9f4; b[4] = 0x184f03; a[]=0; многобайтПрямоугАккумАсм(a[0..14], b[0..7]); assert(a[3]==0x79fff5c2); assert(a[4]==0xcf384241); assert(a[5]== 0x4a17fc8); assert(a[6]==0x4d549025); } } проц многобайтПлощадь(БольшЦифра[] result, БольшЦифра [] x) { if (x.length < 4) { // Special cases, not worth doing triangular. result[x.length] = многобайтУмнож(result[0..x.length], x, x[0], 0); многобайтУмножАккум(result[1..$], x, x[1..$]); return; } // Do half a square multИПly. // приёмник += src[0]*src[1...$] + src[1]*src[2..$] + ... + src[$-3]*src[$-2..$]+ src[$-2]*src[$-1] result[x.length] = многобайтУмнож!('+')(result[1 .. x.length], x[1..$], x[0], 0); многобайтПрямоугАккумАсм(result[2..$], x[1..$]); // MultИПly by 2 result[$-1] = многобайтСдвигЛБезММХ(result[1..$-1], result[1..$-1], 1); // And add the diagonal elements result[0] = 0; многобайтПрибавьДиагПлощ(result, x); } version(TangoPerformanceTest) { import rt.core.stdc.stdio; цел clock() { asm { push EBX; xor EAX, EAX; cpuid; pop EBX; rdtsc; } } бцел [2200] X1; бцел [2200] Y1; бцел [4000] Z1; проц testPerformance() { // The performance results at the top of this file were obtained using // a Windows device driver to access the CPU performance counters. // The код below is less accurate but ещё wопрely usable. // The value for division is quite inconsistent. for (цел i=0; i<X1.length; ++i) { X1[i]=i; Y1[i]=i; Z1[i]=i; } цел t, t0; многобайтСдвигЛ(Z1[0..2000], X1[0..2000], 7); t0 = clock(); многобайтСдвигЛ(Z1[0..1000], X1[0..1000], 7); t = clock(); многобайтСдвигЛ(Z1[0..2000], X1[0..2000], 7); auto shltime = (clock() - t) - (t - t0); t0 = clock(); многобайтСдвигП(Z1[2..1002], X1[4..1004], 13); t = clock(); многобайтСдвигП(Z1[2..2002], X1[4..2004], 13); auto shrtime = (clock() - t) - (t - t0); t0 = clock(); многобайтПрибавОтним!('+')(Z1[0..1000], X1[0..1000], Y1[0..1000], 0); t = clock(); многобайтПрибавОтним!('+')(Z1[0..2000], X1[0..2000], Y1[0..2000], 0); auto addtime = (clock() - t) - (t-t0); t0 = clock(); многобайтУмнож(Z1[0..1000], X1[0..1000], 7, 0); t = clock(); многобайтУмнож(Z1[0..2000], X1[0..2000], 7, 0); auto multime = (clock() - t) - (t - t0); многобайтУмножПрибавь!('+')(Z1[0..2000], X1[0..2000], 217, 0); t0 = clock(); многобайтУмножПрибавь!('+')(Z1[0..1000], X1[0..1000], 217, 0); t = clock(); многобайтУмножПрибавь!('+')(Z1[0..2000], X1[0..2000], 217, 0); auto muladdtime = (clock() - t) - (t - t0); многобайтУмножАккум(Z1[0..64], X1[0..32], Y1[0..32]); t = clock(); многобайтУмножАккум(Z1[0..64], X1[0..32], Y1[0..32]); auto accumtime = clock() - t; t0 = clock(); многобайтПрисвойДеление(Z1[0..2000], 217, 0); t = clock(); многобайтПрисвойДеление(Z1[0..1000], 37, 0); auto divtime = (t - t0) - (clock() - t); t= clock(); многобайтПлощадь(Z1[0..64], X1[0..32]); auto squaretime = clock() - t; printf("-- BigInt asm performance (cycles/цел) --\n"); printf("Add: %.2f\n", addtime/1000.0); printf("Shl: %.2f\n", shltime/1000.0); printf("Shr: %.2f\n", shrtime/1000.0); printf("Mul: %.2f\n", multime/1000.0); printf("MulAdd: %.2f\n", muladdtime/1000.0); printf("Div: %.2f\n", divtime/1000.0); printf("MulAccum32: %.2f*n*n (total %d)\n", accumtime/(32.0*32.0), accumtime); printf("Square32: %.2f*n*n (total %d)\n\n", squaretime/(32.0*32.0), squaretime); } static this() { testPerformance(); } } } // version(D_InlineAsm_X86)
D